Surface NMR forward modelling
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. /* This file is part of Lemma, a geophysical modelling and inversion API.
  2. * More information is available at http://lemmasoftware.org
  3. */
  4. /* This Source Code Form is subject to the terms of the Mozilla Public
  5. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  7. */
  8. /**
  9. * @file
  10. * @date 11/11/2016 01:47:25 PM
  11. * @author Trevor Irons (ti)
  12. * @email tirons@egi.utah.edu
  13. * @copyright Copyright (c) 2016, University of Utah
  14. * @copyright Copyright (c) 2016, Lemma Software, LLC
  15. * @copyright Copyright (c) 2008, Colorado School of Mines
  16. */
  17. #include "KernelV0.h"
  18. #include "FieldPoints.h"
  19. namespace Lemma {
  20. // ==================== FRIEND METHODS =====================
  21. std::ostream &operator << (std::ostream &stream, const KernelV0 &ob) {
  22. stream << ob.Serialize() << "\n---\n"; // End of doc ---
  23. return stream;
  24. }
  25. // ==================== LIFECYCLE =======================
  26. //--------------------------------------------------------------------------------------
  27. // Class: KernelV0
  28. // Method: KernelV0
  29. // Description: constructor (locked)
  30. //--------------------------------------------------------------------------------------
  31. KernelV0::KernelV0 (const ctor_key&) : LemmaObject( ) {
  32. } // ----- end of method KernelV0::KernelV0 (constructor) -----
  33. //--------------------------------------------------------------------------------------
  34. // Class: KernelV0
  35. // Method: KernelV0
  36. // Description: DeSerializing constructor (locked)
  37. //--------------------------------------------------------------------------------------
  38. KernelV0::KernelV0 (const YAML::Node& node, const ctor_key&) : LemmaObject(node) {
  39. //node["PulseType"] = "FID";
  40. Larmor = node["Larmor"].as<Real>();
  41. Temperature = node["Temperature"].as<Real>();
  42. tol = node["tol"].as<Real>();
  43. minLevel = node["minLevel"].as<int>();
  44. maxLevel = node["maxLevel"].as<int>();
  45. Taup = node["Taup"].as<Real>();
  46. PulseI = node["PulseI"].as<VectorXr>();
  47. Interfaces = node["Interfaces"].as<VectorXr>();
  48. Size = node["IntegrationSize"].as<Vector3r>();
  49. Origin = node["IntegrationOrigin"].as<Vector3r>();
  50. if (node["SigmaModel"]) {
  51. if (node["SigmaModel"].Tag() == "LayeredEarthEM") {
  52. SigmaModel = LayeredEarthEM::DeSerialize(node["SigmaModel"]);
  53. } else {
  54. SigmaModel = LayeredEarthEM::DeSerialize( YAML::LoadFile( node["SigmaModel"].as<std::string>() ));
  55. }
  56. }
  57. if (node["Coils"]) {
  58. for ( auto coil : node["Coils"] ) {
  59. if ( coil.second.Tag() == "PolygonalWireAntenna" ) {
  60. TxRx[ coil.first.as<std::string>() ] = PolygonalWireAntenna::DeSerialize( coil.second );
  61. } else {
  62. TxRx[ coil.first.as<std::string>() ] =
  63. PolygonalWireAntenna::DeSerialize( YAML::LoadFile(coil.second.as<std::string>()) );
  64. }
  65. }
  66. }
  67. } // ----- end of method KernelV0::KernelV0 (constructor) -----
  68. //--------------------------------------------------------------------------------------
  69. // Class: KernelV0
  70. // Method: NewSP()
  71. // Description: public constructor returing a shared_ptr
  72. //--------------------------------------------------------------------------------------
  73. std::shared_ptr< KernelV0 > KernelV0::NewSP() {
  74. return std::make_shared< KernelV0 >( ctor_key() );
  75. }
  76. //--------------------------------------------------------------------------------------
  77. // Class: KernelV0
  78. // Method: ~KernelV0
  79. // Description: destructor (protected)
  80. //--------------------------------------------------------------------------------------
  81. KernelV0::~KernelV0 () {
  82. } // ----- end of method KernelV0::~KernelV0 (destructor) -----
  83. //--------------------------------------------------------------------------------------
  84. // Class: KernelV0
  85. // Method: Serialize
  86. //--------------------------------------------------------------------------------------
  87. YAML::Node KernelV0::Serialize ( ) const {
  88. YAML::Node node = LemmaObject::Serialize();
  89. node.SetTag( GetName() );
  90. // Coils Transmitters & Receivers
  91. if (!TxRx.empty()) {
  92. for ( auto txm : TxRx) {
  93. node["Coils"][txm.first] = txm.second->Serialize();
  94. }
  95. }
  96. // LayeredEarthEM
  97. if (SigmaModel != nullptr) {
  98. node["SigmaModel"] = SigmaModel->Serialize();
  99. }
  100. node["PulseType"] = "FID";
  101. node["Larmor"] = Larmor;
  102. node["Temperature"] = Temperature;
  103. node["tol"] = tol;
  104. node["minLevel"] = minLevel;
  105. node["maxLevel"] = maxLevel;
  106. node["Taup"] = Taup;
  107. node["PulseI"] = PulseI;
  108. node["Interfaces"] = Interfaces;
  109. node["IntegrationSize"] = Size;
  110. node["IntegrationOrigin"] = Origin;
  111. if (Kern.array().abs().any() > 1e-16) {
  112. for ( int ilay=0; ilay<Interfaces.size()-1; ++ilay ) {
  113. node["K0"]["layer-" + to_string(ilay) ] = static_cast<VectorXcr>(Kern.row(ilay));
  114. }
  115. }
  116. return node;
  117. } // ----- end of method KernelV0::Serialize -----
  118. //--------------------------------------------------------------------------------------
  119. // Class: KernelV0
  120. // Method: DeSerialize
  121. //--------------------------------------------------------------------------------------
  122. std::shared_ptr<KernelV0> KernelV0::DeSerialize ( const YAML::Node& node ) {
  123. if (node.Tag() != "KernelV0" ) {
  124. throw DeSerializeTypeMismatch( "KernelV0", node.Tag());
  125. }
  126. return std::make_shared< KernelV0 > ( node, ctor_key() );
  127. } // ----- end of method KernelV0::DeSerialize -----
  128. //--------------------------------------------------------------------------------------
  129. // Class: KernelV0
  130. // Method: AlignWithAkvoDataset
  131. //--------------------------------------------------------------------------------------
  132. void KernelV0::AlignWithAkvoDataset( const YAML::Node& node ) {
  133. if (node["processed"].as<std::string>().substr(0,4) == "Akvo") {
  134. std::cout << "Akvo file read\n";
  135. std::cout << node["processed"] << std::endl;
  136. }
  137. if (node["pulseType"].as<std::string>() == "FID") {
  138. PulseI = node["Pulse 1"]["current"].as<VectorXr>();
  139. this->SetPulseDuration( node["pulseLength"].as<double>() );
  140. } else {
  141. std::cerr << "Pulse Type " << node["PulseType"] << "is not supported\n";
  142. }
  143. }
  144. //--------------------------------------------------------------------------------------
  145. // Class: KernelV0
  146. // Method: DeSerialize
  147. //--------------------------------------------------------------------------------------
  148. void KernelV0::CalculateK0 (const std::vector< std::string>& Tx,
  149. const std::vector<std::string >& Rx, bool vtkOutput ) {
  150. // Set up
  151. Larmor = SigmaModel->GetMagneticFieldMagnitude()*GAMMA; // in rad 2246.*2.*PI;
  152. // All EM calculations will share same field points
  153. cpoints = FieldPoints::NewSP();
  154. cpoints->SetNumberOfPoints(8);
  155. for (auto tx : Tx) {
  156. // Set up EMEarth
  157. EMEarths[tx] = EMEarth1D::NewSP();
  158. EMEarths[tx]->AttachWireAntenna(TxRx[tx]);
  159. EMEarths[tx]->AttachLayeredEarthEM(SigmaModel);
  160. EMEarths[tx]->AttachFieldPoints( cpoints );
  161. EMEarths[tx]->SetFieldsToCalculate(H);
  162. // TODO query for method, altough with flat antennae, this is fastest
  163. //EMEarths[tx]->SetHankelTransformMethod(FHTKEY201);
  164. EMEarths[tx]->SetHankelTransformMethod(ANDERSON801);
  165. EMEarths[tx]->SetTxRxMode(TX);
  166. TxRx[tx]->SetCurrent(1.);
  167. }
  168. for (auto rx : Rx) {
  169. if (EMEarths.count(rx)) {
  170. EMEarths[rx]->SetTxRxMode(TXRX);
  171. } else {
  172. EMEarths[rx] = EMEarth1D::NewSP();
  173. EMEarths[rx]->AttachWireAntenna(TxRx[rx]);
  174. EMEarths[rx]->AttachLayeredEarthEM(SigmaModel);
  175. EMEarths[rx]->AttachFieldPoints( cpoints );
  176. EMEarths[rx]->SetFieldsToCalculate(H);
  177. // TODO query for method, altough with flat antennae, this is fastest
  178. //EMEarths[rx]->SetHankelTransformMethod(FHTKEY201);
  179. EMEarths[rx]->SetHankelTransformMethod(ANDERSON801);
  180. EMEarths[rx]->SetTxRxMode(RX);
  181. TxRx[rx]->SetCurrent(1.);
  182. }
  183. }
  184. std::cout << "Calculating K0 kernel\n";
  185. Kern = MatrixXcr::Zero( Interfaces.size()-1, PulseI.size() );
  186. for (ilay=0; ilay<Interfaces.size()-1; ++ilay) {
  187. std::cout << "Layer " << ilay << "\tfrom " << Interfaces(ilay) <<" to "
  188. << Interfaces(ilay+1) << std::endl;
  189. Size(2) = Interfaces(ilay+1) - Interfaces(ilay);
  190. Origin(2) = Interfaces(ilay);
  191. IntegrateOnOctreeGrid( vtkOutput );
  192. }
  193. std::cout << "\nFinished KERNEL\n";
  194. }
  195. //--------------------------------------------------------------------------------------
  196. // Class: KernelV0
  197. // Method: IntegrateOnOctreeGrid
  198. //--------------------------------------------------------------------------------------
  199. void KernelV0::IntegrateOnOctreeGrid( bool vtkOutput) {
  200. Vector3r cpos = Origin + Size/2.;
  201. VOLSUM = 0;
  202. nleaves = 0;
  203. if (!vtkOutput) {
  204. EvaluateKids( Size, 0, cpos, VectorXcr::Ones(PulseI.size()) );
  205. } else {
  206. #ifdef LEMMAUSEVTK
  207. vtkHyperOctree* oct = vtkHyperOctree::New();
  208. oct->SetDimension(3);
  209. oct->SetOrigin( Origin(0), Origin(1), Origin(2) );
  210. oct->SetSize( Size(0), Size(1), Size(2) );
  211. vtkHyperOctreeCursor* curse = oct->NewCellCursor();
  212. curse->ToRoot();
  213. EvaluateKids2( Size, 0, cpos, VectorXcr::Ones(PulseI.size()), oct, curse );
  214. for (int iq=0; iq<PulseI.size(); ++iq) {
  215. // Fill in leaf data
  216. vtkDoubleArray* kr = vtkDoubleArray::New();
  217. kr->SetNumberOfComponents(1);
  218. kr->SetName("Re($\\mathcal{K}_0$)");
  219. kr->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  220. vtkDoubleArray* ki = vtkDoubleArray::New();
  221. ki->SetNumberOfComponents(1);
  222. ki->SetName("Im($\\mathcal{K}_0$)");
  223. ki->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  224. vtkDoubleArray* km = vtkDoubleArray::New();
  225. km->SetNumberOfComponents(1);
  226. km->SetName("mod($\\mathcal{K}_0$)");
  227. km->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  228. vtkIntArray* kid = vtkIntArray::New();
  229. kid->SetNumberOfComponents(1);
  230. kid->SetName("ID");
  231. kid->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  232. vtkIntArray* kerr = vtkIntArray::New();
  233. kerr->SetNumberOfComponents(1);
  234. kerr->SetName("err");
  235. kerr->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  236. // Ht field
  237. vtkDoubleArray* htr = vtkDoubleArray::New();
  238. htr->SetNumberOfComponents(3);
  239. htr->SetName("Re($\\mathbf{\\mathcal{H}}_T$)");
  240. htr->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  241. vtkDoubleArray* hti = vtkDoubleArray::New();
  242. hti->SetNumberOfComponents(3);
  243. hti->SetName("Im($\\mathbf{\\mathcal{H}}_T$)");
  244. hti->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  245. // Hr field
  246. vtkDoubleArray* hrr = vtkDoubleArray::New();
  247. hrr->SetNumberOfComponents(3);
  248. hrr->SetName("Re($\\mathbf{\\mathcal{H}}_R$)");
  249. hrr->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  250. vtkDoubleArray* hri = vtkDoubleArray::New();
  251. hri->SetNumberOfComponents(3);
  252. hri->SetName("Im($\\mathbf{\\mathcal{H}}_R$)");
  253. hri->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  254. //Real LeafVol(0);
  255. for (auto leaf : LeafDict) {
  256. kr->InsertTuple1( leaf.first, std::real(leaf.second(iq)) );
  257. ki->InsertTuple1( leaf.first, std::imag(leaf.second(iq)) );
  258. km->InsertTuple1( leaf.first, std::abs(leaf.second(iq)) );
  259. kid->InsertTuple1( leaf.first, leaf.first );
  260. //LeafVol += std::real(leaf.second);
  261. }
  262. for (auto leaf : LeafHt ) {
  263. htr->InsertTuple( leaf.first, leaf.second.real().data() );
  264. hti->InsertTuple( leaf.first, leaf.second.imag().data() );
  265. }
  266. for (auto leaf : LeafHr ) {
  267. hrr->InsertTuple( leaf.first, leaf.second.real().data() );
  268. hri->InsertTuple( leaf.first, leaf.second.imag().data() );
  269. }
  270. for (auto leaf : LeafDictIdx) {
  271. kerr->InsertTuple1( leaf.first, leaf.second );
  272. }
  273. auto kri = oct->GetLeafData()->AddArray(kr);
  274. auto kii = oct->GetLeafData()->AddArray(ki);
  275. auto kmi = oct->GetLeafData()->AddArray(km);
  276. auto kidi = oct->GetLeafData()->AddArray(kid);
  277. auto keri = oct->GetLeafData()->AddArray(kerr);
  278. auto khtr = oct->GetLeafData()->AddArray(htr);
  279. auto khti = oct->GetLeafData()->AddArray(hti);
  280. auto khrr = oct->GetLeafData()->AddArray(hrr);
  281. auto khri = oct->GetLeafData()->AddArray(hri);
  282. auto write = vtkXMLHyperOctreeWriter::New();
  283. //write.SetDataModeToAscii()
  284. write->SetInputData(oct);
  285. std::string fname = std::string("octree-") + to_string(ilay)
  286. + std::string("-") + to_string(iq) + std::string(".vto");
  287. write->SetFileName(fname.c_str());
  288. write->Write();
  289. write->Delete();
  290. oct->GetLeafData()->RemoveArray( kri );
  291. oct->GetLeafData()->RemoveArray( kii );
  292. oct->GetLeafData()->RemoveArray( kmi );
  293. oct->GetLeafData()->RemoveArray( kidi );
  294. oct->GetLeafData()->RemoveArray( keri );
  295. oct->GetLeafData()->RemoveArray( khtr );
  296. oct->GetLeafData()->RemoveArray( khti );
  297. oct->GetLeafData()->RemoveArray( khrr );
  298. oct->GetLeafData()->RemoveArray( khri );
  299. kerr->Delete();
  300. kid->Delete();
  301. kr->Delete();
  302. ki->Delete();
  303. km->Delete();
  304. htr->Delete();
  305. hti->Delete();
  306. hrr->Delete();
  307. hri->Delete();
  308. }
  309. curse->Delete();
  310. oct->Delete();
  311. #else
  312. throw std::runtime_error("IntegrateOnOctreeGrid with vtkOutput requires Lemma with VTK support");
  313. #endif
  314. }
  315. std::cout << "\nVOLSUM=" << VOLSUM << "\tActual=" << Size(0)*Size(1)*Size(2)
  316. << "\tDifference=" << VOLSUM - (Size(0)*Size(1)*Size(2)) << std::endl;
  317. }
  318. //--------------------------------------------------------------------------------------
  319. // Class: KernelV0
  320. // Method: f
  321. //--------------------------------------------------------------------------------------
  322. VectorXcr KernelV0::f( const Vector3r& r, const Real& volume, const Vector3cr& Ht, const Vector3cr& Hr ) {
  323. // Compute the elliptic fields
  324. Vector3r B0hat = SigmaModel->GetMagneticFieldUnitVector();
  325. Vector3r B0 = SigmaModel->GetMagneticField();
  326. // Elliptic representation
  327. EllipticB EBT = EllipticFieldRep(MU0*Ht, B0hat);
  328. EllipticB EBR = EllipticFieldRep(MU0*Hr, B0hat);
  329. // Compute Mn0
  330. Vector3r Mn0 = ComputeMn0(1.0, B0);
  331. Real Mn0Abs = Mn0.norm();
  332. //std::cout << "Mn0\t" << Mn0.transpose() << std::endl;
  333. // Compute phase delay
  334. // TODO add transmiiter current phase and delay induced apparent time phase!
  335. Complex PhaseTerm = EBR.bhat.dot(EBT.bhat) + Complex(0, (B0hat.dot(EBR.bhat.cross(EBT.bhat))));
  336. Complex ejztr = std::exp(Complex(0, EBR.zeta + EBT.zeta));
  337. // Calcuate vector of all responses
  338. VectorXcr F = VectorXcr::Zero( PulseI.size() );
  339. for (int iq=0; iq<PulseI.size(); ++iq) {
  340. // Compute the tipping angle
  341. Real sintheta = std::sin(0.5*GAMMA*PulseI(iq)*Taup*(EBT.alpha-EBT.beta));
  342. F(iq) = -volume*Complex(0,Larmor)*Mn0Abs*(EBR.alpha+EBR.beta)*ejztr*sintheta*PhaseTerm;
  343. }
  344. return F;
  345. }
  346. // //--------------------------------------------------------------------------------------
  347. // // Class: KernelV0
  348. // // Method: ComputeV0Cell
  349. // //--------------------------------------------------------------------------------------
  350. // Complex KernelV0::ComputeV0Cell(const EllipticB& EBT, const EllipticB& EBR,
  351. // const Real& sintheta, const Real& phase, const Real& Mn0Abs,
  352. // const Real& vol) {
  353. // // earth response of receiver adjoint field
  354. // Vector3r B0hat = SigmaModel->GetMagneticFieldUnitVector();
  355. // Complex ejztr = std::exp(Complex(0, EBR.zeta + EBT.zeta));
  356. // Complex PhaseTerm = EBR.bhat.dot(EBT.bhat) + (B0hat.dot(EBR.bhat.cross(EBT.bhat) ));
  357. // return -vol*Complex(0,Larmor)*Mn0Abs*(EBR.alpha+EBR.beta)*ejztr*sintheta*PhaseTerm;
  358. // }
  359. //--------------------------------------------------------------------------------------
  360. // Class: KernelV0
  361. // Method: ComputeV0Cell
  362. //--------------------------------------------------------------------------------------
  363. Vector3r KernelV0::ComputeMn0(const Real& Porosity, const Vector3r& B0) {
  364. Real chi_n = NH2O*((GAMMA*GAMMA*HBAR*HBAR)/(4.*KB*Temperature));
  365. return chi_n*Porosity*B0;
  366. }
  367. //--------------------------------------------------------------------------------------
  368. // Class: KernelV0
  369. // Method: ComputeV0Cell
  370. //--------------------------------------------------------------------------------------
  371. EllipticB KernelV0::EllipticFieldRep (const Vector3cr& B, const Vector3r& B0hat) {
  372. // This all follows Weichman et al., 2000.
  373. // There are some numerical stability issues that arise when the two terms in the beta
  374. // formulation are nearly equivalent. The current formulation will result in a null-valued
  375. // beta, or can underflow. However, this does not entirely recreate the true value of B perp.
  376. // Error is checked to be below 1%, but reformulating for numeric stability may be welcome
  377. EllipticB ElipB = EllipticB();
  378. Vector3cr Bperp = B - B0hat.dot(B)*B0hat;
  379. Real BperpNorm = Bperp.norm();
  380. // These two are equivalent
  381. //Complex Bp2 = Bperp.transpose() * Bperp;
  382. Complex Bp2 = Bperp.conjugate().dot(Bperp);
  383. VectorXcr iB0 = Complex(0,1)*B0hat.cast<Complex>().array();
  384. ElipB.eizt = std::sqrt(Bp2 / std::abs(Bp2));
  385. ElipB.alpha = INVSQRT2*std::sqrt(BperpNorm*BperpNorm + std::abs(Bp2));
  386. //ElipB.beta = std::copysign(1, std::real(iB0.dot( Bperp.cross(Bperp.conjugate())) )) *
  387. ElipB.beta = sgn( std::real(iB0.dot( Bperp.cross(Bperp.conjugate())) )) *
  388. (INVSQRT2*std::sqrt(BperpNorm*BperpNorm - std::abs(Bp2)));
  389. // Correct underflow in beta calculation
  390. // could use cerrno instead...
  391. // http://en.cppreference.com/w/cpp/numeric/math/sqrt
  392. if (ElipB.beta != ElipB.beta) ElipB.beta = 0;
  393. ElipB.bhat = ((Real)1./ElipB.alpha)*(((Real)1./ElipB.eizt)*Bperp.array()).real().array();
  394. ElipB.bhatp = B0hat.cross(ElipB.bhat);
  395. ElipB.zeta = std::real(std::log(ElipB.eizt)/Complex(0,1));
  396. /* as an error check decomposed field - computed actual */
  397. // Vector3cr Bperp2 = ElipB.eizt * (ElipB.alpha * ElipB.bhat
  398. // + (Complex(0,1) * ElipB.beta * ElipB.bhatp) );
  399. // ElipB.err = (Bperp-Bperp2).norm();
  400. // if (ElipB.err > .01*Bperp.norm() ) { // 1% error
  401. // std::cout << "Elip error\n";
  402. // Real Beta2 = sgn( std::real(iB0.dot( Bperp.cross(Bperp.conjugate())) )) *
  403. // (INVSQRT2*std::sqrt(BperpNorm*BperpNorm - std::abs(Bp2)));
  404. // Vector3cr Bperp3 = ElipB.eizt * (ElipB.alpha * ElipB.bhat
  405. // + (Complex(0,1) * Beta2 * ElipB.bhatp) );
  406. // std::cout << "Beta term0\t" << (INVSQRT2*std::sqrt(BperpNorm*BperpNorm - std::abs(Bp2))) << std::endl;
  407. // std::cout << "Beta term1\t" << BperpNorm*BperpNorm << "\t" << std::abs(Bp2) << std::endl;
  408. // std::cout << "Beta \t" << ElipB.beta << std::endl;
  409. // std::cout << "Beta2 \t" << Beta2 << std::endl;
  410. // std::cout << "Bperp \t" << Bperp.transpose() << std::endl;
  411. // std::cout << "Bperp2\t" << Bperp2.transpose() << std::endl;
  412. // std::cout << "Bperp3\t" << Bperp3.transpose() << std::endl;
  413. // std::cout << "err \t" << ElipB.err << std::endl;
  414. // }
  415. return ElipB;
  416. }
  417. //--------------------------------------------------------------------------------------
  418. // Class: KernelV0
  419. // Method: EvaluateKids
  420. //--------------------------------------------------------------------------------------
  421. void KernelV0::EvaluateKids( const Vector3r& size, const int& level, const Vector3r& cpos,
  422. const VectorXcr& parentVal ) {
  423. std::cout << "\r" << (int)(1e2*VOLSUM/(Size[0]*Size[1]*Size[2])) << "\t" << nleaves;
  424. //std::cout.flush();
  425. // Next level step, interested in one level below
  426. // bitshift requires one extra, faster than, and equivalent to std::pow(2, level+1)
  427. Vector3r step = size.array() / (Real)(1 << (level+1) );
  428. Real vol = (step(0)*step(1)*step(2)); // volume of each child
  429. Vector3r pos = cpos - step/2.;
  430. Eigen::Matrix<Real, 8, 3> posadd = (Eigen::Matrix<Real, 8, 3>() <<
  431. 0, 0, 0,
  432. step[0], 0, 0,
  433. 0, step[1], 0,
  434. step[0], step[1], 0,
  435. 0, 0, step[2],
  436. step[0], 0, step[2],
  437. 0, step[1], step[2],
  438. step[0], step[1], step[2] ).finished();
  439. cpoints->ClearFields();
  440. for (int ichild=0; ichild<8; ++ichild) {
  441. Vector3r cp = pos; // Eigen complains about combining these
  442. cp += posadd.row(ichild);
  443. cpoints->SetLocation( ichild, cp );
  444. }
  445. Eigen::Matrix<Complex, 3, 8> Ht = Eigen::Matrix<Complex, 3, 8>::Zero();
  446. Eigen::Matrix<Complex, 3, 8> Hr = Eigen::Matrix<Complex, 3, 8>::Zero();
  447. for ( auto EMCalc : EMEarths ) {
  448. EMCalc.second->GetFieldPoints()->ClearFields();
  449. EMCalc.second->CalculateWireAntennaFields();
  450. switch (EMCalc.second->GetTxRxMode()) {
  451. case TX:
  452. Ht += EMCalc.second->GetFieldPoints()->GetHfield(0);
  453. break;
  454. case RX:
  455. Hr += EMCalc.second->GetFieldPoints()->GetHfield(0);
  456. break;
  457. case TXRX:
  458. Ht += EMCalc.second->GetFieldPoints()->GetHfield(0);
  459. Hr += EMCalc.second->GetFieldPoints()->GetHfield(0);
  460. break;
  461. default:
  462. break;
  463. }
  464. }
  465. MatrixXcr kvals(8, PulseI.size()); // individual kernel vals
  466. for (int ichild=0; ichild<8; ++ichild) {
  467. Vector3r cp = pos; // Eigen complains about combining these
  468. cp += posadd.row(ichild);
  469. kvals.row(ichild) = f(cp, vol, Ht.col(ichild), Hr.col(ichild));
  470. }
  471. VectorXcr ksum = kvals.colwise().sum(); // Kernel sum
  472. // Evaluate whether or not furthur splitting is needed
  473. if ( (((ksum - parentVal).array().abs() > tol).any() && level<maxLevel) || level < minLevel ) {
  474. // Not a leaf dive further in
  475. for (int ichild=0; ichild<8; ++ichild) {
  476. Vector3r cp = pos; // Eigen complains about combining these
  477. cp += posadd.row(ichild);
  478. EvaluateKids( size, level+1, cp, kvals.row(ichild) );
  479. }
  480. return; // not leaf
  481. }
  482. // implicit else, is a leaf
  483. Kern.row(ilay) += ksum;
  484. VOLSUM += 8.*vol;
  485. nleaves += 8; // reflects the number of kernel evaluations
  486. return; // is leaf
  487. }
  488. #ifdef LEMMAUSEVTK
  489. //--------------------------------------------------------------------------------------
  490. // Class: KernelV0
  491. // Method: EvaluateKids2 -- same as Evaluate Kids, but include VTK octree generation
  492. //--------------------------------------------------------------------------------------
  493. void KernelV0::EvaluateKids2( const Vector3r& size, const int& level, const Vector3r& cpos,
  494. const VectorXcr& parentVal, vtkHyperOctree* oct, vtkHyperOctreeCursor* curse) {
  495. std::cout << "\r" << (int)(1e2*VOLSUM/(Size[0]*Size[1]*Size[2])) << "\t" << nleaves;
  496. //std::cout.flush();
  497. // Next level step, interested in one level below
  498. // bitshift requires one extra, faster than, and equivalent to std::pow(2, level+1)
  499. Vector3r step = size.array() / (Real)(1 << (level+1) );
  500. Real vol = (step(0)*step(1)*step(2)); // volume of each child
  501. Vector3r pos = cpos - step/2.;
  502. Eigen::Matrix<Real, 8, 3> posadd = (Eigen::Matrix<Real, 8, 3>() <<
  503. 0, 0, 0,
  504. step[0], 0, 0,
  505. 0, step[1], 0,
  506. step[0], step[1], 0,
  507. 0, 0, step[2],
  508. step[0], 0, step[2],
  509. 0, step[1], step[2],
  510. step[0], step[1], step[2] ).finished();
  511. MatrixXcr kvals(8, PulseI.size()); // individual kernel vals
  512. cpoints->ClearFields();
  513. for (int ichild=0; ichild<8; ++ichild) {
  514. Vector3r cp = pos; // Eigen complains about combining these
  515. cp += posadd.row(ichild);
  516. cpoints->SetLocation( ichild, cp );
  517. }
  518. Eigen::Matrix<Complex, 3, 8> Ht = Eigen::Matrix<Complex, 3, 8>::Zero();
  519. Eigen::Matrix<Complex, 3, 8> Hr = Eigen::Matrix<Complex, 3, 8>::Zero();
  520. for ( auto EMCalc : EMEarths ) {
  521. //EMCalc->GetFieldPoints()->ClearFields();
  522. EMCalc.second->CalculateWireAntennaFields();
  523. switch (EMCalc.second->GetTxRxMode()) {
  524. case TX:
  525. Ht += EMCalc.second->GetFieldPoints()->GetHfield(0);
  526. break;
  527. case RX:
  528. Hr += EMCalc.second->GetFieldPoints()->GetHfield(0);
  529. break;
  530. case TXRX:
  531. Ht += EMCalc.second->GetFieldPoints()->GetHfield(0);
  532. Hr += EMCalc.second->GetFieldPoints()->GetHfield(0);
  533. break;
  534. default:
  535. break;
  536. }
  537. }
  538. for (int ichild=0; ichild<8; ++ichild) {
  539. Vector3r cp = pos; // Eigen complains about combining these
  540. cp += posadd.row(ichild);
  541. kvals.row(ichild) = f(cp, vol, Ht.col(ichild), Hr.col(ichild));
  542. }
  543. VectorXcr ksum = kvals.colwise().sum(); // Kernel sum
  544. // Evaluate whether or not furthur splitting is needed
  545. if ( (((ksum - parentVal).array().abs() > tol).any() && level<maxLevel) || level < minLevel ) {
  546. oct->SubdivideLeaf(curse);
  547. for (int ichild=0; ichild<8; ++ichild) {
  548. curse->ToChild(ichild);
  549. Vector3r cp = pos; // Eigen complains about combining these
  550. cp += posadd.row(ichild);
  551. /* Test for position via alternative means */
  552. /*
  553. Real p[3];
  554. GetPosition(curse, p);
  555. if ( (Vector3r(p) - cp).norm() > 1e-8 ) {
  556. std::cout << "ERROR @ nleaves" << nleaves << "\n" << cp[0] << "\t" << p[0] << "\t" << cp[1] << "\t" << p[1]
  557. << "\t" << cp[2] << "\t" << p[2] << "\t" << vol<< std::endl;
  558. throw std::runtime_error("doom");
  559. }
  560. */
  561. /* End of position test */
  562. EvaluateKids2( size, level+1, cp, kvals.row(ichild), oct, curse );
  563. curse->ToParent();
  564. }
  565. return; // not a leaf
  566. }
  567. /* just stuff with sum of the kids and don't subdivide */
  568. /*
  569. LeafDict[curse->GetLeafId()] = ksum/(8.*vol);
  570. LeafDictIdx[curse->GetLeafId()] = nleaves;
  571. */
  572. /* Alternatively, subdivide the VTK octree here and stuff the children to make better
  573. * visuals, but also 8x the storage...
  574. */
  575. oct->SubdivideLeaf(curse);
  576. for (int ichild=0; ichild<8; ++ichild) {
  577. curse->ToChild(ichild);
  578. LeafDict[curse->GetLeafId()] = ksum/(8.*vol);
  579. LeafHt[curse->GetLeafId()] = Ht.col(ichild);
  580. LeafHr[curse->GetLeafId()] = Hr.col(ichild);
  581. LeafDictIdx[curse->GetLeafId()] = nleaves;
  582. curse->ToParent();
  583. }
  584. Kern.row(ilay) += ksum;
  585. VOLSUM += 8*vol;
  586. nleaves += 8; // good reason to say 1 or 8 here...8 sounds better and reflects kernel evaluations
  587. return; // is a leaf
  588. }
  589. //--------------------------------------------------------------------------------------
  590. // Class: KernelV0
  591. // Method: GetPosition
  592. //--------------------------------------------------------------------------------------
  593. void KernelV0::GetPosition( vtkHyperOctreeCursor* Cursor, Real* p ) {
  594. Real ratio=1.0/(1<<(Cursor->GetCurrentLevel()));
  595. //step = ((Size).array() / std::pow(2.,Cursor->GetCurrentLevel()));
  596. p[0]=(Cursor->GetIndex(0)+.5)*ratio*this->Size[0]+this->Origin[0] ;//+ .5*step[0];
  597. p[1]=(Cursor->GetIndex(1)+.5)*ratio*this->Size[1]+this->Origin[1] ;//+ .5*step[1];
  598. p[2]=(Cursor->GetIndex(2)+.5)*ratio*this->Size[2]+this->Origin[2] ;//+ .5*step[2];
  599. }
  600. #endif
  601. } // ---- end of namespace Lemma ----
  602. /* vim: set tabstop=4 expandtab */
  603. /* vim: set filetype=cpp */