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 30KB

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