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

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