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

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