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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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. #if LEMMA_VTK8_SUPPORT
  247. oct->SetGridSize( 1, 1, 1 ); // Important!
  248. oct->SetDimension(3);
  249. #elif LEMMA_VTK9_SUPPORT
  250. oct->SetExtent( 0, 1, 0, 1, 0, 1 ); // Important!
  251. oct->SetDimensions(1,1,1);
  252. #endif
  253. vtkNew<vtkDoubleArray> xcoords;
  254. xcoords->SetNumberOfComponents(1);
  255. xcoords->SetNumberOfTuples(2);
  256. xcoords->SetTuple1( 0, Origin(0) );
  257. xcoords->SetTuple1( 1, Origin(0) + Size(0) );
  258. xcoords->SetName("northing (m)");
  259. oct->SetXCoordinates(xcoords);
  260. vtkNew<vtkDoubleArray> ycoords;
  261. ycoords->SetNumberOfComponents(1);
  262. ycoords->SetNumberOfTuples(2);
  263. ycoords->SetTuple1( 0, Origin(1) );
  264. ycoords->SetTuple1( 1, Origin(1) + Size(1) );
  265. ycoords->SetName("easting (m)");
  266. oct->SetYCoordinates(ycoords);
  267. vtkNew<vtkDoubleArray> zcoords;
  268. zcoords->SetNumberOfComponents(1);
  269. zcoords->SetNumberOfTuples(2);
  270. zcoords->SetTuple1( 0, Origin(2) );
  271. zcoords->SetTuple1( 1, Origin(2) + Size(2) );
  272. zcoords->SetName("depth (m)");
  273. oct->SetZCoordinates(zcoords);
  274. //vtkHyperTreeGridLevelEntry* curse2 = vtkHyperTreeGridLevelEntry::New(); // VTK 9
  275. // I belive the index in NewCursor maybe points to which cell in the Rectilinear Grid?
  276. #if LEMMA_VTK8_SUPPORT
  277. vtkHyperTreeCursor* curse = oct->NewCursor(0, true); // true creates the cursor
  278. curse->ToRoot();
  279. EvaluateKids2( Size, 0, cpos, VectorXcr::Ones(PulseI.size()), oct, curse );
  280. #elif LEMMA_VTK9_SUPPORT
  281. auto curse = oct->NewNonOrientedCursor(0, true); // true creates the cursor
  282. curse->ToRoot();
  283. EvaluateKids2( Size, 0, cpos, VectorXcr::Ones(PulseI.size()), oct->GetTree(0, true), curse );
  284. #endif
  285. for (int iq=0; iq<PulseI.size(); ++iq) {
  286. // Fill in leaf data
  287. vtkDoubleArray* kr = vtkDoubleArray::New();
  288. kr->SetNumberOfComponents(1);
  289. kr->SetName("Re($\\mathcal{K}_0$)");
  290. kr->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  291. vtkDoubleArray* ki = vtkDoubleArray::New();
  292. ki->SetNumberOfComponents(1);
  293. ki->SetName("Im($\\mathcal{K}_0$)");
  294. ki->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  295. vtkDoubleArray* km = vtkDoubleArray::New();
  296. km->SetNumberOfComponents(1);
  297. km->SetName("mod($\\mathcal{K}_0$)");
  298. km->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  299. vtkIntArray* kid = vtkIntArray::New();
  300. kid->SetNumberOfComponents(1);
  301. kid->SetName("ID");
  302. kid->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  303. vtkIntArray* kerr = vtkIntArray::New();
  304. kerr->SetNumberOfComponents(1);
  305. kerr->SetName("err");
  306. kerr->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  307. // Ht field
  308. vtkDoubleArray* htr = vtkDoubleArray::New();
  309. htr->SetNumberOfComponents(3);
  310. htr->SetName("Re($\\mathbf{\\mathcal{H}}_T$)");
  311. htr->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  312. vtkDoubleArray* hti = vtkDoubleArray::New();
  313. hti->SetNumberOfComponents(3);
  314. hti->SetName("Im($\\mathbf{\\mathcal{H}}_T$)");
  315. hti->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  316. // Hr field
  317. vtkDoubleArray* hrr = vtkDoubleArray::New();
  318. hrr->SetNumberOfComponents(3);
  319. hrr->SetName("Re($\\mathbf{\\mathcal{H}}_R$)");
  320. hrr->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  321. vtkDoubleArray* hri = vtkDoubleArray::New();
  322. hri->SetNumberOfComponents(3);
  323. hri->SetName("Im($\\mathbf{\\mathcal{H}}_R$)");
  324. hri->SetNumberOfTuples( oct->GetNumberOfLeaves() );
  325. //Real LeafVol(0);
  326. //kr->Fill(0);
  327. int icc(0);
  328. for (auto leaf : LeafDict) {
  329. kr->InsertTuple1( leaf.first, std::real(leaf.second(iq)) );
  330. ki->InsertTuple1( leaf.first, std::imag(leaf.second(iq)) );
  331. km->InsertTuple1( leaf.first, std::abs(leaf.second(iq)) );
  332. kid->InsertTuple1( leaf.first, leaf.first );
  333. //LeafVol += std::real(leaf.second);
  334. ++icc;
  335. }
  336. for (auto leaf : LeafHt ) {
  337. htr->InsertTuple( leaf.first, leaf.second.real().data() );
  338. hti->InsertTuple( leaf.first, leaf.second.imag().data() );
  339. }
  340. for (auto leaf : LeafHr ) {
  341. hrr->InsertTuple( leaf.first, leaf.second.real().data() );
  342. hri->InsertTuple( leaf.first, leaf.second.imag().data() );
  343. }
  344. for (auto leaf : LeafDictIdx) {
  345. kerr->InsertTuple1( leaf.first, leaf.second );
  346. }
  347. // In VTK 8, vtkHyperTreeGrid does not support CellData.
  348. // the previous class vtkHyperOctreeGrid used "LeafData",
  349. // but for the new classes, PointData seems to function as LeafData.
  350. // this could change in VTK 9
  351. auto kri = oct->GetPointData()->AddArray(kr);
  352. auto kii = oct->GetPointData()->AddArray(ki);
  353. auto kmi = oct->GetPointData()->AddArray(km);
  354. auto kidi = oct->GetPointData()->AddArray(kid);
  355. auto keri = oct->GetPointData()->AddArray(kerr);
  356. auto khtr = oct->GetPointData()->AddArray(htr);
  357. auto khti = oct->GetPointData()->AddArray(hti);
  358. auto khrr = oct->GetPointData()->AddArray(hrr);
  359. auto khri = oct->GetPointData()->AddArray(hri);
  360. //std::cout << *oct << std::endl;
  361. auto write = vtkXMLHyperTreeGridWriter::New();
  362. std::string fname = std::string("octree-") + to_string(ilay)
  363. + std::string("-") + to_string(iq) + std::string(".htg");
  364. write->SetFileName(fname.c_str());
  365. write->SetInputData(oct);
  366. write->SetDataModeToBinary();
  367. //write->SetDataModeToAscii();
  368. write->Update();
  369. write->Write();
  370. write->Delete();
  371. oct->GetPointData()->RemoveArray( kri );
  372. oct->GetPointData()->RemoveArray( kii );
  373. oct->GetPointData()->RemoveArray( kmi );
  374. oct->GetPointData()->RemoveArray( kidi );
  375. oct->GetPointData()->RemoveArray( keri );
  376. oct->GetPointData()->RemoveArray( khtr );
  377. oct->GetPointData()->RemoveArray( khti );
  378. oct->GetPointData()->RemoveArray( khrr );
  379. oct->GetPointData()->RemoveArray( khri );
  380. kerr->Delete();
  381. kid->Delete();
  382. kr->Delete();
  383. ki->Delete();
  384. km->Delete();
  385. htr->Delete();
  386. hti->Delete();
  387. hrr->Delete();
  388. hri->Delete();
  389. }
  390. curse->Delete();
  391. oct->Delete();
  392. #else
  393. throw std::runtime_error("IntegrateOnOctreeGrid with vtkOutput requires Lemma with VTK support");
  394. #endif
  395. }
  396. //std::cout << "\nVOLSUM=" << VOLSUM << "\tActual=" << Size(0)*Size(1)*Size(2)
  397. // << "\tDifference=" << VOLSUM - (Size(0)*Size(1)*Size(2)) << std::endl;
  398. }
  399. //--------------------------------------------------------------------------------------
  400. // Class: KernelV0
  401. // Method: f
  402. //--------------------------------------------------------------------------------------
  403. VectorXcr KernelV0::f( const Vector3r& r, const Real& volume, const Vector3cr& Ht, const Vector3cr& Hr ) {
  404. // Compute the elliptic fields
  405. Vector3r B0hat = SigmaModel->GetMagneticFieldUnitVector();
  406. Vector3r B0 = SigmaModel->GetMagneticField();
  407. // Elliptic representation
  408. EllipticB EBT = EllipticFieldRep(MU0*Ht, B0hat);
  409. EllipticB EBR = EllipticFieldRep(MU0*Hr, B0hat);
  410. // Compute Mn0
  411. Vector3r Mn0 = ComputeMn0(1.0, B0);
  412. Real Mn0Abs = Mn0.norm();
  413. //std::cout << "Mn0\t" << Mn0.transpose() << std::endl;
  414. // Compute phase delay
  415. // TODO add transmiiter current phase and delay induced apparent time phase!
  416. Complex PhaseTerm = EBR.bhat.dot(EBT.bhat) + Complex(0, (B0hat.dot(EBR.bhat.cross(EBT.bhat))));
  417. Complex ejztr = std::exp(Complex(0, EBR.zeta + EBT.zeta));
  418. // Calcuate vector of all responses
  419. VectorXcr F = VectorXcr::Zero( PulseI.size() );
  420. for (int iq=0; iq<PulseI.size(); ++iq) {
  421. // Compute the tipping angle
  422. Real sintheta = std::sin(0.5*GAMMA*PulseI(iq)*Taup*(EBT.alpha-EBT.beta));
  423. F(iq) = -volume*Complex(0,Larmor)*Mn0Abs*(EBR.alpha+EBR.beta)*ejztr*sintheta*PhaseTerm;
  424. }
  425. return F;
  426. }
  427. // //--------------------------------------------------------------------------------------
  428. // // Class: KernelV0
  429. // // Method: ComputeV0Cell
  430. // //--------------------------------------------------------------------------------------
  431. // Complex KernelV0::ComputeV0Cell(const EllipticB& EBT, const EllipticB& EBR,
  432. // const Real& sintheta, const Real& phase, const Real& Mn0Abs,
  433. // const Real& vol) {
  434. // // earth response of receiver adjoint field
  435. // Vector3r B0hat = SigmaModel->GetMagneticFieldUnitVector();
  436. // Complex ejztr = std::exp(Complex(0, EBR.zeta + EBT.zeta));
  437. // Complex PhaseTerm = EBR.bhat.dot(EBT.bhat) + (B0hat.dot(EBR.bhat.cross(EBT.bhat) ));
  438. // return -vol*Complex(0,Larmor)*Mn0Abs*(EBR.alpha+EBR.beta)*ejztr*sintheta*PhaseTerm;
  439. // }
  440. //--------------------------------------------------------------------------------------
  441. // Class: KernelV0
  442. // Method: ComputeV0Cell
  443. //--------------------------------------------------------------------------------------
  444. Vector3r KernelV0::ComputeMn0(const Real& Porosity, const Vector3r& B0) {
  445. Real chi_n = NH2O*((GAMMA*GAMMA*HBAR*HBAR)/(4.*KB*Temperature));
  446. return chi_n*Porosity*B0;
  447. }
  448. //--------------------------------------------------------------------------------------
  449. // Class: KernelV0
  450. // Method: ComputeV0Cell
  451. //--------------------------------------------------------------------------------------
  452. EllipticB KernelV0::EllipticFieldRep (const Vector3cr& B, const Vector3r& B0hat) {
  453. // This all follows Weichman et al., 2000.
  454. // There are some numerical stability issues that arise when the two terms in the beta
  455. // formulation are nearly equivalent. The current formulation will result in a null-valued
  456. // beta, or can underflow. However, this does not entirely recreate the true value of B perp.
  457. // Error is checked to be below 1%, but reformulating for numeric stability may be welcome
  458. EllipticB ElipB = EllipticB();
  459. Vector3cr Bperp = B - B0hat.dot(B)*B0hat;
  460. Real BperpNorm = Bperp.norm();
  461. // These two are equivalent
  462. //Complex Bp2 = Bperp.transpose() * Bperp;
  463. Complex Bp2 = Bperp.conjugate().dot(Bperp);
  464. VectorXcr iB0 = Complex(0,1)*B0hat.cast<Complex>().array();
  465. ElipB.eizt = std::sqrt(Bp2 / std::abs(Bp2));
  466. ElipB.alpha = INVSQRT2*std::sqrt(BperpNorm*BperpNorm + std::abs(Bp2));
  467. //ElipB.beta = std::copysign(1, std::real(iB0.dot( Bperp.cross(Bperp.conjugate())) )) *
  468. ElipB.beta = sgn( std::real(iB0.dot( Bperp.cross(Bperp.conjugate())) )) *
  469. (INVSQRT2*std::sqrt(BperpNorm*BperpNorm - std::abs(Bp2)));
  470. // Correct underflow in beta calculation
  471. // could use cerrno instead...
  472. // http://en.cppreference.com/w/cpp/numeric/math/sqrt
  473. if (ElipB.beta != ElipB.beta) ElipB.beta = 0;
  474. ElipB.bhat = ((Real)1./ElipB.alpha)*(((Real)1./ElipB.eizt)*Bperp.array()).real().array();
  475. ElipB.bhatp = B0hat.cross(ElipB.bhat);
  476. ElipB.zeta = std::real(std::log(ElipB.eizt)/Complex(0,1));
  477. /* as an error check decomposed field - computed actual */
  478. // Vector3cr Bperp2 = ElipB.eizt * (ElipB.alpha * ElipB.bhat
  479. // + (Complex(0,1) * ElipB.beta * ElipB.bhatp) );
  480. // ElipB.err = (Bperp-Bperp2).norm();
  481. // if (ElipB.err > .01*Bperp.norm() ) { // 1% error
  482. // std::cout << "Elip error\n";
  483. // Real Beta2 = sgn( std::real(iB0.dot( Bperp.cross(Bperp.conjugate())) )) *
  484. // (INVSQRT2*std::sqrt(BperpNorm*BperpNorm - std::abs(Bp2)));
  485. // Vector3cr Bperp3 = ElipB.eizt * (ElipB.alpha * ElipB.bhat
  486. // + (Complex(0,1) * Beta2 * ElipB.bhatp) );
  487. // std::cout << "Beta term0\t" << (INVSQRT2*std::sqrt(BperpNorm*BperpNorm - std::abs(Bp2))) << std::endl;
  488. // std::cout << "Beta term1\t" << BperpNorm*BperpNorm << "\t" << std::abs(Bp2) << std::endl;
  489. // std::cout << "Beta \t" << ElipB.beta << std::endl;
  490. // std::cout << "Beta2 \t" << Beta2 << std::endl;
  491. // std::cout << "Bperp \t" << Bperp.transpose() << std::endl;
  492. // std::cout << "Bperp2\t" << Bperp2.transpose() << std::endl;
  493. // std::cout << "Bperp3\t" << Bperp3.transpose() << std::endl;
  494. // std::cout << "err \t" << ElipB.err << std::endl;
  495. // }
  496. return ElipB;
  497. }
  498. //--------------------------------------------------------------------------------------
  499. // Class: KernelV0
  500. // Method: EvaluateKids
  501. //--------------------------------------------------------------------------------------
  502. void KernelV0::EvaluateKids( const Vector3r& size, const int& level, const Vector3r& cpos,
  503. const VectorXcr& parentVal ) {
  504. int pdone = (int)(1e2*VOLSUM/(Size[0]*Size[1]*Size[2]));
  505. if (pdone > percent_done ) {
  506. percent_done = pdone;
  507. ++(*disp);
  508. }
  509. //disp->updateLastPrintedMessage("Number of leaves: " + std::to_string(nleaves));
  510. //std::cout << "\r" << (int)(1e2*VOLSUM/(Size[0]*Size[1]*Size[2])) << "\t" << nleaves;
  511. //std::cout.flush();
  512. // Next level step, interested in one level below
  513. // bitshift requires one extra, faster than, and equivalent to std::pow(2, level+1)
  514. Vector3r step = size.array() / (Real)(1 << (level+1) );
  515. Real vol = (step(0)*step(1)*step(2)); // volume of each child
  516. Vector3r pos = cpos - step/2.;
  517. Eigen::Matrix<Real, 8, 3> posadd = (Eigen::Matrix<Real, 8, 3>() <<
  518. 0, 0, 0,
  519. step[0], 0, 0,
  520. 0, step[1], 0,
  521. step[0], step[1], 0,
  522. 0, 0, step[2],
  523. step[0], 0, step[2],
  524. 0, step[1], step[2],
  525. step[0], step[1], step[2] ).finished();
  526. cpoints->ClearFields();
  527. for (int ichild=0; ichild<8; ++ichild) {
  528. Vector3r cp = pos; // Eigen complains about combining these
  529. cp += posadd.row(ichild);
  530. cpoints->SetLocation( ichild, cp );
  531. }
  532. Eigen::Matrix<Complex, 3, 8> Ht = Eigen::Matrix<Complex, 3, 8>::Zero();
  533. Eigen::Matrix<Complex, 3, 8> Hr = Eigen::Matrix<Complex, 3, 8>::Zero();
  534. for ( auto EMCalc : EMEarths ) {
  535. EMCalc.second->GetFieldPoints()->ClearFields();
  536. EMCalc.second->CalculateWireAntennaFields();
  537. switch (EMCalc.second->GetTxRxMode()) {
  538. case TX:
  539. Ht += EMCalc.second->GetFieldPoints()->GetHfield(0);
  540. break;
  541. case RX:
  542. Hr += EMCalc.second->GetFieldPoints()->GetHfield(0);
  543. break;
  544. case TXRX:
  545. Ht += EMCalc.second->GetFieldPoints()->GetHfield(0);
  546. Hr += EMCalc.second->GetFieldPoints()->GetHfield(0);
  547. break;
  548. default:
  549. break;
  550. }
  551. }
  552. MatrixXcr kvals(8, PulseI.size()); // individual kernel vals
  553. for (int ichild=0; ichild<8; ++ichild) {
  554. Vector3r cp = pos; // Eigen complains about combining these
  555. cp += posadd.row(ichild);
  556. kvals.row(ichild) = f(cp, vol, Ht.col(ichild), Hr.col(ichild));
  557. }
  558. VectorXcr ksum = kvals.colwise().sum(); // Kernel sum
  559. // Evaluate whether or not furthur splitting is needed
  560. if ( (((ksum - parentVal).array().abs() > tol).any() && level<maxLevel) || level < minLevel ) {
  561. // Not a leaf dive further in
  562. for (int ichild=0; ichild<8; ++ichild) {
  563. Vector3r cp = pos; // Eigen complains about combining these
  564. cp += posadd.row(ichild);
  565. EvaluateKids( size, level+1, cp, kvals.row(ichild) );
  566. }
  567. return; // not leaf
  568. }
  569. // implicit else, is a leaf
  570. Kern.row(ilay) += ksum;
  571. VOLSUM += 8.*vol;
  572. nleaves += 8; // reflects the number of kernel evaluations
  573. return; // is leaf
  574. }
  575. #ifdef LEMMAUSEVTK
  576. //--------------------------------------------------------------------------------------
  577. // Class: KernelV0
  578. // Method: EvaluateKids2 -- same as Evaluate Kids, but include VTK octree generation
  579. //--------------------------------------------------------------------------------------
  580. #ifdef LEMMA_VTK8_SUPPORT
  581. void KernelV0::EvaluateKids2( const Vector3r& size, const int& level, const Vector3r& cpos,
  582. const VectorXcr& parentVal, vtkHyperTreeGrid* oct, vtkHyperTreeCursor* curse) {
  583. #elif LEMMA_VTK9_SUPPORT
  584. void KernelV0::EvaluateKids2( const Vector3r& size, const int& level, const Vector3r& cpos,
  585. const VectorXcr& parentVal, vtkHyperTree* oct, vtkHyperTreeGridNonOrientedCursor* curse) {
  586. #endif
  587. int pdone = (int)(1e2*VOLSUM/(Size[0]*Size[1]*Size[2]));
  588. if (pdone > percent_done ) {
  589. percent_done = pdone;
  590. ++(*disp);
  591. }
  592. //disp->updateLastPrintedMessage("Number of leaves: " + std::to_string(nleaves));
  593. // Next level step, interested in one level below
  594. // bitshift requires one extra, faster than, and equivalent to std::pow(2, level+1)
  595. Vector3r step = size.array() / (Real)(1 << (level+1) );
  596. Real vol = (step(0)*step(1)*step(2)); // volume of each child
  597. Vector3r pos = cpos - step/2.;
  598. Eigen::Matrix<Real, 8, 3> posadd = (Eigen::Matrix<Real, 8, 3>() <<
  599. 0, 0, 0,
  600. step[0], 0, 0,
  601. 0, step[1], 0,
  602. step[0], step[1], 0,
  603. 0, 0, step[2],
  604. step[0], 0, step[2],
  605. 0, step[1], step[2],
  606. step[0], step[1], step[2] ).finished();
  607. MatrixXcr kvals(8, PulseI.size()); // individual kernel vals
  608. cpoints->ClearFields();
  609. for (int ichild=0; ichild<8; ++ichild) {
  610. Vector3r cp = pos; // Eigen complains about combining these
  611. cp += posadd.row(ichild);
  612. cpoints->SetLocation( ichild, cp );
  613. }
  614. Eigen::Matrix<Complex, 3, 8> Ht = Eigen::Matrix<Complex, 3, 8>::Zero();
  615. Eigen::Matrix<Complex, 3, 8> Hr = Eigen::Matrix<Complex, 3, 8>::Zero();
  616. for ( auto EMCalc : EMEarths ) {
  617. //EMCalc->GetFieldPoints()->ClearFields();
  618. EMCalc.second->CalculateWireAntennaFields();
  619. switch (EMCalc.second->GetTxRxMode()) {
  620. case TX:
  621. Ht += EMCalc.second->GetFieldPoints()->GetHfield(0);
  622. break;
  623. case RX:
  624. Hr += EMCalc.second->GetFieldPoints()->GetHfield(0);
  625. break;
  626. case TXRX:
  627. Ht += EMCalc.second->GetFieldPoints()->GetHfield(0);
  628. Hr += EMCalc.second->GetFieldPoints()->GetHfield(0);
  629. break;
  630. default:
  631. break;
  632. }
  633. }
  634. for (int ichild=0; ichild<8; ++ichild) {
  635. Vector3r cp = pos; // Eigen complains about combining these
  636. cp += posadd.row(ichild);
  637. kvals.row(ichild) = f(cp, vol, Ht.col(ichild), Hr.col(ichild));
  638. }
  639. VectorXcr ksum = kvals.colwise().sum(); // Kernel sum
  640. // Evaluate whether or not furthur splitting is needed
  641. if ( (((ksum - parentVal).array().abs() > tol).any() && level<maxLevel) || level < minLevel ) {
  642. // 0 after curse is vtkIdType?
  643. #ifdef LEMMA_VTK8_SUPPORT
  644. oct->SubdivideLeaf(curse, 0);
  645. #elif LEMMA_VTK9_SUPPORT
  646. curse->SubdivideLeaf();
  647. #endif
  648. for (int ichild=0; ichild<8; ++ichild) {
  649. curse->ToChild(ichild);
  650. Vector3r cp = pos; // Eigen complains about combining these
  651. cp += posadd.row(ichild);
  652. /* Test for position via alternative means */
  653. /*
  654. Real p[3];
  655. GetPosition(curse, p);
  656. if ( (Vector3r(p) - cp).norm() > 1e-8 ) {
  657. std::cout << "ERROR @ nleaves" << nleaves << "\n" << cp[0] << "\t" << p[0] << "\t" << cp[1] << "\t" << p[1]
  658. << "\t" << cp[2] << "\t" << p[2] << "\t" << vol<< std::endl;
  659. throw std::runtime_error("doom");
  660. }
  661. */
  662. /* End of position test */
  663. EvaluateKids2( size, level+1, cp, kvals.row(ichild), oct, curse );
  664. curse->ToParent();
  665. }
  666. return; // not a leaf
  667. }
  668. /* just stuff with sum of the kids and don't subdivide */
  669. /*
  670. LeafDict[curse->GetLeafId()] = ksum/(8.*vol);
  671. LeafDictIdx[curse->GetLeafId()] = nleaves;
  672. */
  673. /* Alternatively, subdivide the VTK octree here and stuff the children to make better
  674. * visuals, but also 8x the storage...
  675. */
  676. // 0 after curse is vtkIdType?
  677. #ifdef LEMMA_VTK8_SUPPORT
  678. oct->SubdivideLeaf(curse, 0);
  679. #elif LEMMA_VTK9_SUPPORT
  680. curse->SubdivideLeaf();
  681. #endif
  682. for (int ichild=0; ichild<8; ++ichild) {
  683. curse->ToChild(ichild);
  684. LeafDict[curse->GetVertexId()] = ksum/(8.*vol);
  685. LeafHt[curse->GetVertexId()] = Ht.col(ichild);
  686. LeafHr[curse->GetVertexId()] = Hr.col(ichild);
  687. LeafDictIdx[curse->GetVertexId()] = nleaves;
  688. curse->ToParent();
  689. }
  690. Kern.row(ilay) += ksum;
  691. VOLSUM += 8*vol;
  692. nleaves += 8; // good reason to say 1 or 8 here...8 sounds better and reflects kernel evaluations
  693. return; // is a leaf
  694. }
  695. //--------------------------------------------------------------------------------------
  696. // Class: KernelV0
  697. // Method: GetPosition
  698. //--------------------------------------------------------------------------------------
  699. void KernelV0::GetPosition( vtkHyperTreeCursor* Cursor, Real* p ) {
  700. // TODO fix
  701. /*
  702. Real ratio=1.0/(1<<(Cursor->GetCurrentLevel()));
  703. //step = ((Size).array() / std::pow(2.,Cursor->GetCurrentLevel()));
  704. p[0]=(Cursor->GetIndex(0)+.5)*ratio*this->Size[0]+this->Origin[0] ;//+ .5*step[0];
  705. p[1]=(Cursor->GetIndex(1)+.5)*ratio*this->Size[1]+this->Origin[1] ;//+ .5*step[1];
  706. p[2]=(Cursor->GetIndex(2)+.5)*ratio*this->Size[2]+this->Origin[2] ;//+ .5*step[2];
  707. */
  708. }
  709. #endif
  710. } // ---- end of namespace Lemma ----
  711. /* vim: set tabstop=4 expandtab */
  712. /* vim: set filetype=cpp */