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

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