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

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