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

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