TRIQS/nrgljubljana_interface 4.0.0
A TRIQS application
Loading...
Searching...
No Matches
solver_core.cpp
1/*******************************************************************************
2 *
3 * nrgljubljana_interface: A TRIQS interface to the nrgljubliana impurity solver
4 *
5 * Copyright (c) 2019 The Simons foundation
6 * authors: Rok Zitko, Nils Wentzell
7 *
8 * nrgljubljana_interface is free software: you can redistribute it and/or modify it under the
9 * terms of the GNU General Public License as published by the Free Software
10 * Foundation, either version 3 of the License, or (at your option) any later
11 * version.
12 *
13 * nrgljubljana_interface is distributed in the hope that it will be useful, but WITHOUT ANY
14 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
16 * details.
17 *
18 * You should have received a copy of the GNU General Public License along with
19 * nrgljubljana_interface. If not, see <http://www.gnu.org/licenses/>.
20 *
21 ******************************************************************************/
22#include "./solver_core.hpp"
23
24#include <triqs/utility/exceptions.hpp> // TRIQS_RUNTIME_ERROR
25#include <itertools/itertools.hpp>
26
27#include <algorithm> // max
28#include <cmath> // pow, log
29#include <cstdlib> // system
30#include <sys/stat.h> // mkdir
31#include <iostream>
32#include <fstream>
33#include <utility>
34#include <deque>
35#include <iomanip> // setprecision
36#include <limits> // max_digits10, MAX_PATH
37
38#include <boost/lexical_cast.hpp>
39#include <nrg-lib.hpp>
40
41#include <mpi/mpi.hpp>
42#include <mpi/string.hpp>
43
44#include "openmp.hpp"
45
46// std::filesystem is not production-ready as of 2020. As a workaround,
47// we remove temporary files using "rm".
48//
49//#ifdef __has_include
50//# if __has_include(<filesystem>)
51//# include <filesystem>
52//namespace fs = std::filesystem;
53//# elif __has_include(<experimental/filesystem>)
54//# include <experimental/filesystem>
55//namespace fs = std::experimental::filesystem;
56//# else
57//# error "Missing <filesystem>"
58//# endif
59//#endif
60
61namespace nrgljubljana_interface {
62
63 // Returns true if the GF structure is non-trivial, i.e., it has any elements at all.
64 bool has_struct(const gf_struct_t &s) {
65 unsigned int len = 0;
66 for (const auto &[bl_name, bl_size] : s) len += bl_size;
67 return len > 0;
68 }
69
71 if (world.rank() == 0)
72 report_openMP(); // important for performance, so we report the settings here for easy inspection by the user
73
74 gf_struct = read_structure("gf_struct", true); // true=mandatory
75 Delta_struct = read_structure("Delta_struct", false); // false=optional
76 if (!has_struct(Delta_struct))
77 Delta_struct = gf_struct; // default to equal structure of Delta and G
78 TRIQS_ASSERT2(has_struct(Delta_struct), "Delta_struct must be defined. template corrupted?");
79 chi_struct = read_structure("chi_struct", false); // false=optional
80
81 // Read model-specific template info file
82 std::ifstream F(constr_params.get_model_dir() + "/info");
83 if (!F) TRIQS_RUNTIME_ERROR << "Failed to open template info file";
84 auto getline = [&F](const std::string &keyword) -> std::string {
85 std::string s;
86 std::getline(F, s);
87 auto pos = s.find(':');
88 std::string keyword_found = s.substr(0, pos);
89 TRIQS_ASSERT2(keyword == keyword_found, "template info file is corrupted");
90 std::string value = s.substr(pos+1);
91 return value;
92 };
93 constr_params.ops = getline("ops");
94 constr_params.specs = getline("specs");
95 constr_params.specd = getline("specd");
96 constr_params.spect = getline("spect");
97 constr_params.specq = getline("specq");
98 constr_params.specot = getline("specot");
99 constr_params.params = getline("params");
100 constr_params.polarized = getline("polarized") == "true";
101
102 // Create the hybridization function on a logarithmic mesh
103 log_mesh = refreq_log{cp.mesh_min, cp.mesh_max, cp.mesh_ratio};
104 // Note: Delta may have a different structure from G.
105 Delta_w = g_w_t{log_mesh, Delta_struct};
106 // We also construct G_w and Sigma_w here to enable their initialization in the DMFT loops
107 // prior to solver calls.
108 if (has_struct(gf_struct)) {
109 G_w = g_w_t{log_mesh, gf_struct};
110 Sigma_w = g_w_t{log_mesh, gf_struct};
111 }
112 }
113
114 // -------------------------------------------------------------------------------
115
116 gf_struct_t solver_core::read_structure(const std::string &filename, bool mandatory = true) {
117 std::ifstream F(constr_params.get_model_dir() + "/" + filename);
118 if (mandatory && not F.is_open()) TRIQS_RUNTIME_ERROR << "Failed to open structure file " << filename;
119 gf_struct_t _gf_struct;
120 if (F) {
121 std::string bl_name;
122 int bl_size;
123 while (F >> bl_name >> bl_size) { _gf_struct.emplace_back(bl_name, bl_size); }
124 }
125 return _gf_struct;
126 }
127
128 void solver_core::readGF(const std::string &name, std::optional<g_w_t> &G_w, gf_struct_t &_gf_struct) {
129 if (!has_struct(_gf_struct))
130 return;
131 G_w = g_w_t{log_mesh, _gf_struct};
132 for (int bl_idx : range(_gf_struct.size())) {
133 long bl_size = Delta_w[bl_idx].target_shape()[0];
134 for (auto [i, j] : product_range(bl_size, bl_size)) {
135 auto bl_name = Delta_w.block_names()[bl_idx];
136 auto file_ending = std::string{"_"} + bl_name + "_" + std::to_string(i) + std::to_string(j) + ".dat";
137 std::string imGfilename = "im" + name + file_ending;
138 std::ifstream imG(imGfilename);
139 std::string reGfilename = "re" + name + file_ending;
140 std::ifstream reG(reGfilename);
141 if (imG && reG) {
142 double w, re, im;
143 for (auto mp : log_mesh) {
144 imG >> w >> im;
145 reG >> w >> re;
146 TRIQS_ASSERT2(abs(w-double(mp)) < 1e-8*abs(w), "frequency mismatch");
147 (*G_w)[bl_idx][mp](i, j) = re + 1i * im;
148 }
149 } else {
150 // If the files cannot be read (do not exist), the corresponding GF matrix component
151 // is zero-ed out.
152 for (auto mp : log_mesh) (*G_w)[bl_idx][mp](i, j) = 0.0;
153 }
154 }
155 }
156 }
157
158 void solver_core::readA(const std::string &name, std::optional<g_w_t> &A_w, gf_struct_t &_gf_struct) {
159 if (!has_struct(_gf_struct))
160 return;
161 A_w = g_w_t{log_mesh, _gf_struct};
162 for (int bl_idx : range(_gf_struct.size())) {
163 long bl_size = Delta_w[bl_idx].target_shape()[0];
164 for (auto [i, j] : product_range(bl_size, bl_size)) {
165 auto bl_name = Delta_w.block_names()[bl_idx];
166 auto file_ending = std::string{"_"} + bl_name + "_" + std::to_string(i) + std::to_string(j) + ".dat";
167 std::string Afilename = name + file_ending;
168 std::ifstream A(Afilename);
169 if (A) {
170 double w, re;
171 for (auto mp : log_mesh) {
172 A >> w >> re;
173 TRIQS_ASSERT2(abs(w-double(mp)) < 1e-8*abs(w), "frequency mismatch");
174 (*A_w)[bl_idx][mp](i, j) = re;
175 }
176 } else {
177 for (auto mp : log_mesh) (*A_w)[bl_idx][mp](i, j) = 0.0;
178 }
179 }
180 }
181 }
182
183 // Read expectation values and average over Nz runs
185 for (int cnt = 1; cnt <= Nz; cnt++) {
186 const std::string expvfilename = std::to_string(cnt) + "/customfdm";
187 std::ifstream F(expvfilename);
188 if (!F) TRIQS_RUNTIME_ERROR << "Expectation values output file not found.";
189 std::string snumber, skeyword, svalue;
190 getline(F, snumber); // snumber not used
191 getline(F, skeyword);
192 getline(F, svalue);
193 F.close();
194 skeyword.erase(0,1); // drop #
195 std::istringstream sskeyword(skeyword);
196 std::deque<std::string> keywords{std::istream_iterator<std::string>{sskeyword},
197 std::istream_iterator<std::string>{}};
198 std::istringstream ssvalue(svalue);
199 std::deque<double> values{std::istream_iterator<double>{ssvalue},
200 std::istream_iterator<double>{}};
201 TRIQS_ASSERT2(keywords.size() == values.size(), "customfdm corrupted");
202 keywords.pop_front(); // ignore first column (temperature)
203 values.pop_front();
204 for (auto [k, v] : zip(keywords, values)) expv[k] += v; // zeroed by default constructor
205 }
206 for (auto &i : expv) { i.second /= Nz; } // calculate the average over discretization meshes
207 }
208
209 // Read thermodynamic variables (FDM algorithm) and average over Nz runs
211 for (int cnt = 1; cnt <= Nz; cnt++) {
212 const std::string tdfdmfilename = std::to_string(cnt) + "/tdfdm";
213 std::ifstream F(tdfdmfilename);
214 if (!F) TRIQS_RUNTIME_ERROR << "Thermodynamic variables output file not found.";
215 std::string skeyword, svalue;
216 getline(F, skeyword);
217 getline(F, svalue);
218 F.close();
219 skeyword.erase(0,1); // drop #
220 std::istringstream sskeyword(skeyword);
221 std::deque<std::string> keywords{std::istream_iterator<std::string>{sskeyword},
222 std::istream_iterator<std::string>{}};
223 std::istringstream ssvalue(svalue);
224 std::deque<double> values{std::istream_iterator<double>{ssvalue},
225 std::istream_iterator<double>{}};
226 TRIQS_ASSERT2(keywords.size() == values.size(), "tdfdm corrupted");
227 keywords.pop_front(); // ignore first column (temperature)
228 values.pop_front();
229 for (auto [k, v] : zip(keywords, values)) tdfdm[k] += v; // zeroed by default constructor
230 }
231 for (auto &i : tdfdm) { i.second /= Nz; } // calculate the average over discretization meshes
232 }
233
234 inline void call(const std::string &command, bool verbose = true, bool exit_on_failure = true) {
235 std::string s = command + (verbose ? "" : " >/dev/null");
236 std::cout << "running " << s << std::endl;
237 if (system(s.c_str()) != 0) {
238 if (exit_on_failure)
239 TRIQS_RUNTIME_ERROR << "Failure running NRGLjubljana_interface script: " << s;
240 else
241 std::cerr << "Warning: failure running NRGLjubljana_interface script: " << s << std::endl;
242 }
243 }
244
245 // Write Gamma=-Im(Delta_w) to a file
247 for (int bl_idx : range(Delta_struct.size())) {
248 long bl_size = Delta_w[bl_idx].target_shape()[0];
249 auto bl_name = Delta_w.block_names()[bl_idx];
250 for (auto [i, j] : product_range(bl_size, bl_size)) {
251 std::ofstream F("Gamma_" + bl_name + "_" + std::to_string(i) + std::to_string(j) + ".dat");
252 F << std::setprecision(std::numeric_limits<double>::max_digits10); // number of decimal digits necessary to differentiate all values of this type
253 const double cutoff = 1e-8; // ensure hybridisation function is positive
254 for (auto w : Delta_w[bl_idx].mesh()) {
255 double value = -Delta_w[bl_idx][w](i, j).imag();
256 if (value < cutoff) { value = cutoff; }
257 F << double(w) << " " << value << std::endl;
258 }
259 }
260 }
261 }
262
263 inline std::string get_current_dir() {
264 char temp[PATH_MAX]; // on stack, no memory leak
265 return ( getcwd(temp, sizeof(temp)) ? std::string(temp) : std::string("") );
266 }
267
270 container_set::operator=(container_set{}); // Reset the results
271 std::string tempdir{};
272 if (world.rank() == 0) {
273 std::cout << "Starting NRG solver\n";
274 tempdir = create_tempdir(""); // Create a temporary directory for file-based interfacing (RAM disk is best)
275 }
276 world.barrier(); // Ensures temporary directory is created
277 mpi::broadcast(tempdir, world);
278 std::string cwd = get_current_dir();
279 if (chdir(tempdir.c_str()) != 0) TRIQS_RUNTIME_ERROR << "chdir to tempdir failed.";
280 if (world.rank() == 0) {
281 write_gamma();
282 // we need a mock param file for 'adapt' tool
284 call(constr_params.get_model_dir() + "/prepare", verbose);
285 call("./discretize", verbose);
286 for (int i: range(1,sp.Nz+1))
287 instantiate(double(i)/sp.Nz, std::to_string(i));
288 }
289 world.barrier(); // Ensures the initialization scripts have completed
290
291 // Perform the calculations in parallel
292 auto chunk = mpi::chunk(range(1,sp.Nz+1), world);
293 for (int i: chunk)
294 solve_one(std::to_string(i));
295
296 world.barrier(); // Ensures all subcalculations are completed
297 // Post-Processing in perl script
298 if (world.rank() == 0) {
299 std::cout << "Post-processing results" << std::endl;
300 call("./process", verbose);
301 }
302
303 world.barrier(); // Ensures post-processing is completed
304 // Read Results into TRIQS Containers
305 if (world.rank() == 0)
306 std::cout << "Reading results from files" << std::endl;
307 readexpv(sp.Nz);
308 readtdfdm(sp.Nz);
309 readGF("G", G_w, gf_struct);
310 readGF("F_l", F_l_w, gf_struct);
311 readGF("F_r", F_r_w, gf_struct);
312 readGF("I", I_w, gf_struct);
313 readGF("SigmaHartree", SigmaHartree_w, gf_struct);
314 readA("A", A_w, gf_struct);
315 readA("B_l", B_l_w, gf_struct);
316 readA("B_r", B_r_w, gf_struct);
317 readA("C", C_w, gf_struct);
318 readGF("SS", chi_SS_w, chi_struct);
319 readGF("NN", chi_NN_w, chi_struct);
320
321 // Post-Processing in C++ interface
322 if (has_struct(gf_struct)) {
323 Sigma_w = (*SigmaHartree_w) + (*I_w) - (*F_l_w) / (*G_w) * (*F_r_w);
324 }
325 // Cleanup
326 world.barrier(); // Ensures all processes have read the results before cleanup
327 if (chdir(cwd.c_str()) != 0) TRIQS_RUNTIME_ERROR << "failed to return from tempdir";
328 world.barrier(); // Ensures all processes have chdired from temp dir before it is deleted
329 if (world.rank() == 0 && !keep_temp_dir) {
330 // std::error_code ec;
331 // fs::remove_all(tempdir, ec);
332 // if (ec) std::cerr << "Warning: failed to remove the temporary directory." << std::endl;
333 // Workaround:
334 call("rm -rf " + tempdir, verbose, false);
335 }
336 }
337
338 // -------------------------------------------------------------------------------
339
341 const constr_params_t &cp = constr_params;
343 nrg_params_t &np = nrg_params; // only nrg_params allowed to be changed!
344
345 // Test if the low-level paramerers are sensible for use with the
346 // high-level interface.
347 if (np.discretization != "Z") TRIQS_RUNTIME_ERROR << "Must use discretization=Z in the high-level solver interface.";
348
349 // Automatically set (override) some low-level parameters
350 if (sp.Tmin > 0) { // If Tmin is set, determine the required length of the Wilson chain.
351 np.Nmax = 0;
352 auto scale = [=](int n) {
353 return (1. - 1. / sp.Lambda) / std::log(sp.Lambda) * std::pow(sp.Lambda, -(np.z - 1)) * std::pow(sp.Lambda, -(n - 1) / 2.);
354 };
355 while (scale(np.Nmax + 1) >= sp.Tmin) np.Nmax++;
356 }
357 if (np.mMAX < 0) // Determine the number of sites in the star representation
358 np.mMAX = std::max(80, 2 * np.Nmax);
359 if (np.xmax < 0) // Length of the x-interval in the discretization=Z (ODE) approach
360 np.xmax = np.Nmax / 2. + 2.;
361 if (sp.bandrescale < 0) // Make the NRG energy window correspond to the extent of the frequency mesh
362 sp.bandrescale = cp.mesh_max;
363 // Ensure the selected method is enabled. Other methods may be enabled as well, but only the output files for the selected method well be read-in by the nrglj-interface.
364 TRIQS_ASSERT2(sp.method == "fdm", "currently only method=fdm is supported"); // TODO
365 if (sp.method == "fdm") { np.fdm = true; }
366 if (sp.method == "dmnrg") { np.dmnrg = true; }
367 if (sp.method == "cfs") { np.cfs = true; }
368 if (sp.method == "finite") { np.finite = true; }
369 }
370
371 void solver_core::set_nrg_params(nrg_params_t const &nrg_params_) { nrg_params = nrg_params_; }
372
373 // Creates input files for NRG iteration (param & data) by calling the "instantiate" script
374 void solver_core::instantiate(double z, const std::string &taskdir) {
375 std::cout << "Preparing z=" << z << " taskdir=" << taskdir << std::endl;
376 TRIQS_ASSERT(world.rank() == 0); // should not run in parallel!
378 if (mkdir(taskdir.c_str(), 0755) != 0) TRIQS_RUNTIME_ERROR << "failed to mkdir taskdir " << taskdir;
379 call("./instantiate " + taskdir, verbose);
380 }
381
382 // Solve the problem for a single value of the twist parameter z
383 void solver_core::solve_one(const std::string &taskdir) {
384 std::cout << "Solving taskdir=" << taskdir << " rank=" << world.rank() << std::endl;
385 if (chdir(taskdir.c_str()) != 0) TRIQS_RUNTIME_ERROR << "failed to chdir to taskdir " << taskdir;
386 // Solve the impurity model
387 std::streambuf *old = std::cout.rdbuf();
388 std::ofstream log_stream;
389 if (!verbose) {
390 log_stream.open("log");
391 if (!log_stream) TRIQS_RUNTIME_ERROR << "failed to open log file";
392 std::cout.rdbuf(log_stream.rdbuf()); // redirect stdout to log file
393 }
394 NRG::set_workdir(""); // Defaults to . but may be overridden by NRG_WORKDIR in the environment
395 NRG::run_nrg_master("");
396 if (!verbose) std::cout.rdbuf(old); // restore
397 if (chdir("..") != 0) TRIQS_RUNTIME_ERROR << "failed to return from taskdir " << taskdir;
398 }
399
400 std::string solver_core::create_tempdir(const std::string &tempdir_ = "") {
401 const std::string default_tempdir = ".";
402 std::string tempdir = default_tempdir;
403 if (const char *env_w = std::getenv("NRG_TEMPDIR")) tempdir = env_w;
404 if (!tempdir_.empty()) tempdir = tempdir_;
405 const std::string tempdir_template = tempdir + "/nrg_tempdir_XXXXXX";
406 size_t len = tempdir_template.length()+1;
407 auto x = std::make_unique<char[]>(len); // NOLINT
408 strncpy(x.get(), tempdir_template.c_str(), len);
409 if (auto w = mkdtemp(x.get())) // create a unique directory
410 return w;
411 else
412 TRIQS_RUNTIME_ERROR << "Failed to create a directory for temporary files.";
413 }
414
416 std::istringstream ss(constr_params.params);
417 do {
418 std::string p;
419 ss >> p;
420 if (p != "" && sp.model_parameters.count(p) != 1)
421 TRIQS_RUNTIME_ERROR << "Model parameter " << p << " has not been defined.";
422 } while (ss);
423 }
424
426 const constr_params_t &cp = constr_params;
429 np.z = z;
430 // Automatically establish appropriate default values for the high-level interface
431 set_params();
432 // Check if all model parameters have been defined
434 // Generate the parameter file
435 std::ofstream F("param");
436 F << std::boolalpha; // important: we want to output true/false strings
437 F << std::setprecision(std::numeric_limits<double>::max_digits10); // number of decimal digits necessary to differentiate all values of this type
438 F << "[extra]" << std::endl;
439 for (const auto &i : sp.model_parameters) F << i.first << "=" << i.second << std::endl;
440 F << "[param]" << std::endl;
441 F << "bandrescale=" << sp.bandrescale << std::endl; // !
442 F << "model=" << cp.model << std::endl;
443 F << "symtype=" << cp.symtype << std::endl;
444 F << "Lambda=" << sp.Lambda << std::endl;
445 F << "xmax=" << np.xmax << std::endl;
446 F << "Nmax=" << np.Nmax << std::endl;
447 F << "mMAX=" << np.mMAX << std::endl;
448 F << "keep=" << sp.keep << std::endl;
449 F << "keepenergy=" << sp.keepenergy << std::endl;
450 F << "keepmin=" << sp.keepmin << std::endl;
451 F << "T=" << sp.T << std::endl;
452 F << "ops=" << cp.ops << std::endl;
453 F << "specs=" << cp.specs << std::endl;
454 F << "specd=" << cp.specd << std::endl;
455 F << "spect=" << cp.spect << std::endl;
456 F << "specq=" << cp.specq << std::endl;
457 F << "specot=" << cp.specot << std::endl;
458 F << "specgt=" << np.specgt << std::endl;
459 F << "speci1t=" << np.speci1t << std::endl;
460 F << "speci2t=" << np.speci2t << std::endl;
461 F << "specchit=" << cp.specchit << std::endl;
462 F << "specv3=" << cp.specv3 << std::endl;
463 F << "v3mm=" << np.v3mm << std::endl;
464 F << "dmnrg=" << np.dmnrg << std::endl;
465 F << "cfs=" << np.cfs << std::endl;
466 F << "fdm=" << np.fdm << std::endl;
467 F << "fdmexpv=" << np.fdmexpv << std::endl;
468 F << "dmnrgmats=" << np.dmnrgmats << std::endl;
469 F << "fdmmats=" << np.fdmmats << std::endl;
470 F << "mats=" << np.mats << std::endl;
471 F << "alpha=" << sp.alpha << std::endl;
472 F << "gamma=" << sp.gamma << std::endl; // ?
473 F << "discretization=" << np.discretization << std::endl;
474 F << "z=" << np.z << std::endl;
475 F << "Nz=" << sp.Nz << std::endl; // !
476 F << "polarized=" << cp.polarized << std::endl;
477 F << "pol2x2=" << cp.pol2x2 << std::endl;
478 F << "rungs=" << cp.rungs << std::endl;
479 F << "tri=" << np.tri << std::endl;
480 F << "preccpp=" << np.preccpp << std::endl;
481 F << "diag=" << np.diag << std::endl;
482 F << "diagratio=" << np.diagratio << std::endl;
483 F << "dsyevrlimit=" << np.dsyevrlimit << std::endl;
484 F << "zheevrlimit=" << np.zheevrlimit << std::endl;
485 F << "restart=" << np.restart << std::endl;
486 F << "restartfactor=" << np.restartfactor << std::endl;
487 F << "safeguard=" << np.safeguard << std::endl;
488 F << "safeguardmax=" << np.safeguardmax << std::endl;
489 F << "fixeps=" << np.fixeps << std::endl;
490 F << "betabar=" << np.betabar << std::endl;
491 F << "gtp=" << np.gtp << std::endl;
492 F << "chitp=" << np.chitp << std::endl;
493 F << "finite=" << np.finite << std::endl;
494 F << "cfsgt=" << np.cfsgt << std::endl;
495 F << "cfsls=" << np.cfsls << std::endl;
496 F << "fdmgt=" << np.fdmgt << std::endl;
497 F << "fdmls=" << np.fdmls << std::endl;
498 F << "fdmexpvn=" << np.fdmexpvn << std::endl;
499 F << "finitemats=" << np.finitemats << std::endl;
500 F << "dm=" << np.dm << std::endl;
501 F << "broaden_max=" << cp.mesh_max << std::endl; // !
502 F << "broaden_min=" << cp.mesh_min << std::endl; // !
503 F << "broaden_ratio=" << cp.mesh_ratio << std::endl; // !
504 F << "broaden_min_ratio=" << np.broaden_min_ratio << std::endl; // keep this one?
505 F << "omega0=" << np.omega0 << std::endl;
506 F << "omega0_ratio=" << np.omega0_ratio << std::endl;
507 F << "diagth=" << np.diagth << std::endl;
508 F << "substeps=" << np.substeps << std::endl;
509 F << "strategy=" << np.strategy << std::endl;
510 F << "Ninit=" << np.Ninit << std::endl;
511 F << "reim=" << np.reim << std::endl;
512 F << "dumpannotated=" << np.dumpannotated << std::endl;
513 F << "dumpabs=" << np.dumpabs << std::endl;
514 F << "dumpscaled=" << np.dumpscaled << std::endl;
515 F << "dumpprecision=" << np.dumpprecision << std::endl;
516 F << "dumpgroups=" << np.dumpgroups << std::endl;
517 F << "grouptol=" << np.grouptol << std::endl;
518 F << "dumpdiagonal=" << np.dumpdiagonal << std::endl;
519 F << "savebins=" << np.savebins << std::endl;
520 F << "broaden=" << np.broaden << std::endl;
521 F << "emin=" << np.emin << std::endl;
522 F << "emax=" << np.emax << std::endl;
523 F << "bins=" << np.bins << std::endl;
524 F << "accumulation=" << np.accumulation << std::endl;
525 F << "linstep=" << np.linstep << std::endl;
526 F << "discard_trim=" << np.discard_trim << std::endl;
527 F << "discard_immediately=" << np.discard_immediately << std::endl;
528 F << "goodE=" << np.goodE << std::endl;
529 F << "NN1=" << np.NN1 << std::endl;
530 F << "NN2even=" << np.NN2even << std::endl;
531 F << "NN2avg=" << np.NN2avg << std::endl;
532 F << "NNtanh=" << np.NNtanh << std::endl;
533 F << "width_td=" << np.width_td << std::endl;
534 F << "width_custom=" << np.width_custom << std::endl;
535 F << "prec_td=" << np.prec_td << std::endl;
536 F << "prec_custom=" << np.prec_custom << std::endl;
537 F << "prec_xy=" << np.prec_xy << std::endl;
538 F << "resume=" << np.resume << std::endl;
539 F << "log=" << np.log << std::endl;
540 F << "logall=" << np.logall << std::endl;
541 F << "done=" << np.done << std::endl;
542 F << "calc0=" << np.calc0 << std::endl;
543 F << "lastall=" << np.lastall << std::endl;
544 F << "lastalloverride=" << np.lastalloverride << std::endl;
545 F << "dumpsubspaces=" << np.dumpsubspaces << std::endl;
546 F << "dump_f=" << np.dump_f << std::endl;
547 F << "dumpenergies=" << np.dumpenergies << std::endl;
548 F << "logenumber=" << np.logenumber << std::endl;
549 F << "stopafter=" << np.stopafter << std::endl;
550 F << "forcestop=" << np.forcestop << std::endl;
551 F << "removefiles=" << np.removefiles << std::endl;
552 F << "noimag=" << np.noimag << std::endl;
553 F << "checksumrules=" << np.checksumrules << std::endl;
554 F << "checkdiag=" << np.checkdiag << std::endl;
555 F << "checkrho=" << np.checkrho << std::endl;
556 F << "data_has_rescaled_energies=false" << std::endl; // NRGLj-TRIQS interface uses unscaled energies
557 }
558
559 // -------------------------------------------------------------------------------
560
561 // Function that writes a solver object to hdf5 file
562
563 void h5_write(h5::group h5group, std::string subgroup_name, solver_core const &s) {
564 auto grp = h5group.create_group(subgroup_name);
565 h5_write_attribute(grp, "Format", solver_core::hdf5_format());
566 h5_write_attribute(grp, "TRIQS_GIT_HASH", std::string(AS_STRING(TRIQS_GIT_HASH)));
567 h5_write_attribute(grp, "NRGLJUBLJANA_INTERFACE_GIT_HASH", std::string(AS_STRING(NRGLJUBLJANA_INTERFACE_GIT_HASH)));
568 h5_write(grp, "", s.result_set());
569 h5_write(grp, "constr_params", s.constr_params);
570 h5_write(grp, "nrg_params", s.nrg_params);
571 h5_write(grp, "last_solve_params", s.last_solve_params);
572 h5_write(grp, "Delta_w", s.Delta_w); // !!
573 }
574
575 // Function that constructs a solver object from an hdf5 file
576 solver_core solver_core::h5_read_construct(h5::group h5group, std::string subgroup_name) {
577 auto grp = h5group.open_group(subgroup_name);
578 auto constr_params = h5_read<constr_params_t>(grp, "constr_params");
579 auto s = solver_core{constr_params};
580 h5_read(grp, "", s.result_set());
581 h5_read(grp, "nrg_params", s.nrg_params);
582 h5_read(grp, "last_solve_params", s.last_solve_params);
583 h5_read(grp, "Delta_w", s.Delta_w);
584 return s;
585 }
586
587 // Hilbert transform for refreq objects
588 std::complex<double> hilbert_transform_refreq(const c_w_cvt &gf, std::complex<double> z){
589 return hilbert_transform(gf, z);
590 }
591
592 matrix<std::complex<double>> hilbert_transform_elementwise(const m_w_cvt &gf, std::complex<double> z) {
593 return hilbert_transform_elementwise(gf, z);
594 }
595
596} // namespace nrgljubljana_interface
nrg_params_t nrg_params
Low-level NRG parameters.
std::optional< solve_params_t > last_solve_params
Parameters used for the most recent solve process.
static std::string hdf5_format()
HDF5 format tag for the solver object.
void readtdfdm(int Nz)
Read thermodynamic variables (FDM algorithm) from the NRG output files.
constr_params_t constr_params
Parameters used for the solver construction.
C2PY_IGNORE void readGF(const std::string &name, std::optional< g_w_t > &G_w, gf_struct_t &_gf_struct)
Read a block Green's function from (im/re)name-block-ij.dat files.
refreq_log log_mesh
Logarithmic real-frequency mesh.
g_w_t Delta_w
The hybridization function on the real-frequency axis.
friend void h5_write(h5::group h5group, std::string subgroup_name, solver_core const &s)
Write a solver object to an HDF5 file.
void solve(solve_params_t const &solve_params)
Solve the impurity problem.
void generate_param_file(double z)
Produce the param file for a given value of the twist parameter .
gf_struct_t gf_struct
The Green's function structure object.
void check_model_params(const solve_params_t &sp)
Check that all required model parameters have been defined.
gf_struct_t Delta_struct
The hybridization function structure object.
solver_core(constr_params_t cp)
Construct an NRGLjubljana_interface solver.
void set_params()
Establish good defaults for the low-level NRG parameters.
gf_struct_t chi_struct
The susceptibility structure object.
std::string create_tempdir(const std::string &tempdir_)
Create a temporary working directory for a series of NRG runs.
C2PY_IGNORE void readA(const std::string &name, std::optional< g_w_t > &A_w, gf_struct_t &_gf_struct)
Read a block spectral function from name-block-ij.dat files.
gf_struct_t read_structure(const std::string &filename, bool mandatory)
Read the block structure of Green's function objects from a file.
void solve_one(const std::string &taskdir)
Perform an individual NRG calculation. Called from solve().
void readexpv(int Nz)
Read expectation values from the NRG output files.
void set_nrg_params(nrg_params_t const &nrg_params)
Adjust the advanced (low-level) NRG parameters.
void write_gamma()
Write to a file.
bool verbose
If true, detailed output from NRGLjubljana and its tools is sent to stdout.
bool keep_temp_dir
Keep the temporary directories after the calculation.
void instantiate(double z, const std::string &taskdir)
Prepare the input files for an individual NRG calculation. Called from solve().
static C2PY_IGNORE solver_core h5_read_construct(h5::group h5group, std::string subgroup_name)
Construct a solver object from an HDF5 file.
Construction parameters for the NRGLjubljana solver.
Definition params.hpp:28
double mesh_max
Maximum frequency of the logarithmic mesh.
Definition params.hpp:56
std::string specd
Spectral functions of doublet operators to compute.
Definition params.hpp:80
std::string symtype
Symmetry type (NRGLjubljana symmetry code, e.g. QS, QSZ, ISO).
Definition params.hpp:37
std::string specq
Spectral functions of quadruplet operators to compute.
Definition params.hpp:86
std::string model
Impurity model to solve (selects a template directory).
Definition params.hpp:34
std::string specv3
3-leg vertex functions to compute.
Definition params.hpp:95
std::string specot
Spectral functions of orbital-triplet operators to compute.
Definition params.hpp:89
std::string specs
Spectral functions of singlet operators to compute.
Definition params.hpp:77
std::string specchit
Susceptibilities to compute.
Definition params.hpp:92
double mesh_min
Minimum frequency of the logarithmic mesh.
Definition params.hpp:59
bool pol2x2
Use a 2x2 spin structure in the Wilson chain.
Definition params.hpp:68
bool polarized
Use a spin-polarized Wilson chain.
Definition params.hpp:65
std::string ops
Operators whose expectation values are to be calculated.
Definition params.hpp:74
bool rungs
Include channel-mixing terms in the Wilson chain.
Definition params.hpp:71
double mesh_ratio
Common ratio of the geometric (logarithmic) frequency mesh.
Definition params.hpp:62
std::string spect
Spectral functions of triplet operators to compute.
Definition params.hpp:83
Collection of all output containers held by the solver.
std::optional< g_w_t > G_w
The retarded Green's function .
std::map< std::string, double > expv
Expectation values of local impurity operators.
std::optional< g_w_t > Sigma_w
The retarded self-energy (computed from , , and ).
std::optional< g_w_t > B_l_w
The spectral function of the auxiliary correlator .
std::optional< g_w_t > F_l_w
The auxiliary Green's function .
std::optional< g_w_t > F_r_w
The auxiliary Green's function .
std::optional< g_w_t > I_w
The auxiliary Green's function .
std::optional< g_w_t > SigmaHartree_w
Constant Hartree shift to the self-energy, stored as a Green's function.
std::optional< g_w_t > B_r_w
The spectral function of the auxiliary correlator .
std::map< std::string, double > tdfdm
Thermodynamic variables (FDM algorithm).
std::optional< g_w_t > C_w
The spectral function of the auxiliary correlator .
friend void h5_read(h5::group h5group, std::string subgroup_name, container_set &c)
Read all containers from an HDF5 file.
std::optional< g_w_t > chi_SS_w
Spin susceptibility .
std::optional< g_w_t > chi_NN_w
Charge susceptibility .
std::optional< g_w_t > A_w
The spectral function .
Low-level NRG parameters.
Definition params.hpp:154
bool fdmmats
Perform the FDM calculation on the Matsubara axis.
Definition params.hpp:172
double z
Parameter (twist) in the logarithmic discretization.
Definition params.hpp:202
double discard_trim
Peak clipping at the end of the run.
Definition params.hpp:337
size_t dsyevrlimit
Minimal matrix size for dsyevr.
Definition params.hpp:217
std::string discretization
Discretization scheme.
Definition params.hpp:199
int mMAX
Number of sites in the star representation ( : automatically determined).
Definition params.hpp:190
bool checkdiag
Test the diagonalisation results.
Definition params.hpp:421
bool fdm
Perform an FDM (full-density-matrix) calculation.
Definition params.hpp:163
double betabar
Parameter for thermodynamics.
Definition params.hpp:238
bool dumpabs
Dump in terms of absolute energies.
Definition params.hpp:298
bool removefiles
Remove temporary data files.
Definition params.hpp:412
double diagratio
Ratio of eigenstates computed in partial diagonalisation.
Definition params.hpp:214
std::string tri
Tridiagonalisation approach.
Definition params.hpp:205
double emin
Lower binning limit.
Definition params.hpp:322
bool v3mm
Compute the 3-leg vertex on the Matsubara/Matsubara axis.
Definition params.hpp:187
bool dump_f
Dump matrix elements.
Definition params.hpp:397
bool fdmls
Compute the FDM lesser correlation function.
Definition params.hpp:259
size_t Ninit
Number of initial Wilson chain operators.
Definition params.hpp:289
int Nmax
Number of sites in the Wilson chain ( : automatically determined).
Definition params.hpp:193
bool dmnrgmats
Perform the DMNRG calculation on the Matsubara axis.
Definition params.hpp:169
bool NN1
Perform N/N+1 patching.
Definition params.hpp:346
size_t safeguardmax
Maximal number of additional states to keep.
Definition params.hpp:232
size_t dumpprecision
Number of digits of precision used when dumping.
Definition params.hpp:304
bool cfsgt
Compute the CFS greater correlation function.
Definition params.hpp:250
bool noimag
Do not output the imaginary parts of expectation values.
Definition params.hpp:415
double discard_immediately
Peak clipping on the fly.
Definition params.hpp:340
bool resume
Attempt to restart the calculation.
Definition params.hpp:373
double fixeps
Threshold value for eigenvalue splitting corrections.
Definition params.hpp:235
bool cfs
Perform a CFS (complete Fock space) calculation.
Definition params.hpp:160
double restartfactor
Rescale factor used when restart is true.
Definition params.hpp:226
bool reim
Output the imaginary parts of the correlators.
Definition params.hpp:292
bool dm
Compute density matrices.
Definition params.hpp:268
size_t logenumber
Number of eigenvalues to show for log=e.
Definition params.hpp:403
int forcestop
Force stop at the given iteration (-1: disabled).
Definition params.hpp:409
std::string specgt
Conductance curves to compute.
Definition params.hpp:178
std::string stopafter
Stop the calculation at a given point.
Definition params.hpp:406
size_t dumpdiagonal
Dump diagonal matrix elements.
Definition params.hpp:313
double chitp
Parameter for calculations.
Definition params.hpp:244
bool dumpsubspaces
Save detailed subspace info.
Definition params.hpp:394
double broaden_min_ratio
Auto-tune the broaden_min parameter.
Definition params.hpp:271
size_t prec_td
Precision of columns in the 'td' output file.
Definition params.hpp:364
bool checksumrules
Check operator sum rules.
Definition params.hpp:418
bool dumpenergies
Dump all energies to a file.
Definition params.hpp:400
bool restart
Restart the calculation to achieve the truncation goal.
Definition params.hpp:223
std::string speci1t
curves to compute.
Definition params.hpp:181
double NNtanh
Parameter in the window function.
Definition params.hpp:355
bool NN2avg
Average over even and odd N/N+2 spectra.
Definition params.hpp:352
std::string strategy
Recalculation strategy.
Definition params.hpp:286
bool calc0
Perform calculations at the 0-th iteration.
Definition params.hpp:385
double gtp
Parameter for calculations.
Definition params.hpp:241
bool fdmexpv
Calculate expectation values using the FDM algorithm.
Definition params.hpp:166
double grouptol
Energy tolerance for considering two states as degenerate.
Definition params.hpp:310
bool finitemats
Perform a calculation on the Matsubara axis.
Definition params.hpp:265
size_t width_custom
Width of columns in the 'custom' output file.
Definition params.hpp:361
bool dumpscaled
Dump using omega_N energy units.
Definition params.hpp:301
size_t width_td
Width of columns in the 'td' output file.
Definition params.hpp:358
bool dumpgroups
Dump by grouping degenerate states.
Definition params.hpp:307
size_t preccpp
Precision for tridiagonalisation.
Definition params.hpp:208
bool lastalloverride
Override the automatic lastall setting.
Definition params.hpp:391
double goodE
Energy window parameter for patching.
Definition params.hpp:343
double linstep
Bin width for the linear mesh.
Definition params.hpp:334
bool savebins
Save binned (unbroadened) data.
Definition params.hpp:316
bool NN2even
Use even iterations in N/N+2 patching.
Definition params.hpp:349
double emax
Upper binning limit.
Definition params.hpp:325
double xmax
Largest in the discretization ODE solver ( : automatically determined).
Definition params.hpp:196
bool cfsls
Compute the CFS lesser correlation function.
Definition params.hpp:253
bool fdmgt
Compute the FDM greater correlation function.
Definition params.hpp:256
size_t bins
Number of bins per decade for spectral data.
Definition params.hpp:328
size_t mats
Number of Matsubara points to collect.
Definition params.hpp:175
bool broaden
Enable broadening of spectra.
Definition params.hpp:319
bool lastall
Keep all states in the last iteration for DMNRG.
Definition params.hpp:388
std::string diag
Eigensolver routine (dsyev|dsyevr|zheev|zheevr|default).
Definition params.hpp:211
std::string speci2t
curves to compute.
Definition params.hpp:184
double omega0
Smallest energy scale in the problem, .
Definition params.hpp:274
size_t prec_xy
Precision of the spectral function output.
Definition params.hpp:370
size_t dumpannotated
Number of eigenvalues to dump.
Definition params.hpp:295
size_t zheevrlimit
Minimal matrix size for zheevr.
Definition params.hpp:220
double accumulation
Shift of the accumulation points for binning.
Definition params.hpp:331
size_t fdmexpvn
Iteration at which the expectation values are evaluated.
Definition params.hpp:262
bool done
Create a DONE file.
Definition params.hpp:382
double safeguard
Additional states to keep in case of a near degeneracy.
Definition params.hpp:229
bool finite
Perform a Costi-Hewson-Zlatic finite-T calculation.
Definition params.hpp:247
int diagth
Number of diagonalisation threads.
Definition params.hpp:280
size_t prec_custom
Precision of columns in the 'custom' output file.
Definition params.hpp:367
std::string log
List of tokens defining what to log.
Definition params.hpp:376
bool dmnrg
Perform a DMNRG (density-matrix NRG) calculation.
Definition params.hpp:157
bool substeps
Use the interleaved diagonalization scheme.
Definition params.hpp:283
Parameters for the solve() method.
Definition params.hpp:108
double Lambda
Logarithmic discretization parameter.
Definition params.hpp:111
int Nz
Number of discretization meshes (interleaved twist parameters z).
Definition params.hpp:114
size_t keepmin
Minimum number of states to keep at each NRG step.
Definition params.hpp:126
double bandrescale
Band rescaling factor (half-width of the support of the hybridisation function); set to mesh_max if n...
Definition params.hpp:141
std::map< std::string, double > model_parameters
Model parameters (name to value map, e.g. U1, eps1).
Definition params.hpp:144
double gamma
Parameter for the Gaussian convolution step.
Definition params.hpp:135
std::string method
Method for calculating the dynamical quantities.
Definition params.hpp:138
double alpha
Width of the logarithmic gaussian used for broadening.
Definition params.hpp:132
double keepenergy
Cut-off energy for truncation.
Definition params.hpp:123
double Tmin
Lowest energy scale on the Wilson chain.
Definition params.hpp:117
size_t keep
Maximum number of states to keep at each NRG step.
Definition params.hpp:120