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

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