Surface NMR forward modelling
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

KernelV0.cpp 31KB

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. std::cout << "coil " << coil.first << coil.second << std::endl;
  60. if ( coil.second.Tag() == "PolygonalWireAntenna" ) {
  61. TxRx[ coil.first.as<std::string>() ] = PolygonalWireAntenna::DeSerialize( coil.second );
  62. } else {
  63. TxRx[ coil.first.as<std::string>() ] =
  64. PolygonalWireAntenna::DeSerialize( YAML::LoadFile(coil.second.as<std::string>()) );
  65. }
  66. }
  67. }
  68. } // ----- end of method KernelV0::KernelV0 (constructor) -----
  69. //--------------------------------------------------------------------------------------
  70. // Class: KernelV0
  71. // Method: NewSP()
  72. // Description: public constructor returing a shared_ptr
  73. //--------------------------------------------------------------------------------------
  74. std::shared_ptr< KernelV0 > KernelV0::NewSP() {
  75. return std::make_shared< KernelV0 >( ctor_key() );
  76. }
  77. //--------------------------------------------------------------------------------------
  78. // Class: KernelV0
  79. // Method: ~KernelV0
  80. // Description: destructor (protected)
  81. //--------------------------------------------------------------------------------------
  82. KernelV0::~KernelV0 () {
  83. } // ----- end of method KernelV0::~KernelV0 (destructor) -----
  84. //--------------------------------------------------------------------------------------
  85. // Class: KernelV0
  86. // Method: Serialize
  87. //--------------------------------------------------------------------------------------
  88. YAML::Node KernelV0::Serialize ( ) const {
  89. YAML::Node node = LemmaObject::Serialize();
  90. node.SetTag( GetName() );
  91. // Coils Transmitters & Receivers
  92. if (!TxRx.empty()) {
  93. for ( auto txm : TxRx) {
  94. node["Coils"][txm.first] = txm.second->Serialize();
  95. }
  96. }
  97. // LayeredEarthEM
  98. if (SigmaModel != nullptr) {
  99. node["SigmaModel"] = SigmaModel->Serialize();
  100. }
  101. node["PulseType"] = "FID";
  102. node["Larmor"] = Larmor;
  103. node["Temperature"] = Temperature;
  104. node["tol"] = tol;
  105. node["minLevel"] = minLevel;
  106. node["maxLevel"] = maxLevel;
  107. node["Taup"] = Taup;
  108. node["PulseI"] = PulseI;
  109. node["Interfaces"] = Interfaces;
  110. node["IntegrationSize"] = Size;
  111. node["IntegrationOrigin"] = Origin;
  112. if (Kern.array().abs().any() > 1e-16) {
  113. for ( int ilay=0; ilay<Interfaces.size()-1; ++ilay ) {
  114. node["K0"]["layer-" + to_string(ilay) ] = static_cast<VectorXcr>(Kern.row(ilay));
  115. }
  116. }
  117. return node;
  118. } // ----- end of method KernelV0::Serialize -----
  119. //--------------------------------------------------------------------------------------
  120. // Class: KernelV0
  121. // Method: DeSerialize
  122. //--------------------------------------------------------------------------------------
  123. std::shared_ptr<KernelV0> KernelV0::DeSerialize ( const YAML::Node& node ) {
  124. if (node.Tag() != "KernelV0" ) {
  125. throw DeSerializeTypeMismatch( "KernelV0", node.Tag());
  126. }
  127. return std::make_shared< KernelV0 > ( node, ctor_key() );
  128. } // ----- end of method KernelV0::DeSerialize -----
  129. //--------------------------------------------------------------------------------------
  130. // Class: KernelV0
  131. // Method: AlignWithAkvoDataset
  132. //--------------------------------------------------------------------------------------
  133. void KernelV0::AlignWithAkvoDataset( const YAML::Node& node ) {
  134. if (node["processed"].as<std::string>().substr(0,4) == "Akvo") {
  135. std::cout << "Akvo file read\n";
  136. std::cout << node["processed"] << std::endl;
  137. }
  138. if (node["pulseType"].as<std::string>() == "FID") {
  139. PulseI = node["Pulse 1"]["current"].as<VectorXr>();
  140. this->SetPulseDuration( node["pulseLength"].as<double>() );
  141. } else {
  142. std::cerr << "Pulse Type " << node["PulseType"] << "is not supported\n";
  143. }
  144. }
  145. //--------------------------------------------------------------------------------------
  146. // Class: KernelV0
  147. // Method: DeSerialize
  148. //--------------------------------------------------------------------------------------
  149. void KernelV0::CalculateK0 (const std::vector< std::string>& Tx,
  150. const std::vector<std::string >& Rx, bool vtkOutput ) {
  151. // Set up
  152. Larmor = SigmaModel->GetMagneticFieldMagnitude()*GAMMA; // in rad 2246.*2.*PI;
  153. // All EM calculations will share same field points
  154. cpoints = FieldPoints::NewSP();
  155. cpoints->SetNumberOfPoints(8);
  156. for (auto tx : Tx) {
  157. // Set up EMEarth
  158. EMEarths[tx] = EMEarth1D::NewSP();
  159. EMEarths[tx]->AttachWireAntenna(TxRx[tx]);
  160. EMEarths[tx]->AttachLayeredEarthEM(SigmaModel);
  161. EMEarths[tx]->AttachFieldPoints( cpoints );
  162. EMEarths[tx]->SetFieldsToCalculate(H);
  163. // TODO query for method, altough with flat antennae, this is fastest
  164. //EMEarths[tx]->SetHankelTransformMethod(FHTKEY201);
  165. EMEarths[tx]->SetHankelTransformMethod(ANDERSON801);
  166. EMEarths[tx]->SetTxRxMode(TX);
  167. TxRx[tx]->SetCurrent(1.);
  168. }
  169. for (auto rx : Rx) {
  170. if (EMEarths.count(rx)) {
  171. EMEarths[rx]->SetTxRxMode(TXRX);
  172. } else {
  173. EMEarths[rx] = EMEarth1D::NewSP();
  174. EMEarths[rx]->AttachWireAntenna(TxRx[rx]);
  175. EMEarths[rx]->AttachLayeredEarthEM(SigmaModel);
  176. EMEarths[rx]->AttachFieldPoints( cpoints );
  177. EMEarths[rx]->SetFieldsToCalculate(H);
  178. // TODO query for method, altough with flat antennae, this is fastest
  179. //EMEarths[rx]->SetHankelTransformMethod(FHTKEY201);
  180. EMEarths[rx]->SetHankelTransformMethod(ANDERSON801);
  181. EMEarths[rx]->SetTxRxMode(RX);
  182. TxRx[rx]->SetCurrent(1.);
  183. }
  184. }
  185. std::cout << "Calculating K0 kernel\n";
  186. Kern = MatrixXcr::Zero( Interfaces.size()-1, PulseI.size() );
  187. for (ilay=0; ilay<Interfaces.size()-1; ++ilay) {
  188. std::cout << "Layer " << ilay << "\tfrom " << Interfaces(ilay) <<" to "
  189. << Interfaces(ilay+1) << std::endl;
  190. Size(2) = Interfaces(ilay+1) - Interfaces(ilay);
  191. Origin(2) = Interfaces(ilay);
  192. IntegrateOnOctreeGrid( vtkOutput );
  193. }
  194. std::cout << "\nFinished KERNEL\n";
  195. }
  196. //--------------------------------------------------------------------------------------
  197. // Class: KernelV0
  198. // Method: IntegrateOnOctreeGrid
  199. //--------------------------------------------------------------------------------------
  200. void KernelV0::IntegrateOnOctreeGrid( bool vtkOutput) {
  201. Vector3r cpos = Origin + Size/2.;
  202. VOLSUM = 0;
  203. nleaves = 0;
  204. if (!vtkOutput) {
  205. EvaluateKids( Size, 0, cpos, VectorXcr::Ones(PulseI.size()) );
  206. } else {
  207. #ifdef LEMMAUSEVTK
  208. vtkHyperOctree* oct = vtkHyperOctree::New();
  209. oct->SetDimension(3);
  210. oct->SetOrigin( Origin(0), Origin(1), Origin(2) );
  211. oct->SetSize( Size(0), Size(1), Size(2) );
  212. vtkHyperOctreeCursor* curse = oct->NewCellCursor();
  213. curse->ToRoot();
  214. EvaluateKids2( Size, 0, cpos, VectorXcr::Ones(PulseI.size()), oct, curse );
  215. for (int iq=0; iq<PulseI.size(); ++iq) {
  216. // Fill in leaf data
  217. vtkDoubleArray* kr = vtkDoubleArray::New();
  218. kr->SetNumberOfComponents(1);
  219. kr->SetName("Re($\\mathcal{K}_0$)");
  220. kr->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  221. vtkDoubleArray* ki = vtkDoubleArray::New();
  222. ki->SetNumberOfComponents(1);
  223. ki->SetName("Im($\\mathcal{K}_0$)");
  224. ki->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  225. vtkDoubleArray* km = vtkDoubleArray::New();
  226. km->SetNumberOfComponents(1);
  227. km->SetName("mod($\\mathcal{K}_0$)");
  228. km->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  229. vtkIntArray* kid = vtkIntArray::New();
  230. kid->SetNumberOfComponents(1);
  231. kid->SetName("ID");
  232. kid->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  233. vtkIntArray* kerr = vtkIntArray::New();
  234. kerr->SetNumberOfComponents(1);
  235. kerr->SetName("err");
  236. kerr->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  237. // Ht field
  238. vtkDoubleArray* htr = vtkDoubleArray::New();
  239. htr->SetNumberOfComponents(3);
  240. htr->SetName("Re($\\mathbf{\\mathcal{H}}_T$)");
  241. htr->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  242. vtkDoubleArray* hti = vtkDoubleArray::New();
  243. hti->SetNumberOfComponents(3);
  244. hti->SetName("Im($\\mathbf{\\mathcal{H}}_T$)");
  245. hti->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  246. // Hr field
  247. vtkDoubleArray* hrr = vtkDoubleArray::New();
  248. hrr->SetNumberOfComponents(3);
  249. hrr->SetName("Re($\\mathbf{\\mathcal{H}}_R$)");
  250. hrr->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  251. vtkDoubleArray* hri = vtkDoubleArray::New();
  252. hri->SetNumberOfComponents(3);
  253. hri->SetName("Im($\\mathbf{\\mathcal{H}}_R$)");
  254. hri->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  255. //Real LeafVol(0);
  256. for (auto leaf : LeafDict) {
  257. kr->InsertTuple1( leaf.first, std::real(leaf.second(iq)) );
  258. ki->InsertTuple1( leaf.first, std::imag(leaf.second(iq)) );
  259. km->InsertTuple1( leaf.first, std::abs(leaf.second(iq)) );
  260. kid->InsertTuple1( leaf.first, leaf.first );
  261. //LeafVol += std::real(leaf.second);
  262. }
  263. for (auto leaf : LeafHt ) {
  264. htr->InsertTuple( leaf.first, leaf.second.real().data() );
  265. hti->InsertTuple( leaf.first, leaf.second.imag().data() );
  266. }
  267. for (auto leaf : LeafHr ) {
  268. hrr->InsertTuple( leaf.first, leaf.second.real().data() );
  269. hri->InsertTuple( leaf.first, leaf.second.imag().data() );
  270. }
  271. for (auto leaf : LeafDictIdx) {
  272. kerr->InsertTuple1( leaf.first, leaf.second );
  273. }
  274. auto kri = oct->GetLeafData()->AddArray(kr);
  275. auto kii = oct->GetLeafData()->AddArray(ki);
  276. auto kmi = oct->GetLeafData()->AddArray(km);
  277. auto kidi = oct->GetLeafData()->AddArray(kid);
  278. auto keri = oct->GetLeafData()->AddArray(kerr);
  279. auto khtr = oct->GetLeafData()->AddArray(htr);
  280. auto khti = oct->GetLeafData()->AddArray(hti);
  281. auto khrr = oct->GetLeafData()->AddArray(hrr);
  282. auto khri = oct->GetLeafData()->AddArray(hri);
  283. auto write = vtkXMLHyperOctreeWriter::New();
  284. //write.SetDataModeToAscii()
  285. write->SetInputData(oct);
  286. std::string fname = std::string("octree-") + to_string(ilay)
  287. + std::string("-") + to_string(iq) + std::string(".vto");
  288. write->SetFileName(fname.c_str());
  289. write->Write();
  290. write->Delete();
  291. oct->GetLeafData()->RemoveArray( kri );
  292. oct->GetLeafData()->RemoveArray( kii );
  293. oct->GetLeafData()->RemoveArray( kmi );
  294. oct->GetLeafData()->RemoveArray( kidi );
  295. oct->GetLeafData()->RemoveArray( keri );
  296. oct->GetLeafData()->RemoveArray( khtr );
  297. oct->GetLeafData()->RemoveArray( khti );
  298. oct->GetLeafData()->RemoveArray( khrr );
  299. oct->GetLeafData()->RemoveArray( khri );
  300. kerr->Delete();
  301. kid->Delete();
  302. kr->Delete();
  303. ki->Delete();
  304. km->Delete();
  305. htr->Delete();
  306. hti->Delete();
  307. hrr->Delete();
  308. hri->Delete();
  309. }
  310. curse->Delete();
  311. oct->Delete();
  312. #else
  313. throw std::runtime_error("IntegrateOnOctreeGrid with vtkOutput requires Lemma with VTK support");
  314. #endif
  315. }
  316. std::cout << "\nVOLSUM=" << VOLSUM << "\tActual=" << Size(0)*Size(1)*Size(2)
  317. << "\tDifference=" << VOLSUM - (Size(0)*Size(1)*Size(2)) << std::endl;
  318. }
  319. //--------------------------------------------------------------------------------------
  320. // Class: KernelV0
  321. // Method: f
  322. //--------------------------------------------------------------------------------------
  323. VectorXcr KernelV0::f( const Vector3r& r, const Real& volume, const Vector3cr& Ht, const Vector3cr& Hr ) {
  324. // Compute the elliptic fields
  325. Vector3r B0hat = SigmaModel->GetMagneticFieldUnitVector();
  326. Vector3r B0 = SigmaModel->GetMagneticField();
  327. // Elliptic representation
  328. EllipticB EBT = EllipticFieldRep(MU0*Ht, B0hat);
  329. EllipticB EBR = EllipticFieldRep(MU0*Hr, B0hat);
  330. // Compute Mn0
  331. Vector3r Mn0 = ComputeMn0(1.0, B0);
  332. Real Mn0Abs = Mn0.norm();
  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 */