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

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