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

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