Surface NMR forward modelling
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

KernelV0.cpp 34KB

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