id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,535,528
|
test_common.cpp
|
rokzitko_nrgljubljana/test/unit/test_common/test_common.cpp
|
#include <string>
#include <sstream>
#include <gtest/gtest.h>
#include "test_common.hpp"
#include <invar.hpp>
#include <subspaces.hpp>
#include <core.hpp>
using namespace NRG;
TEST(test_common, basic) {
Params P;
P.logstr.set_str("!");
auto Sym = set_symmetry<double>(P, "QS", 1);
EXPECT_EQ(P.combs, 4);
EXPECT_EQ(Sym->nr_combs(), 4);
}
TEST(test_common_2, basic) {
Params P;
P.logstr.set_str("!");
auto Sym = set_symmetry<double>(P, "QS", 2);
EXPECT_EQ(P.combs, 16);
EXPECT_EQ(Sym->nr_combs(), 16);
}
TEST(test_common_cplx, basic) {
Params P;
P.logstr.set_str("!");
auto Sym = set_symmetry<std::complex<double>>(P, "QS", 1);
EXPECT_EQ(P.combs, 4);
EXPECT_EQ(Sym->nr_combs(), 4);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); // NOLINT
}
| 834
|
C++
|
.cpp
| 33
| 23
| 60
| 0.659119
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,529
|
unitary2.cpp
|
rokzitko_nrgljubljana/test/unit/unitary/unitary2.cpp
|
#include <gtest/gtest.h>
#include "unitary/unitary.hpp"
#include <string>
#include <cmake_configure.hpp>
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <array>
#include <vector>
#include <traits.hpp>
#include <numerics.hpp>
#include "compare.hpp"
using namespace NRG::Unitary;
using namespace NRG;
using namespace std::string_literals;
std::string exec(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe)
throw std::runtime_error("popen() failed!");
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr)
result += buffer.data();
return result;
}
TEST(unitary, unitary_help){
auto out = exec(PROJECT_BINARY_DIR "/tools/unitary -h");
std::string expected = "Usage: unitary [-h] [-b | -B] [-qvV] [-tl] [-s scale] [-o output_fn] [-c chop_tol] <A> <B> <C>\n";
EXPECT_EQ(out, expected);
}
class unitaryProdTest : public ::testing::Test {
protected:
void SetUp() override{
A = read_matrix("txt/matrix_A.txt");
B = read_matrix("txt/matrix_B.txt");
C = read_matrix("txt/matrix_C.txt");
}
void TearDown() override{
std::remove("txt/temp_result_matrix.txt");
}
void Compare() {
EigenMatrix<double> D = B*C;
my_result = A*D;
func_result = read_matrix("txt/temp_result_matrix.txt");
EXPECT_TRUE(my_result.isApprox(func_result));
}
EigenMatrix<double> A;
EigenMatrix<double> B;
EigenMatrix<double> C;
EigenMatrix<double> my_result;
EigenMatrix<double> func_result;
};
TEST_F(unitaryProdTest, noTrans_noScale){
auto out = exec(PROJECT_BINARY_DIR "/tools/unitary -q -o txt/temp_result_matrix.txt txt/matrix_A.txt txt/matrix_B.txt txt/matrix_C.txt");
std::cout << out << std::endl;
Compare();
}
TEST_F(unitaryProdTest, Trans_noScale){
auto out = exec(PROJECT_BINARY_DIR "/tools/unitary -t -q -o txt/temp_result_matrix.txt txt/matrix_A.txt txt/matrix_B.txt txt/matrix_C.txt"); // t = transpose first (A)
std::cout << out << std::endl;
A.transposeInPlace();
Compare();
}
TEST_F(unitaryProdTest, Trans_Scale){
auto out = exec(PROJECT_BINARY_DIR "/tools/unitary -s 2 -t -q -o txt/temp_result_matrix.txt txt/matrix_A.txt txt/matrix_B.txt txt/matrix_C.txt");
std::cout << out << std::endl;
A.transposeInPlace();
A = 2.0*A;
Compare();
}
| 2,524
|
C++
|
.cpp
| 71
| 30.915493
| 171
| 0.652317
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,530
|
mk_sym.cpp
|
rokzitko_nrgljubljana/test/unit/mk_sym/mk_sym.cpp
|
#include <gtest/gtest.h>
#include <complex>
#include <mk_sym.hpp>
#include <symmetry.hpp>
#include <params.hpp>
#include <outfield.hpp>
using namespace NRG;
TEST(mk_sym, QS) {
Params P;
auto sym = mk_QS<double>(P);
}
TEST(mk_sym, QSZ) {
Params P;
auto sym = mk_QSZ<double>(P);
}
TEST(mk_sym, get) {
Params P;
auto sym = get<double>("QS", P);
}
TEST(mk_sym, QS_complex) {
Params P;
auto sym = mk_QS<std::complex<double>>(P);
}
TEST(mk_sym, QSZ_complex) {
Params P;
auto sym = mk_QSZ<std::complex<double>>(P);
}
TEST(mk_sym, get_complex) {
Params P;
auto sym = get<std::complex<double>>("QS", P);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 735
|
C++
|
.cpp
| 35
| 18.914286
| 48
| 0.663295
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,531
|
workdir.cpp
|
rokzitko_nrgljubljana/test/unit/workdir/workdir.cpp
|
#include <string>
using namespace std::string_literals;
#include <gtest/gtest.h>
#include <workdir.hpp>
using namespace NRG;
TEST(workdir, workdir) {
Workdir workdir("testdir", true); // true=quiet
EXPECT_EQ(workdir.get(), "."); // because no testdir/, this defaulted to .
EXPECT_EQ(workdir.rhofn(1, "rho"), "./rho1"s);
EXPECT_EQ(workdir.unitaryfn(1), "./unitary1"s);
}
TEST(workdir, dtemp) {
Workdir workdir(".", true); // true=quiet
EXPECT_EQ(workdir.get().size(), 8); // ./XXXXXX
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 607
|
C++
|
.cpp
| 19
| 29.789474
| 76
| 0.684932
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,532
|
test_clean.cpp
|
rokzitko_nrgljubljana/test/unit/test_clean/test_clean.cpp
|
#include <string>
#include <sstream>
#include <gtest/gtest.h>
// Reproduce test/c++/test0_clean calculation
#include "test_common.hpp"
#include "test_clean.hpp"
#include <basicio.hpp>
#include <core.hpp>
using namespace NRG;
TEST(Clean, H) { // NOLINT
Params P;
setup_P_clean(P);
auto SymSP = setup_Sym<double>(P); // get the shared pointer
auto Sym = SymSP.get(); // get the raw pointer
Stats<double> stats(P, Sym->get_td_fields(), 0.0);
Step step{P, RUNTYPE::NRG};
EXPECT_EQ(step.ndx(), 0);
Store<double> store(P.Ninit,P.Nlen);
auto diagprev = setup_diag_clean(P, Sym);
auto operators = setup_operators_clean<double>(diagprev);
operators.opch = setup_opch_clean(P, Sym, diagprev);
auto coef = setup_coef_clean<double>(P);
EXPECT_EQ(coef.xi.max(0), P.Nmax);
auto output = Output(step.get_runtype(), operators, stats, P);
SubspaceStructure substruct{diagprev, Sym};
TaskList tasklist{substruct};
DiagInfo<double> diag;
for(const auto &I : tasklist.get()) {
auto h = hamiltonian<double>(step, I, operators.opch, coef, diagprev, output, Sym, P);
dump_matrix(h);
auto e = diagonalise(h, DiagParams(P, 1.0), -1); // -1 = not using MPI
diag[I] = NRG::Eigen<double>(std::move(e), step);
}
stats.Egs = diag.Egs_subtraction();
stats.update(step);
Clusters<double> clusters(diag, P.fixeps);
truncate_prepare(step, diag, Sym->multfnc(), P);
calc_abs_energies(step, diag, stats);
calculate_TD(step, diag, stats, Sym, P);
split_in_blocks(diag, substruct);
MemTime mt;
auto oprecalc = Oprecalc<double>(step.get_runtype(), operators, SymSP, mt, P);
oprecalc.recalculate_operators(operators, step, diag, P);
calculate_spectral_and_expv(step, stats, output, oprecalc, diag, operators, store, mt, Sym, P);
diag.truncate_perform();
EXPECT_EQ(step.last(), true);
store[step.ndx()] = Subs(diag, substruct, step.last());
recalc_irreducible(step, diag, operators.opch, Sym, mt, P);
operators.opch.dump();
//X operators.trim_matrices(diag);
//X diag.clear_eigenvectors();
mt.brief_report();
EXPECT_EQ(step.ndx(), step.lastndx());
stats.GS_energy = stats.total_energy;
store.shift_abs_energies(stats.GS_energy); // A
auto rho = init_rho(step, diag, Sym, P);
rho.save(step.lastndx(), P, fn_rho);
calc_densitymatrix(rho, store, Sym, mt, P);
calc_ZnD(store, stats, Sym, P);
fdm_thermodynamics(store, stats, Sym, P.T);
auto rhoFDM = init_rho_FDM(step.lastndx(), store, stats, Sym->multfnc(), P.T);
rhoFDM.save(step.lastndx(), P, fn_rhoFDM);
calc_fulldensitymatrix(step, rhoFDM, store, store, stats, Sym, mt, P);
// single-step calculation: no need to recalculate diag & operators, but we need to run
// subtract_GS_energy()
diag.subtract_GS_energy(stats.GS_energy); // B
Step step_dmnrg{P, RUNTYPE::DMNRG};
auto oprecalc_dmnrg = Oprecalc<double>(step_dmnrg.get_runtype(), operators, SymSP, mt, P);
auto output_dmnrg = Output(step_dmnrg.get_runtype(), operators, stats, P);
calculate_spectral_and_expv(step_dmnrg, stats, output_dmnrg, oprecalc_dmnrg, diag, operators, store, mt, Sym, P);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); // NOLINT
}
| 3,216
|
C++
|
.cpp
| 75
| 39.973333
| 115
| 0.699808
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,533
|
integ.cc
|
rokzitko_nrgljubljana/tools/integ/integ.cc
|
// Numerical integration tool: compute accurate spectral weights and moments
// of tabulated functions using smooth interpolation functions (GSL).
// Part of "NRG Ljubljana"
// Rok Zitko, rok.zitko@ijs.si, May 2014
// The input file must consist of a table of space-separated (energy,
// value) pairs. Gauss-Kronrod quadrature rules are used.
// CHANGE LOG
// 21.5.2014 - first version
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <utility>
#include <cassert>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_integration.h>
#include <unistd.h>
#include <getopt.h>
using namespace std;
typedef pair<double, double> XYPOINT;
using XYFUNC = vector<XYPOINT>;
using DVEC = vector<double>;
// number of digits of precision in the output
#define OUTPUT_PRECISION 16
// Dump additional information to stdout?
bool verbose = false; // enable with -v
bool veryverbose = false; // enable with -V
bool showwarnings = true; // disable with -s
double T = 1e-99; // Temperature. Default is (essentially) 0.
string inputfn; // Filename for input data
double sum; // integral over input function on [Xmin:Xmax] interval
double total, totalabs, pos, neg, fermi; // Results
string out = "total"; // What to output to STDOUT
void about() {
cout << "Integration tool - GSL" << endl;
#ifdef __TIMESTAMP__
cout << "Timestamp: " << __TIMESTAMP__ << endl;
#endif
cout << "Compiled on " << __DATE__ << " at " << __TIME__ << endl;
}
void usage() {
cout << "\nUsage: integ [-h] [-v] [-V] [-w] [-T temp] <input> [-p|n|a|f]" << endl;
cout << "-h: show help" << endl;
cout << "-v: toggle verbose messages (now=" << verbose << ")" << endl;
cout << "-V: toggle very verbose messages (now=" << veryverbose << ")" << endl;
cout << "-w: toggle warnings (now=" << showwarnings << ")" << endl;
cout << "-T: temperature T" << endl;
cout << "-p: integral over positive X range" << endl;
cout << "-n: integral over negative X range" << endl;
cout << "-a: integral over |f|" << endl;
cout << "-f: integral weighted with Fermi-Dirac function for temperature T" << endl;
}
void cmd_line(int argc, char *argv[]) {
char c;
while (c = getopt(argc, argv, "hvVwt:T:pnaf"), c != -1) {
switch (c) {
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'v': verbose = true; break;
case 'V': veryverbose = true; break;
case 'w': showwarnings = false; break;
case 't': // case insensitive!
case 'T':
T = atof(optarg);
if (verbose) { cout << "T=" << T << endl; }
break;
case 'p': out = "pos"; break;
case 'n': out = "neg"; break;
case 'a': out = "abs"; break;
case 'f': out = "fermi"; break;
default: abort();
}
}
int remaining = argc - optind;
if (remaining != 1) {
about();
usage();
exit(1);
}
inputfn = string(argv[optind]);
}
// Read data from stream F.
void readtable(istream &F, XYFUNC &v) {
while (F) {
if (F.peek() == '#') { // skip comment lines
string line;
getline(F, line);
} else {
double x, y;
F >> x >> y;
if (F.fail()) break;
assert(std::isfinite(x) && std::isfinite(y));
v.push_back(make_pair(x, y));
}
}
if (verbose) cout << v.size() << " lines read." << endl;
}
int len; // number of data points
double Xmin, Xmax; // the interval boundaries
DVEC Xpts, Ypts;
gsl_interp_accel *acc;
gsl_spline *spline;
const size_t limit = 1000;
gsl_integration_workspace *w;
const double EPSABS = 1e-12; // numeric integration epsilon (absolute)
const double EPSREL = 1e-8; // numeric integration epsilon (relative)
void init(XYFUNC &im) {
sort(im.begin(), im.end());
len = im.size();
Xmin = im[0].first;
Xmax = im[len - 1].first;
if (verbose) cout << "Range: [" << Xmin << " ; " << Xmax << "]" << endl;
// Xpts are increasing
Xpts = DVEC(len);
Ypts = DVEC(len);
for (int i = 0; i < len; i++) {
Xpts[i] = im[i].first;
Ypts[i] = im[i].second;
}
acc = gsl_interp_accel_alloc();
//const gsl_interp_type * Interp_type = gsl_interp_linear;
//const gsl_interp_type * Interp_type = gsl_interp_cspline;
const gsl_interp_type *Interp_type = gsl_interp_akima;
spline = gsl_spline_alloc(Interp_type, len);
gsl_spline_init(spline, &Xpts[0], &Ypts[0], len);
sum = gsl_spline_eval_integ(spline, Xmin, Xmax, acc);
if (!std::isfinite(sum)) {
cerr << "Error: Integral is not a finite number." << endl;
exit(1);
}
if (verbose) cout << "Sum=" << sum << endl;
w = gsl_integration_workspace_alloc(limit);
gsl_set_error_handler_off();
}
inline double f_neg(double X, [[maybe_unused]] void *params) { return (X < 0 ? gsl_spline_eval(spline, X, acc) : 0); }
inline double f_pos(double X, [[maybe_unused]] void *params) { return (X > 0 ? gsl_spline_eval(spline, X, acc) : 0); }
inline double f_total(double X, [[maybe_unused]] void *params) { return gsl_spline_eval(spline, X, acc); }
inline double f_abs(double X, [[maybe_unused]] void *params) { return fabs(gsl_spline_eval(spline, X, acc)); }
inline double f_fermi(double X, [[maybe_unused]] void *params) {
double fd = 1.0 / (1.0 + exp(X / T));
return gsl_spline_eval(spline, X, acc) * fd;
}
void handle_qag(int status) {
if (status && showwarnings) { cerr << "WARNING - qag error: " << status << " -- " << gsl_strerror(status) << endl; }
}
// NOTE about Gauss-Kronrod: The higher-order rules give better accuracy
// for smooth functions, while lower-order rules save time when the
// function contains local difficulties, such as discontinuities. [GSL manual]
// On each iteration the adaptive integration strategy bisects the
// interval with the largest error estimate. The subintervals and their
// results are stored in the memory provided by workspace. The maximum
// number of subintervals is given by limit, which may not exceed the
// allocated size of the workspace. [GSL manual]
double calc(double (*fnc)(double, void *)) {
gsl_function F;
F.function = fnc;
// F.params = &Z;
double integral;
double integration_error;
int status = gsl_integration_qag(&F, // integrand function
Xmin, // lower integration boundary
Xmax, // upper integration boundary
EPSABS, EPSREL,
limit, // size of workspace w
GSL_INTEG_GAUSS15, // Gauss-Kronrod rule
w, // integration workspace
&integral, // final approximation
&integration_error); // estimate of absolute error
handle_qag(status);
if (veryverbose) {
cout << scientific;
cout << "Result=" << integral << endl;
cout << "Int. error=" << integration_error << endl;
cout.unsetf(ios_base::scientific);
}
return integral;
}
void done() {
gsl_spline_free(spline);
gsl_interp_accel_free(acc);
gsl_integration_workspace_free(w);
}
int main(int argv, char *argc[]) {
cmd_line(argv, argc);
if (verbose) about();
if (verbose) cout << "T=" << T << endl;
ifstream Fin;
Fin.open(inputfn.c_str());
if (!Fin) {
cerr << "Can't open " << inputfn << " for reading." << endl;
exit(2);
}
XYFUNC f;
readtable(Fin, f);
init(f);
total = calc(f_total);
pos = calc(f_pos);
neg = calc(f_neg);
totalabs = calc(f_abs);
fermi = calc(f_fermi);
done();
if (verbose) {
cout << "Total=" << total << endl;
cout << "Positive=" << pos << endl;
cout << "Negative=" << neg << endl;
cout << "Total|f|=" << totalabs << endl;
cout << "Fermi-Dirac weighted=" << fermi << endl;
}
cout << setprecision(OUTPUT_PRECISION);
if (out == "total") cout << total << endl;
if (out == "pos") cout << pos << endl;
if (out == "neg") cout << neg << endl;
if (out == "abs") cout << totalabs << endl;
if (out == "fermi") cout << fermi << endl;
}
| 8,266
|
C++
|
.cc
| 221
| 32.945701
| 118
| 0.608079
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,535
|
nrgchain.cc
|
rokzitko_nrgljubljana/tools/nrgchain/nrgchain.cc
|
// Calculation of NRG chain coefficients
// Rok Zitko, rok.zitko@ijs.si, 2009-2020
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cfloat>
#include <utility>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
#include <ctime>
#include <limits>
#include <gmp.h>
using namespace std;
#include "lambda.h"
#include "linint.h"
#include "io.h"
#include "parser.h"
#include "load.h"
#include "calc.h"
string param_fn = "param"; // file with input parameters
LAMBDA Lambda; // discretization parameter
double z; // twist parameter
double xmax; // higher boundary of the x=j+z interval, where the ODE
// was solved numerically
unsigned int mMAX; // the number of coefficients computed (max index)
unsigned int Nmax; // the length of the Wilson chain (max index)
double bandrescale = 1.0; // band rescaling factor
bool rescalexi = false; // rescale coefficients xi
unsigned int preccpp; // precision for GMP
Vec vecrho_pos, vecrho_neg; // rho, for positive and negative energies
LinInt rho_pos, rho_neg;
IntLinInt intrho_pos, intrho_neg; // integrated rho
LinInt g_pos, g_neg; // g(x)
LinInt f_pos, f_neg;
using Table = vector<double>;
// Input to the tridiagonalisation.
Table de_pos, de_neg, du_pos, du_neg;
bool adapt; // If adapt=false --> g(x)=1.
string band; // If band="flat", we use an analytical expression for f,
// otherwise we load "FSOL.dat" and "FSOLNEG.dat"
bool nrgchain_tables_save; // If nrg_tables_save=true, coefficient tables are
// written to files.
bool nrgchain_tables_load; // If nrg_tables_load=true, coefficient tables are
// read from files.
bool nrgchain_tridiag; // If nrgchain_tridiag=true, tridiagonalisation is
// performed.
// eps(x) = D g(x) Lambda^(2-x) for x>2.
// This is only an auxiliary quantity which defines the discretization
// mesh.
double eps_pos(double x) {
const double gx = (adapt ? g_pos(x) : 1.0);
return (x <= 2.0 ? 1.0 : gx * Lambda.power(2.0 - x));
}
double eps_neg(double x) {
const double gx = (adapt ? g_neg(x) : 1.0);
return (x <= 2.0 ? 1.0 : gx * Lambda.power(2.0 - x));
}
// Analytical expression for Epsilon(x) in the case of a flat band.
// Cf. PRB 79, 085106 (2009), Eqs. (25) & (36).
inline double Eps_flat(double x) {
assert(x >= 1.0);
const int j = floor(x);
const double z = x - j;
if (j == 1) {
return (1.0 - Lambda.power(-z)) / Lambda.logL() + 1.0 - z;
} else {
return (1.0 - Lambda.power(-1.0)) / Lambda.logL() * Lambda.power(2.0 - j - z);
}
}
// Eps(x) = D f(x) Lambda^(2-x)
// This are the "representative energies" of the grid.
inline double Eps_pos(double x) {
if (band == "flat") return Eps_flat(x);
assert(x >= 1.0);
const double f = f_pos(x);
return f * Lambda.power(2.0 - x);
}
inline double Eps_neg(double x) {
if (band == "flat") return Eps_flat(x);
assert(x >= 1.0);
const double f = f_neg(x);
return f * Lambda.power(2.0 - x);
}
void about(ostream &F = cout) {
F << "# Calculation of NRG coefficients" << endl;
F << "# Rok Zitko, rok.zitko@ijs.si, 2009" << endl;
}
void usage(ostream &F = cout) {
F << "Usage: nrgchain [-h] [s|l]" << endl;
}
// Called before the parser.
void cmd_line(int argc, char *argv[]) {
if (argc >= 2 && string(argv[1]) == "-h") {
usage();
exit(EXIT_SUCCESS);
}
}
// Called after the parser.
void cmd_line_post(int argc, char *argv[]) {
// Argument 's': save tables, do not tridiagonalise
if (argc == 2 && string(argv[1]) == "s") {
nrgchain_tables_load = false;
nrgchain_tables_save = true;
nrgchain_tridiag = false;
}
// Argument 'l': load tables, tridiagonalise
if (argc == 2 && string(argv[1]) == "l") {
nrgchain_tables_load = true;
nrgchain_tables_save = false;
nrgchain_tridiag = true;
}
}
void set_parameters() {
cout << setprecision(PREC);
Lambda = LAMBDA(P("Lambda", 2.0));
assert(Lambda > 1.0);
z = P("z", 1.0);
assert(0 < z && z <= 1.0);
adapt = Pbool("adapt", false); // Enable adaptable g(x)? Default is false!!
bandrescale = P("bandrescale", 1.0);
rescalexi = Pbool("rescalexi", false);
xmax = P("xmax", 30); // Interval [1..xmax]
assert(xmax >= 1.0);
Nmax = Pint("Nmax", 0); // Maximal site index in the Wilson chain
mMAX = Pint("mMAX", 2 * Nmax); // Maximal index of coefficients (e,f)
assert(mMAX > 0);
preccpp = Pint("preccpp", 2000); // Precision for GMP
assert(preccpp > 10);
band = Pstr("band", "adapt"); // Default: load FSOL*.dat
nrgchain_tables_save = Pbool("nrgchain_tables_save", false);
nrgchain_tables_load = Pbool("nrgchain_tables_load", false);
nrgchain_tridiag = Pbool("nrgchains_tridiag", true);
cout << "# Lambda=" << Lambda;
cout << " bandrescale=" << bandrescale;
cout << " z=" << z << endl;
cout << "# xmax=" << xmax;
cout << " mMAX=" << mMAX;
cout << " Nmax=" << Nmax << endl;
cout << "# band=" << band << endl;
}
void add_zero_point (Vec &vecrho)
{
double x0 = vecrho.front().first;
double y0 = vecrho.front().second;
const double SMALL = 1e-99;
if (x0 > SMALL)
vecrho.push_back(make_pair(SMALL, y0));
sort(begin(vecrho), end(vecrho));
}
void load_rho() {
const string rhofn = Pstr("dos", "Delta.dat");
vecrho_pos = load_rho(rhofn, POS);
rescalevecxy(vecrho_pos, 1.0 / bandrescale, bandrescale);
add_zero_point(vecrho_pos);
vecrho_neg = load_rho(rhofn, NEG);
rescalevecxy(vecrho_neg, 1.0 / bandrescale, bandrescale);
add_zero_point(vecrho_neg);
}
void init_rho() {
rho_pos = LinInt(vecrho_pos);
rho_neg = LinInt(vecrho_neg);
Vec vecintrho_pos(vecrho_pos);
integrate(vecintrho_pos);
intrho_pos = IntLinInt(vecrho_pos, vecintrho_pos);
Vec vecintrho_neg(vecrho_neg);
integrate(vecintrho_neg);
intrho_neg = IntLinInt(vecrho_neg, vecintrho_neg);
}
void load_g() {
const string gfn_pos = "GSOL.dat";
Vec vecg_pos = load_g(gfn_pos);
g_pos = LinInt(vecg_pos);
const string gfn_neg = "GSOLNEG.dat";
Vec vecg_neg = load_g(gfn_neg);
g_neg = LinInt(vecg_neg);
}
void load_f() {
const string ffn_pos = "FSOL.dat";
Vec vecf_pos = load_g(ffn_pos); // same load_g() function as for g
f_pos = LinInt(vecf_pos);
const string ffn_neg = "FSOLNEG.dat";
Vec vecf_neg = load_g(ffn_neg);
f_neg = LinInt(vecf_neg);
}
// The factor that multiplies eigenvalues of the Wilson chain Hamiltonian
// in order to obtain the eigenvalues of the true Hamiltonian (at scale D).
double SCALE(int N) { return (1.0 - 1. / Lambda) / log(Lambda) * pow(Lambda, -(N - 1.0) / 2.0 + 1.0 - z); }
inline double sqr(double x) { return x * x; }
void tables() {
const double int_pos1 = integrate_ab(vecrho_pos, 0.0, 1.0);
const double int_neg1 = integrate_ab(vecrho_neg, 0.0, 1.0);
const double theta1 = int_pos1 + int_neg1;
cout << "# int_pos1=" << int_pos1 << " int_neg1=" << int_neg1 << " theta1=" << theta1 << endl;
const double int_pos2 = intrho_pos(eps_pos(z+1)) - intrho_pos(eps_pos(z + mMAX + 2));
const double int_neg2 = intrho_neg(eps_neg(z+1)) - intrho_neg(eps_neg(z + mMAX + 2));
const double theta2 = int_pos2 + int_neg2;
cout << "# int_pos2=" << int_pos2 << " int_neg2=" << int_neg2 << " theta2=" << theta2 << endl;
// For consistency with df_pos & df_neg, we use set 2
const double theta = theta2;
ofstream THETA;
safe_open(THETA, "theta.dat"); // theta (hybridisation fnc. weight)
THETA << theta << endl;
THETA.close();
Table df_pos(mMAX + 1), df_neg(mMAX + 1);
Table du0_neg(mMAX + 1), du0_pos(mMAX + 1);
de_pos.resize(mMAX + 1);
de_neg.resize(mMAX + 1);
for (unsigned int m = 0; m <= mMAX; m++) {
df_pos[m] = intrho_pos(eps_pos(z + m + 1)) - intrho_pos(eps_pos(z + m + 2));
df_neg[m] = intrho_neg(eps_neg(z + m + 1)) - intrho_neg(eps_neg(z + m + 2));
du0_pos[m] = sqrt(df_pos[m]) / sqrt(theta);
du0_neg[m] = sqrt(df_neg[m]) / sqrt(theta);
de_pos[m] = Eps_pos(z + m + 1);
de_neg[m] = Eps_neg(z + m + 1);
}
double checksum = 0.0;
for (unsigned int m = 0; m <= mMAX; m++) checksum += sqr(du0_pos[m]) + sqr(du0_neg[m]);
cout << "# 1-checksum=" << 1 - checksum << endl;
// A large deviation probably indicates a serious problem!
const double CHECKSUM_LIMIT = 1e-10;
if (abs(1 - checksum) > CHECKSUM_LIMIT) {
cerr << "Checksum test failed." << endl;
exit(1);
}
du_pos.resize(mMAX + 1);
du_neg.resize(mMAX + 1);
for (unsigned int m = 0; m <= mMAX; m++) {
du_pos[m] = du0_pos[m] / sqrt(checksum);
du_neg[m] = du0_neg[m] / sqrt(checksum);
}
for (unsigned int m = 0; m <= mMAX; m++) {
cout << "# " << m << " " << du_pos[m] << " " << du_neg[m] << " " << de_pos[m] << " " << de_neg[m] << endl;
}
}
void save_tables() {
save("de_pos.dat", de_pos);
save("de_neg.dat", de_neg);
save("du_pos.dat", du_pos);
save("du_neg.dat", du_neg);
}
void load_tables() {
load("de_pos.dat", de_pos);
load("de_neg.dat", de_neg);
load("du_pos.dat", du_pos);
load("du_neg.dat", du_neg);
}
class my_mpf {
private:
mpf_t val{};
public:
my_mpf() { mpf_init(val); }
// Copy constructor is mendatory!
my_mpf(const my_mpf &x) {
mpf_init(val);
mpf_set(val, x.val);
}
~my_mpf() { mpf_clear(val); }
inline operator mpf_t &() { return val; }
};
using vmpf = std::vector<my_mpf>;
// Fix normalization of u_{n,m}, v_{n,m} to 1. IMPORTANT: pass by
// reference!
void fix_norm(vmpf &up, vmpf &um, unsigned int mMAX) {
// Constants
my_mpf mpZERO, mpONE;
mpf_set_str(mpONE, "1.e0", 10);
my_mpf sum, temp, tempsq;
mpf_set(sum, mpZERO);
for (unsigned int m = 0; m <= mMAX; m++) {
mpf_mul(tempsq, up[m], up[m]);
mpf_add(sum, sum, tempsq);
mpf_mul(tempsq, um[m], um[m]);
mpf_add(sum, sum, tempsq);
}
mpf_sqrt(temp, sum);
for (unsigned int m = 0; m <= mMAX; m++) {
mpf_div(up[m], up[m], temp);
mpf_div(um[m], um[m], temp);
}
}
#define HIGHPREC(val) setw(30) << setprecision(16) << (val) << setprecision(PREC)
// Triagonalisation by iteration.
//
// INPUT: tables du_pos, du_neg, de_pos, de_neg
// OUTPUT: written to files "xi.dat" and "zeta.dat"
void tridiag() {
ofstream XI, ZETA;
safe_open(XI, "xi.dat"); // hopping constants
safe_open(ZETA, "zeta.dat"); // on-site energies
mpf_set_default_prec(preccpp);
cout << "Using precision of " << preccpp << " digits." << endl;
// Constants
my_mpf mpZERO;
// Temporary MP variables
my_mpf temp, tempsq, sum;
my_mpf mpxi; // xi
my_mpf xi2; // xi^2
my_mpf mpzeta; // zeta
my_mpf xi_prev, xi2_prev; // values in previous iteration
vmpf up(mMAX + 1);
vmpf up_prev(mMAX + 1);
vmpf up_prev2(mMAX + 1);
vmpf um(mMAX + 1);
vmpf um_prev(mMAX + 1);
vmpf um_prev2(mMAX + 1);
vmpf ep1(mMAX + 1);
vmpf em1(mMAX + 1);
vmpf ep2(mMAX + 1);
vmpf em2(mMAX + 1);
for (unsigned int m = 0; m <= mMAX; m++) {
mpf_set_d(up_prev[m], du_pos[m]);
mpf_set_d(um_prev[m], du_neg[m]);
mpf_set_d(ep1[m], de_pos[m]);
mpf_set_d(em1[m], de_neg[m]);
mpf_mul(ep2[m], ep1[m], ep1[m]);
mpf_mul(em2[m], em1[m], em1[m]);
}
fix_norm(up_prev, um_prev, mMAX);
for (unsigned int n = 0; n <= Nmax; n++) {
// Calculate zeta_n, xi2_n and xi_n
mpf_set(mpzeta, mpZERO);
mpf_set(xi2, mpZERO);
for (unsigned int m = 0; m <= mMAX; m++) {
// up_prev = u^+_{n,m}
mpf_mul(tempsq, up_prev[m], up_prev[m]);
mpf_mul(temp, tempsq, ep2[m]);
mpf_add(xi2, xi2, temp);
mpf_mul(temp, tempsq, ep1[m]);
mpf_add(mpzeta, mpzeta, temp);
// um_prev = u^-_{n,m}
mpf_mul(tempsq, um_prev[m], um_prev[m]);
mpf_mul(temp, tempsq, em2[m]);
mpf_add(xi2, xi2, temp);
mpf_mul(temp, tempsq, em1[m]);
mpf_sub(mpzeta, mpzeta, temp);
}
// subtract xi^2_{n-1}
mpf_sub(xi2, xi2, xi2_prev);
// subtract zeta^2_n
mpf_mul(tempsq, mpzeta, mpzeta);
mpf_sub(xi2, xi2, tempsq);
if (!mpf_cmp_d(xi2, 0.0)) {
cerr << "xi2 negative, aborting." << endl;
exit(1);
}
mpf_sqrt(mpxi, xi2);
// compute u_{n+1,m}, v_{n+1,m}
for (unsigned int m = 0; m <= mMAX; m++) {
// zeta=zeta_n
mpf_sub(temp, ep1[m], mpzeta);
// up_prev[m]=u_{n,m}
mpf_mul(up[m], temp, up_prev[m]);
// xi_prev=xi_{n-1}, up_prev2=u_{n-1,m}
mpf_mul(temp, xi_prev, up_prev2[m]);
mpf_sub(up[m], up[m], temp);
// xi=xi_n
mpf_div(up[m], up[m], mpxi);
mpf_neg(temp, em1[m]);
mpf_sub(temp, temp, mpzeta);
mpf_mul(um[m], temp, um_prev[m]);
mpf_mul(temp, xi_prev, um_prev2[m]);
mpf_sub(um[m], um[m], temp);
mpf_div(um[m], um[m], mpxi);
}
fix_norm(up, um, mMAX);
// Recalculate xi, xi2
mpf_set(sum, mpZERO);
for (unsigned int m = 0; m <= mMAX; m++) {
mpf_mul(temp, up[m], up_prev[m]);
mpf_mul(temp, temp, ep1[m]);
mpf_add(sum, sum, temp);
mpf_mul(temp, um[m], um_prev[m]);
mpf_mul(temp, temp, em1[m]);
mpf_sub(sum, sum, temp);
}
mpf_set(mpxi, sum);
mpf_mul(xi2, mpxi, mpxi);
// Save results
double dxi = mpf_get_d(mpxi);
double dzeta = mpf_get_d(mpzeta);
double coef_xi = dxi / (rescalexi == true ? SCALE(n + 1) : 1.0);
double coef_zeta = dzeta; // NEVER RESCALED!!!
coef_xi = coef_xi * bandrescale; // by analogy with initial.m
coef_zeta = coef_zeta * bandrescale;
XI << coef_xi << endl;
ZETA << coef_zeta << endl;
cout << " xi(" << n << ")=" << HIGHPREC(dxi) << " --> " << HIGHPREC(coef_xi) << endl;
cout << "zeta(" << n << ")=" << HIGHPREC(dzeta) << endl;
// Store results from previous iteration
mpf_set(xi_prev, mpxi);
mpf_set(xi2_prev, xi2);
for (unsigned int m = 0; m <= mMAX; m++) {
mpf_set(um_prev2[m], um_prev[m]);
mpf_set(up_prev2[m], up_prev[m]);
mpf_set(um_prev[m], um[m]);
mpf_set(up_prev[m], up[m]);
}
}
}
void calc_tables() {
if (band != "flat") {
load_rho();
if (adapt) { load_g(); }
load_f();
} else {
// Flat band
const double mindbl = numeric_limits<double>::min();
Vec v;
v.push_back(make_pair(mindbl, 0.5));
v.push_back(make_pair(1.0, 0.5));
vecrho_pos = v;
vecrho_neg = v;
}
init_rho();
tables();
if (nrgchain_tables_save) { save_tables(); }
}
int main(int argc, char *argv[]) {
clock_t start_clock = clock();
about();
cmd_line(argc, argv);
parser(param_fn);
set_parameters();
cmd_line_post(argc, argv);
if (nrgchain_tables_load) {
load_tables();
} else {
calc_tables();
}
if (nrgchain_tridiag) tridiag();
clock_t end_clock = clock();
cout << "# Elapsed " << double(end_clock - start_clock) / CLOCKS_PER_SEC << " s" << endl;
}
| 15,050
|
C++
|
.cc
| 438
| 30.557078
| 110
| 0.597447
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,536
|
kk.cc
|
rokzitko_nrgljubljana/tools/kk/kk.cc
|
#include "kk.hpp"
int main(int argc, char *argv[]) {
NRG::KK::KK kk(argc, argv);
}
| 86
|
C++
|
.cc
| 4
| 19.75
| 34
| 0.62963
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,537
|
mats.cc
|
rokzitko_nrgljubljana/tools/mats/mats.cc
|
// mats - evaluation of Green's functions at Matsubara frequencies
// Ljubljana code Rok Zitko, rok.zitko@ijs.si, Nov 2012
// CHANGE LOG
// 16.11.2012 - first version based on the 'broaden' tool
#define VERSION "0.0.1"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cfloat>
#include <utility>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <complex>
#include <unistd.h>
#include <getopt.h>
using namespace std;
bool verbose = false; // output verbosity level
double T; // temperature parameter
bool one = false; // For Nz=1, no subdir.
char stat = 'f'; // f)ermionic, b)osonic
// Multi-column support
int nrcol = 1; // Number of columns
int col = 1; // Which y column are we interested in?
string name; // filename of binary files containing the raw data
int Nz; // Number of spectra (1..Nz)
int nrmats; // Number of Matsubara points
double **buffers; // binary data buffers
int *sizes; // sizes of buffers
using cmpl = complex<double>;
typedef map<double, cmpl> mapdc;
typedef map<double, double> mapdd;
using vec = vector<double>;
using cvec = vector<cmpl>;
mapdd spec; // Spectrum
unsigned int nr_spec; // Number of raw spectrum points
vec vfreq, vspec; // Same info as spectrum, but in vector<double> form
mapdd intspec; // Integrated spectrum
cvec mesh; // Frequency mesh
cvec G; // Green's function
void usage(ostream &F = cout) {
F << "Usage: mats <name> <Nz> <T> <nrmats>" << endl;
F << endl;
F << "Optional parameters:" << endl;
F << "- h -- show help" << endl;
F << " -v -- verbose" << endl;
F << " -o -- one .dat file" << endl;
F << " -2 -- use the 2nd column for weight values (complex spectra)" << endl;
F << " -3 -- use the 3rd column for weight values (complex spectra)" << endl;
}
void cmd_line(int argc, char *argv[]) {
char c;
while (c = getopt(argc, argv, "hvo23"), c != -1) {
switch (c) {
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'v': verbose = true; break;
case 'o': one = true; break;
case '2':
nrcol = 2;
col = 1;
break;
case '3':
nrcol = 2;
col = 2;
break;
default: abort();
}
}
int remaining = argc - optind; // arguments left
if (remaining != 4) {
usage();
exit(1);
}
name = string(argv[optind]); // Name of spectral density files
Nz = atoi(argv[optind + 1]); // Number of z-values
assert(Nz >= 1);
T = atof(argv[optind + 2]); // Temperature
assert(T > 0.0);
nrmats = atoi(argv[optind + 3]); // Number of Matsubara points
assert(nrmats >= 1);
cout << "Processing: " << name << endl;
cout << "Nz=" << Nz << " T=" << T << " nrmats=" << nrmats << endl;
}
string tostring(int i) {
ostringstream S;
S << i;
return S.str();
}
// Load a file containing binary representation of raw spectral density.
// The grid is not assumed to be uniform.
void load(int i) {
// i-th z-value defines the name of the directory where the results of
// the NRG calculation are contained.
string filename;
if (one && Nz == 1)
filename = name;
else
filename = tostring(i) + "/" + name;
ifstream f(filename.c_str(), ios::in | ios::binary);
if (!f.good() || f.eof() || !f.is_open()) {
cerr << "Error opening file " << filename << endl;
exit(1);
}
if (verbose) cout << "Reading " << filename << endl;
const int rows = 1 + nrcol; // number of elements in a line
// Determine the number of records
f.seekg(0, ios::beg);
const ios::pos_type begin_pos = f.tellg();
f.seekg(0, ios::end);
const ios::pos_type end_pos = f.tellg();
const long len = end_pos - begin_pos;
assert(len % (rows * sizeof(double)) == 0);
const int nr = len / (rows * sizeof(double)); // number of lines
if (verbose) cout << "len=" << len << " nr=" << nr << " data points" << endl;
// Allocate the read buffer. The data will be kept in memory for the
// duration of the calculation!
auto *buffer = new double[rows * nr];
f.seekg(0, ios::beg); // Return to the beginning of the file.
f.read((char *)buffer, len);
if (f.fail()) {
cerr << "Error reading " << filename << endl;
exit(1);
}
f.close();
// Keep record of the the buffer and its size.
buffers[i] = buffer;
sizes[i] = nr;
if (verbose) {
// Check normalization.
double sum = 0.0;
for (int j = 0; j < nr; j++) sum += buffer[rows * j + col];
cout << "Weight=" << sum << endl;
}
}
// Load all the input data.
void read_files() {
buffers = new double *[Nz + 1];
sizes = new int[Nz + 1];
for (int i = 1; i <= Nz; i++) load(i);
}
// Combine data from all NRG runs (z-averaging).
void merge() {
const int rows = 1 + nrcol; // number of elements in a line
// Sum weight corresponding to equal frequencies. Map of
// (frequency,weight) pairs is used for this purpose.
for (int i = 1; i <= Nz; i++) {
for (int l = 0; l < sizes[i]; l++) {
double &freq = buffers[i][rows * l];
double &value = buffers[i][rows * l + col];
auto I = spec.find(freq);
if (I == spec.end())
spec[freq] = value;
else
I->second += value;
}
}
nr_spec = spec.size();
if (verbose) cout << nr_spec << " unique frequencies." << endl;
// Normalize weight by 1/Nz, determine total weight, and store the
// (frequency,weight) data in the form of linear vectors for faster
// access in the ensuing calculations.
double sum = 0.0;
for (auto & I : spec) {
const double weight = (I.second /= Nz); // Normalize weight on the fly
const double freq = I.first;
vfreq.push_back(freq);
vspec.push_back(weight);
sum += weight;
}
if (verbose) cout << "Total weight=" << sum << endl;
assert(vfreq.size() == nr_spec && vspec.size() == nr_spec);
}
// Matsubara frequency (WITHOUT the imaginary unit)
// Starting from n=0
double omegan(int n) {
if (stat == 'f') return T * M_PI * (2 * n + 1);
if (stat == 'b') return T * M_PI * (2 * n);
cerr << "oops. stat=" << stat << endl;
exit(1);
}
// Matsubara frequencuy (WITH the i factor)
cmpl iomegan(int n) { return omegan(n) * cmpl(0, 1); }
// Create a mesh on which the output Green's function will be computed.
void make_mesh(cvec &mesh) {
for (int i = 0; i < nrmats; i++) mesh.push_back(iomegan(i));
}
void compute(const cvec &mesh, cvec &G) {
const int nr_mesh = mesh.size();
if (verbose) cout << "Computing. nr_mesh=" << nr_mesh << endl;
G.resize(nr_mesh);
for (int i = 0; i < nr_mesh; i++) {
const cmpl &z = mesh[i];
G[i] = 0.0;
for (unsigned int j = 0; j < nr_spec; j++) G[i] += vspec[j] / (z - vfreq[j]);
}
}
// Use high precision!
const int SAVE_PREC = 18; // Precision for output to the file
const int COUT_PREC = 18; // Precision for verbose reporting on console
// Save a map of (double,double) pairs to a file.
void save(const string filename, const cvec &x, const cvec &y) {
if (verbose) cout << "Saving " << filename << endl;
ofstream F(filename.c_str());
if (!F) {
cerr << "Failed to open " << filename << " for writing." << endl;
exit(1);
}
F << setprecision(SAVE_PREC);
assert(x.size() == y.size());
unsigned int nr = x.size();
for (unsigned int i = 0; i < nr; i++) {
assert(x[i].real() == 0.0);
F << x[i].imag() << " " << y[i].real() << " " << y[i].imag() << endl;
}
}
int main(int argc, char *argv[]) {
cout << "mats - thermal Green's function evaluation tool - " << VERSION << endl;
cout << "Rok Zitko, rok.zitko@ijs.si, Nov 2012" << endl;
cout << setprecision(COUT_PREC);
cmd_line(argc, argv);
read_files();
merge();
make_mesh(mesh);
compute(mesh, G);
string output = "spec.dat";
save(output, mesh, G);
}
| 7,874
|
C++
|
.cc
| 234
| 30.547009
| 82
| 0.611476
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,538
|
specmoments.cc
|
rokzitko_nrgljubljana/tools/specmoments/specmoments.cc
|
// specmoments - Compute spectral moments from raw spectal data
// Ljubljana code, Rok Zitko, rok.zitko@ijs.si, Aug 2015
// CHANGE LOG
// 25.8.2015 - first version
#define VERSION "1.0"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cfloat>
#include <utility>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <unistd.h>
#include <getopt.h>
using namespace std;
bool verbose = false; // output verbosity
bool one = false; // For Nz=1, no subdirs.
double filterlow = 0.0; // filter all input data points with |omega|<filterlow
double filterhigh = DBL_MAX; // filter all input data points with |omega|>filterhigh
bool posonly = false; // keep only positive omega
bool negonly = false; // keep only negative omega
bool central = false; // central or raw moments?
// Multi-column support
int nrcol = 1; // Number of columns
int col = 1; // Which y column are we interested in?
string name;
int Nz;
const int COUT_PREC = 16;
void about(ostream &F = cout) {
F << "specmoments - Spectral moment calculation tool - " << VERSION << endl;
F << "Rok Zitko, rok.zitko@ijs.si, 2015" << endl;
}
void usage(ostream &F = cout) {
F << "Usage: specmoments <name> <Nz>\n";
F << endl;
F << "Optional parameters:" << endl;
F << " -h -- show help (when used as sole cmd line switch)" << endl;
F << " -v -- verbose" << endl;
F << " -o -- one .dat file" << endl;
F << " -l -- filter out low-frequency raw data" << endl;
F << " -h -- filter out high-frequency raw data" << endl;
F << " -p -- positive frequencies only" << endl;
F << " -n -- negative frequencies only" << endl;
F << " -c -- central moments" << endl;
F << endl;
F << "Output: <mom0> <mom1> <mom2> <mom3> <mom4>" << endl;
}
void cmd_line(int argc, char *argv[]) {
if (argc == 2 && string(argv[1]) == "-h") {
usage();
exit(EXIT_SUCCESS);
}
char c;
while (c = getopt(argc, argv, "vol:h:pnc"), c != -1) {
switch (c) {
case 'v':
verbose = true;
about(); // only if verbose is on
break;
case 'o': one = true; break;
case 'l':
filterlow = atof(optarg);
if (verbose) { cout << "filterlow=" << filterlow << endl; }
break;
case 'h':
filterhigh = atof(optarg);
if (verbose) { cout << "filterhigh=" << filterhigh << endl; }
break;
case 'p':
posonly = true;
if (verbose) { cout << "positive part" << endl; }
break;
case 'n':
negonly = true;
if (verbose) { cout << "negative part" << endl; }
break;
case 'c': central = true; break;
default: abort();
}
}
int remaining = argc - optind;
if (remaining != 2) {
if (!verbose) about();
usage();
exit(1);
}
name = string(argv[optind]);
Nz = atoi(argv[optind + 1]);
assert(Nz >= 1);
if (verbose) cout << "Processing: " << name << " Nz=" << Nz << endl;
}
double **buffers; // binary data buffers
int *sizes; // sizes of buffers
typedef map<double, double> mapdd;
using vec = vector<double>;
mapdd spec; // Spectrum
unsigned int nr_spec; // Number of raw spectrum points
vec vfreq, vspec; // Same info as spectrum, but in vector<double> form
string tostring(int i) {
ostringstream S;
S << i;
return S.str();
}
// Load a file containing binary representation of raw spectral density.
// The grid is not assumed to be uniform.
void load(int i) {
// i-th z-value defines the name of the directory where the results of
// the NRG calculation are contained.
string filename;
if (one && Nz == 1) {
filename = name;
} else {
filename = tostring(i) + "/" + name;
}
ifstream f(filename.c_str(), ios::in | ios::binary);
if (!f.good() || f.eof() || !f.is_open()) {
cerr << "Error opening file " << filename << endl;
exit(1);
}
if (verbose) cout << "Reading " << filename << endl;
const int rows = 1 + nrcol; // number of elements in a line
// Determine the number of records
f.seekg(0, ios::beg);
const ios::pos_type begin_pos = f.tellg();
f.seekg(0, ios::end);
const ios::pos_type end_pos = f.tellg();
const long len = end_pos - begin_pos;
assert(len % (rows * sizeof(double)) == 0);
const int nr = len / (rows * sizeof(double)); // number of lines
if (verbose) cout << "len=" << len << " nr=" << nr << " data points" << endl;
// Allocate the read buffer. The data will be kept in memory for the
// duration of the calculation!
auto *buffer = new double[rows * nr];
f.seekg(0, ios::beg); // Return to the beginning of the file.
f.read((char *)buffer, len);
if (f.fail()) {
cerr << "Error reading " << filename << endl;
exit(1);
}
f.close();
// Keep record of the the buffer and its size.
buffers[i] = buffer;
sizes[i] = nr;
if (verbose) {
// Check normalization.
double sum = 0.0;
for (int j = 0; j < nr; j++) sum += buffer[rows * j + col];
cout << "Weight=" << sum << endl;
}
}
// Load all the input data.
void read_files() {
buffers = new double *[Nz + 1];
sizes = new int[Nz + 1];
for (int i = 1; i <= Nz; i++) load(i);
}
// Combine data from all NRG runs (z-averaging).
void merge() {
const int rows = 1 + nrcol; // number of elements in a line
// Sum weight corresponding to equal frequencies. Map of
// (frequency,weight) pairs is used for this purpose.
for (int i = 1; i <= Nz; i++) {
for (int l = 0; l < sizes[i]; l++) {
double &freq = buffers[i][rows * l];
double &value = buffers[i][rows * l + col];
auto I = spec.find(freq);
if (I == spec.end()) {
spec[freq] = value;
} else {
I->second += value;
}
}
}
nr_spec = spec.size();
if (verbose) { cout << nr_spec << " unique frequencies." << endl; }
// Normalize weight by 1/Nz, determine total weight, and store the
// (frequency,weight) data in the form of linear vectors for faster
// access in the ensuing calculations.
double sum = 0.0;
for (auto & I : spec) {
const double weight = (I.second /= Nz); // Normalize weight on the fly
const double freq = I.first;
vfreq.push_back(freq);
vspec.push_back(weight);
sum += weight;
}
if (verbose) { cout << "Total weight=" << sum << endl; }
assert(vfreq.size() == nr_spec && vspec.size() == nr_spec);
}
void filter() {
for (unsigned int j = 0; j < nr_spec; j++) {
if (abs(vfreq[j]) < filterlow) vspec[j] = 0.0;
if (abs(vfreq[j]) > filterhigh) vspec[j] = 0.0;
if (vfreq[j] < 0.0 && posonly) vspec[j] = 0.0;
if (vfreq[j] > 0.0 && negonly) vspec[j] = 0.0;
}
}
// Moments about 0
void moments() {
double mom0 = 0.0, mom1 = 0.0, mom2 = 0.0, mom3 = 0.0, mom4 = 0.0;
for (unsigned int j = 0; j < nr_spec; j++) {
mom0 += vspec[j];
mom1 += vspec[j] * vfreq[j];
mom2 += vspec[j] * pow(vfreq[j], 2);
mom3 += vspec[j] * pow(vfreq[j], 3);
mom4 += vspec[j] * pow(vfreq[j], 4);
}
// Important: no normalization!
if (verbose) {
cout << endl;
cout << "0. raw moment = " << mom0 << endl;
cout << "1. raw moment = " << mom1 << endl;
cout << "2. raw moment = " << mom2 << endl;
cout << "3. raw moment = " << mom3 << endl;
cout << "4. raw moment = " << mom4 << endl;
} else {
cout << mom0 << " " << mom1 << " " << mom2 << " " << mom3 << " " << mom4;
cout << endl;
}
}
// Moments about the mean
void central_moments() {
double mom0 = 0.0, mom1 = 0.0, mom2 = 0.0, mom3 = 0.0, mom4 = 0.0;
for (unsigned int j = 0; j < nr_spec; j++) {
mom0 += vspec[j];
mom1 += vspec[j] * vfreq[j];
mom2 += vspec[j] * pow(vfreq[j], 2);
mom3 += vspec[j] * pow(vfreq[j], 3);
mom4 += vspec[j] * pow(vfreq[j], 4);
}
if (verbose) {
cout << endl;
cout << "0. raw moment = " << mom0 << endl;
cout << "1. raw moment = " << mom1 << endl;
cout << "2. raw moment = " << mom2 << endl;
cout << "3. raw moment = " << mom3 << endl;
cout << "4. raw moment = " << mom4 << endl;
}
const double weight = mom0;
const double mean = mom1 / weight;
double cmom2 = 0.0, cmom3 = 0.0, cmom4 = 0.0;
for (unsigned int j = 0; j < nr_spec; j++) {
cmom2 += vspec[j] * pow(vfreq[j] - mean, 2);
cmom3 += vspec[j] * pow(vfreq[j] - mean, 3);
cmom4 += vspec[j] * pow(vfreq[j] - mean, 4);
}
// Normalize by total weight
cmom2 /= weight;
cmom3 /= weight;
cmom4 /= weight;
const double sigma = sqrt(cmom2); // std. deviation
const double skewness = cmom3 / pow(sigma, 3);
const double kurtosis = cmom4 / pow(sigma, 4) - 3.0;
if (verbose) {
cout << endl;
cout << "0. moment (weight) = " << mom0 << endl;
cout << "1. moment = " << mom1 << endl;
cout << endl;
cout << "2. central moment = " << cmom2 << endl;
cout << "3. central moment = " << cmom3 << endl;
cout << "4. central moment = " << cmom4 << endl;
cout << endl;
cout << "mean = " << mean << endl;
cout << "sigma (std dev) = " << sigma << endl;
cout << "skewness = " << skewness << endl;
cout << "kurtosis = " << kurtosis << endl;
} else {
cout << mom0 << " " << mom1 << " " << cmom2 << " " << cmom3 << " " << cmom4;
cout << endl;
}
}
int main(int argc, char *argv[]) {
cmd_line(argc, argv);
cout << setprecision(COUT_PREC);
read_files();
merge();
filter();
if (central)
central_moments();
else
moments();
}
| 9,578
|
C++
|
.cc
| 288
| 29.614583
| 84
| 0.574188
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,539
|
hilb.cc
|
rokzitko_nrgljubljana/tools/hilb/hilb.cc
|
#include "hilb.hpp"
int main(int argc, char *argv[]) {
NRG::Hilb::Hilb hilb(argc, argv);
}
| 94
|
C++
|
.cc
| 4
| 21.75
| 35
| 0.662921
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,542
|
intavg.cc
|
rokzitko_nrgljubljana/tools/intavg/intavg.cc
|
// intavg - Averaging with interpolation
// Part of "NRG Ljubljana", Rok Zitko, rok.zitko@ijs.si, Aug 2009
// CHANGE LOG
// 25.8.2009 - first version
// 12.1.2010 - missing header added
#define VERSION "0.1"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cfloat>
#include <utility>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <unistd.h>
#include <getopt.h>
using namespace std;
bool verbose = false; // output verbosity level
bool veryverbose = false; // horribly detailed output
string name; // filename of binary files containing the raw data
int Nz; // Number of spectra (1..Nz)
typedef pair<double, double> Pair;
using Vec = vector<Pair>;
using dvec = vector<double>;
vector<Vec> input; // input data
dvec mesh; // output mesh
void usage(ostream &F = cout) { F << "Usage: intavg [-h] [-vV] <name> <Nz>\n"; }
void cmd_line(int argc, char *argv[]) {
char c;
while (c = getopt(argc, argv, "hvV"), c != -1) {
switch (c) {
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'v': verbose = true; break;
case 'V': veryverbose = true; break;
default: abort();
}
}
int remaining = argc - optind; // arguments left
if (remaining != 2) {
usage();
exit(1);
}
name = string(argv[optind]); // Name of spectral density files
Nz = atoi(argv[optind + 1]); // Number of z-values
assert(Nz >= 1);
}
string tostring(int i) {
ostringstream S;
S << i;
return S.str();
}
Vec load(int i) {
// i-th z-value defines the name of the directory where the results of
// the NRG calculation are contained.
const string filename = tostring(i) + "/" + name;
ifstream f(filename.c_str());
if (!f.good() || f.eof() || !f.is_open()) {
cerr << "Error opening file " << filename << endl;
exit(1);
}
if (verbose) { cout << "Reading " << filename << endl; }
Vec data;
while (f) {
if (f.peek() == '#') { // skip comment lines
string line;
getline(f, line);
} else {
double x, y;
f >> x >> y;
if (f.fail()) break;
assert(std::isfinite(x) && std::isfinite(y));
data.push_back(make_pair(x, y));
}
}
return data;
}
// Load all the input data.
void read_files() {
for (int i = 1; i <= Nz; i++) {
Vec v = load(i);
input.push_back(v);
}
}
// Linear interpolation class
class LinInt {
protected:
Vec vec; // tabulated data
int len{}; // length of vec
int index{}; // index of the interval where last x was found
double x0{}, x1{}; // last x was in [x0:x1]
double f0{}, f1{}; // f(x0), f(x1)
double deriv{}; // (f1-f0)/(x1-x0)
bool newintegral_flag{}; // set to true when we switch to a new interval
double xmin{}, xmax{}; // lowest and highest x contained in vec
double fxmin{}, fxmax{}; // f(xmin), f(xmax)
public:
LinInt()= default;
LinInt(Vec &in_vec) : vec(in_vec) {
len = vec.size();
index = -1;
newintegral_flag = false;
xmin = vec.front().first;
fxmin = vec.front().second;
xmax = vec.back().first;
fxmax = vec.back().second;
};
void findindex(double x);
double operator()(double x);
};
// Serach for the interval so that x is contained in [x0:x1].
void LinInt::findindex(double x) {
if (index == -1) {
// When interpolation class object is constructed, index is
// initialized to -1. We have no prior knowledge, thus we search in
// the full interval.
for (int i = 0; i < len - 1; i++) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
} else {
if (x >= x1) {
for (int i = index + 1; i < len - 1; i++) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
} else {
for (int i = index - 1; i >= 0; i--) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
}
}
if (!(0 <= index && index < len && x0 <= x && x <= x1)) {
cerr << "findindex() error."
<< " x=" << x << " x0=" << x0 << " x1=" << x1 << " index=" << index << " len=" << len << endl;
exit(1);
}
f0 = vec[index].second; // f(x0)
f1 = vec[index + 1].second; // f(x1)
double Delta_y = f1 - f0;
double Delta_x = x1 - x0;
deriv = Delta_y / Delta_x;
}
// Return y(x) using linear interpolation between the tabulated values.
double LinInt::operator()(double x) {
// Extrapolate if necessary
if (x <= xmin) { return fxmin; }
if (x >= xmax) { return fxmax; }
if (index == -1 || !(x0 <= x && x < x1)) {
newintegral_flag = true;
findindex(x);
}
double dx = x - x0;
return f0 + deriv * dx;
}
const double EPS = 1e-6;
inline bool eq_approx(double a, double b) { return abs((a - b) / a) < EPS; }
dvec merge_meshes() {
dvec mesh;
for (int i = 0; i < Nz; i++) {
const int len = input[i].size();
for (int j = 0; j < len; j++) { mesh.push_back(input[i][j].first); }
}
sort(mesh.begin(), mesh.end());
auto new_end = unique(mesh.begin(), mesh.end(), eq_approx);
mesh.erase(new_end, mesh.end());
return mesh;
}
vector<LinInt> f; // interpolation objects
void interpolate() {
for (int i = 0; i < Nz; i++) { f.emplace_back(input[i]); }
}
Vec avg() {
Vec result;
const int len = mesh.size();
for (int j = 0; j < len; j++) {
const double x = mesh[j];
double sum = 0.0;
for (int i = 0; i < Nz; i++) { sum += f[i](x); }
const double avg = sum / Nz;
result.push_back(make_pair(x, avg));
}
return result;
}
void save(const Vec &result, string filename) {
ofstream f(filename.c_str());
if (!f) {
cerr << "Failed opening " << filename << endl;
exit(1);
}
f << setprecision(16);
const int len = result.size();
for (int j = 0; j < len; j++) { f << result[j].first << " " << result[j].second << endl; }
}
int main(int argc, char *argv[]) {
cout << "intavg - Averaging tool - " << VERSION << endl;
cout << "Rok Zitko, rok.zitko@ijs.si, 2009" << endl;
cout << setprecision(16);
cmd_line(argc, argv);
read_files();
mesh = merge_meshes();
interpolate();
Vec result = avg();
save(result, name);
}
| 6,584
|
C++
|
.cc
| 224
| 25.566964
| 103
| 0.55955
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,543
|
adapt.cc
|
rokzitko_nrgljubljana/tools/adapt/adapt.cc
|
// Discretization ODE solver for NRG
// Adaptable discretization mesh code
//
// Linear interpolation of rho(omega), integration using trapezoidal method. 4th-order Runge-Kutta ODE solver. Secant
// method for refinement of parameter A.
#include <iostream>
#include <fstream>
#include <utility>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std::string_literals;
#include "adapt.hpp"
using namespace NRG::Adapt;
void about(std::ostream &F = std::cout) {
F << "# Discretization ODE solver" << std::endl;
F << "# Rok Zitko, rok.zitko@ijs.si, 2008-2020" << std::endl;
}
void help(int argc, char **argv, const std::string &help_message)
{
std::vector<std::string> args(argv+1, argv+argc); // NOLINT
if (args.size() >= 1 && args[0] == "-h") {
std::cout << help_message << std::endl;
exit(EXIT_SUCCESS);
}
}
const auto usage = "Usage: adapt [-h] [P|N] [param_filename]"s;
std::pair<Sign, std::string> cmd_line(int argc, char *argv[]) {
Sign sign = Sign::POS;
if (argc >= 2) {
const auto first_char = toupper(argv[1][0]);
switch (first_char) {
case 'P': sign = Sign::POS; break;
case 'N': sign = Sign::NEG; break;
default: std::cerr << usage << std::endl; exit(1);
}
}
const std::string param_fn = argc == 3 ? std::string(argv[2]) : "param";
std::cout << "# ++ " << (sign == Sign::POS ? "POSITIVE" : "NEGATIVE") << std::endl;
return {sign, param_fn};
}
int main(int argc, char *argv[]) {
const clock_t start_clock = clock();
about();
help(argc, argv, usage);
const auto [sign, param_fn] = cmd_line(argc, argv);
Params P(param_fn);
Adapt calc(P, sign);
calc.run();
const clock_t end_clock = clock();
std::cout << "# Elapsed " << double(end_clock - start_clock) / CLOCKS_PER_SEC << " s" << std::endl;
}
| 1,834
|
C++
|
.cc
| 54
| 31.481481
| 117
| 0.650113
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,544
|
bw.cc
|
rokzitko_nrgljubljana/tools/bw/bw.cc
|
// bw - Adaptive broadening of spectral functions obtained using NRG.
// Ljubljana code Rok Zitko, rok.zitko@ijs.si, Mar, Aug 2009, Jun 2010
// Approach from A. Freyn, S. Florens, PRB 79, 121102(R) (2009).
// CHANGE LOG
// 24.9.2009 - bmin - minimal b(w)
// - dynamic mesh
// 28.9.2009 - option 'one'
// 12.1.2010 - missing header added
// 14.6.2010 - rescale 'avg' by q in calc_b()
// 22.10.2010 - removed some overzealous assertion checks
#define VERSION "0.2.5"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cfloat>
#include <utility>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <unistd.h>
#include <getopt.h>
using namespace std;
bool verbose = false; // output verbosity level
bool veryverbose = false; // horribly detailed output
double broaden_min = 1e-7; // parameters defining the frequency mesh
double broaden_max = 2.0;
double broaden_ratio = 1.01;
int nr_iter = 10; // number of iterations to perform
double trim = -999; // the lowest (abs) frequency for output
bool enforce_positivity = false; // Enforce A(w) to be positive
double b0; // initial broadening parameter, b_0
double bmin = -999; // the smallest b(omega) allowed
double q = 1.0; // regularization parameter
bool savemore = false; // save intermediate results for A(w) and b(w)
bool saveall = false; // save all quantities (integrated DOS, etc.)
double dyn_mesh = -999; // if > 0, the mesh is dynamically refined
bool one = false; // For Nz=1, no subdir.
string name; // filename of binary files containing the raw data
int Nz; // Number of spectra (1..Nz)
double **buffers; // binary data buffers
int *sizes; // sizes of buffers
typedef map<double, double> mapdd;
using vec = vector<double>;
mapdd spec; // Spectrum
unsigned int nr_spec; // Number of raw spectrum points
vec vfreq, vspec; // Same info as spectrum, but in vector<double> form
mapdd intspec; // Integrated spectrum
vec b; // Broadening coefficients (associated with data points!)
vec mesh; // Frequency mesh
vec a; // Spectral function [current approximation]
vec inta, intb, intc; // Integrated spectral functions
void usage(ostream &F = cout) {
F << "Usage: bw [-h] [-vVpsSo] [-m min] [-M max] [-r ratio] [-n nr_iter] [-t trim] [-q q] <name> <b0> <Nz>\n";
}
void cmd_line(int argc, char *argv[]) {
char c;
while (c = getopt(argc, argv, "hvVm:M:r:n:t:pq:sSx:d:o"), c != -1) {
switch (c) {
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'v': verbose = true; break;
case 'V': veryverbose = true; break;
case 'm':
broaden_min = atof(optarg);
if (verbose) { cout << "broaden_min=" << broaden_min << endl; }
break;
case 'M':
broaden_max = atof(optarg);
if (verbose) { cout << "broaden_max=" << broaden_max << endl; }
break;
case 'r':
broaden_ratio = atof(optarg);
if (verbose) { cout << "broaden_ratio=" << broaden_ratio << endl; }
break;
case 'n':
nr_iter = atoi(optarg);
if (verbose) { cout << "nr_iter=" << nr_iter << endl; }
break;
case 't':
trim = atof(optarg);
if (verbose) { cout << "trim=" << trim << " trim/broaden_min=" << trim / broaden_min << endl; }
break;
case 'p':
enforce_positivity = true;
if (verbose) { cout << "positivity of the spectral function will be enforced" << endl; }
break;
case 'q':
q = atof(optarg);
if (verbose) { cout << "regularization q=" << q << endl; }
break;
case 's': savemore = true; break;
case 'S': saveall = true; break;
case 'x':
bmin = atof(optarg);
if (verbose) { cout << "minimal b(w)=" << bmin << endl; }
break;
case 'd':
dyn_mesh = atof(optarg);
if (verbose) { cout << "dyn_mesh=" << dyn_mesh << endl; }
break;
case 'o': one = true; break;
default: abort();
}
}
int remaining = argc - optind; // arguments left
if (remaining != 3) {
usage();
exit(1);
}
name = string(argv[optind]); // Name of spectral density files
b0 = atof(argv[optind + 1]); // Parameter b0 (asymptotic broadening)
assert(b0 > 0.0);
Nz = atoi(argv[optind + 2]); // Number of z-values
assert(Nz >= 1);
cout << "Processing: " << name << endl;
cout << "b0=" << b0 << " Nz=" << Nz << endl;
}
string tostring(int i) {
ostringstream S;
S << i;
return S.str();
}
// Load a file containing binary representation of raw spectral density.
// The grid is not assumed to be uniform.
void load(int i) {
// i-th z-value defines the name of the directory where the results of
// the NRG calculation are contained.
string filename;
if (one && Nz == 1) {
filename = name;
} else {
filename = tostring(i) + "/" + name;
}
ifstream f(filename.c_str(), ios::in | ios::binary);
if (!f.good() || f.eof() || !f.is_open()) {
cerr << "Error opening file " << filename << endl;
exit(1);
}
if (verbose) { cout << "Reading " << filename << endl; }
// Determine the number of records
f.seekg(0, ios::beg);
const ios::pos_type begin_pos = f.tellg();
f.seekg(0, ios::end);
const ios::pos_type end_pos = f.tellg();
const long len = end_pos - begin_pos;
assert(len % (2 * sizeof(double)) == 0);
const int nr = len / (2 * sizeof(double)); // number of pairs of double
if (verbose) { cout << "len=" << len << " nr=" << nr << " data points" << endl; }
// Allocate the read buffer. The data will be kept in memory for the
// duration of the calculation!
auto *buffer = new double[2 * nr];
f.seekg(0, ios::beg); // Return to the beginning of the file.
f.read((char *)buffer, len);
if (f.fail()) {
cerr << "Error reading " << filename << endl;
exit(1);
}
f.close();
// Keep record of the the buffer and its size.
buffers[i] = buffer;
sizes[i] = nr;
if (verbose) {
// Check normalization to 1.
double sum = 0.0;
for (int j = 0; j < nr; j++) sum += buffer[2 * j + 1];
cout << "Weight=" << sum << endl;
}
}
// Load all the input data.
void read_files() {
buffers = new double *[Nz + 1];
sizes = new int[Nz + 1];
for (int i = 1; i <= Nz; i++) { load(i); }
}
// Combine data from all NRG runs (z-averaging).
void merge() {
// Sum weight corresponding to equal frequencies. Map of
// (frequency,weight) pairs is used for this purpose.
for (int i = 1; i <= Nz; i++) {
for (int l = 0; l < sizes[i]; l++) {
double &freq = buffers[i][2 * l];
double &value = buffers[i][2 * l + 1];
auto I = spec.find(freq);
if (I == spec.end()) {
spec[freq] = value;
} else {
I->second += value;
}
}
}
nr_spec = spec.size();
if (verbose) { cout << nr_spec << " unique frequencies." << endl; }
// Normalize weight by 1/Nz, determine total weight, and store the
// (frequency,weight) data in the form of linear vectors for faster
// access in the ensuing calculations.
double sum = 0.0;
for (auto & I : spec) {
const double weight = (I.second /= Nz); // Normalize weight on the fly
const double freq = I.first;
vfreq.push_back(freq);
vspec.push_back(weight);
sum += weight;
}
if (verbose) { cout << "Total weight=" << sum << endl; }
assert(vfreq.size() == nr_spec && vspec.size() == nr_spec);
}
// Calculate integrated spectral function of (a) defined on the mesh (mesh)
// and store the results in a vector (inta). Trapezoid rule is used to
// perform the integration.
void integrate_a(const vec &a, const vec &mesh, vec &inta) {
assert(a.size() == mesh.size());
double sum = 0.0;
const int nr = a.size();
inta.resize(nr);
inta[0] = 0.0;
for (int i = 1; i < nr; i++) {
assert(mesh[i] > mesh[i - 1]);
sum += (a[i] + a[i - 1]) * (mesh[i] - mesh[i - 1]) / 2.0; // Trapezoid rule
inta[i] = sum; // Integrated spectrum up to current freq
}
if (verbose) { cout << "Total weight=" << sum << endl; }
}
// inta = \int [-infty, omega]
// intb = \int [0, omega]
// intc = \int [+infty, omega]
void combinations(const vec &mesh, const vec &inta, vec &intb, vec &intc) {
const int nr = mesh.size();
intb.resize(nr);
intc.resize(nr);
// Determine the value at omega=0
double omega0 = -1;
for (int i = 1; i < nr; i++) {
if (mesh[i - 1] < 0.0 && mesh[i] > 0.0) {
omega0 = (inta[i - 1] + inta[i]) / 2.0;
break;
}
}
// The value at +infty
const double omegainf = inta[nr - 1];
for (int i = 0; i < nr; i++) {
intb[i] = inta[i] - omega0;
intc[i] = omegainf - inta[i];
}
}
// Create a mesh on which the output spectral function will be computed.
void make_mesh(vec &mesh) {
assert(broaden_min < broaden_max);
assert(broaden_ratio > 1.0);
double z;
for (z = broaden_min; z < broaden_max; z *= broaden_ratio) {
mesh.push_back(z);
mesh.push_back(-z);
}
// One more point to ensure that the point 'broaden_max' is part of the
// full frequency interval.
z *= broaden_ratio;
mesh.push_back(z);
mesh.push_back(-z);
if (verbose) { cout << "Maximal frequency=" << z << endl; }
sort(mesh.begin(), mesh.end());
}
// Create an initial approximation for the frequency dependent broadening
// function b(omega).
void initial_b(vec &b) {
b.resize(nr_spec);
for (unsigned int i = 0; i < nr_spec; i++) { b[i] = b0; }
}
// The modified log-Gaussian broadening function.
// E is the output energy, omega the energy of a delta-peak contribution.
// Normalization issue: since alpha is associated with a particular
// delta peak, the broadened function is still normalized to one since
// alpha is a constant [for that particular contribution].
double bfnc(double E, double alpha, double omega) {
const double div = alpha * abs(E) * sqrt(M_PI);
const double gamma = alpha / 4.0;
const double ln = log(E / omega);
const double eksponent = -pow(ln / alpha - gamma, 2);
const double res = exp(eksponent) / div;
return res;
}
void refine_mesh(vec &mesh, const vec &a) {
assert(mesh.size() == a.size());
assert(mesh.size() >= 6); // minimal meaningful mesh size
const int nr = mesh.size();
vec newmesh;
// Negative part of the spectrum
newmesh.push_back(mesh[0]);
double newpt1 = -sqrt(mesh[0] * mesh[1]);
if (mesh[0] < newpt1 && newpt1 < mesh[1]) newmesh.push_back(newpt1); // always refine here, if still possible!
newmesh.push_back(mesh[1]);
for (int i = 2; i < nr && mesh[i] < 0.0; i++) {
const double deriv = (a[i - 2] - a[i - 1]) / (mesh[i - 2] - mesh[i - 1]);
const double y_predicted = a[i - 1] + deriv * (mesh[i] - mesh[i - 1]);
const double y = a[i];
const double error_ratio = abs((y - y_predicted) / y);
if (error_ratio > dyn_mesh) {
// add one additional mesh point!
// geometric average!
double newpt = -sqrt(mesh[i] * mesh[i - 1]);
// Only add a point if it is actually distinct from its
// neighbours. This check is necessary in the presence of
// singularities.
if (mesh[i - 1] < newpt && newpt < mesh[i]) newmesh.push_back(newpt);
}
newmesh.push_back(mesh[i]);
}
// Positive part of the spectrum
newmesh.push_back(mesh[nr - 1]);
double newpt2 = sqrt(mesh[nr - 1] * mesh[nr - 2]);
if (mesh[nr - 2] < newpt2 && newpt2 < mesh[nr - 1]) newmesh.push_back(newpt2); // always refine here!
newmesh.push_back(mesh[nr - 2]);
for (int i = (nr - 1) - 2; i > 0 && mesh[i] > 0.0; i--) {
const double deriv = (a[i + 2] - a[i + 1]) / (mesh[i + 2] - mesh[i + 1]);
const double y_predicted = a[i + 1] + deriv * (mesh[i] - mesh[i + 1]);
const double y = a[i];
const double error_ratio = abs((y - y_predicted) / y);
if (error_ratio > dyn_mesh) {
double newpt = +sqrt(mesh[i] * mesh[i + 1]);
if (mesh[i] < newpt && newpt < mesh[i + 1]) newmesh.push_back(newpt);
}
newmesh.push_back(mesh[i]);
}
sort(newmesh.begin(), newmesh.end());
// Trick: avoid copying!
mesh.swap(newmesh);
}
// Note: vector 'a' is resized to match the length of vector 'mesh'. The
// mesh can thus dynamically change from iteration to iteration.
void broaden(const vec &mesh, vec &a, const vec &b) {
const int nr_mesh = mesh.size();
if (verbose) { cout << "Broadening. nr_mesh=" << nr_mesh << endl; }
a.resize(nr_mesh);
for (int i = 0; i < nr_mesh; i++) {
const double &outputfreq = mesh[i];
a[i] = 0.0;
for (unsigned int j = 0; j < nr_spec; j++) {
const double &omega = vfreq[j];
bool sameSign = (outputfreq < 0.0) == (omega < 0.0);
if (sameSign) { a[i] += vspec[j] * bfnc(outputfreq, b[j], omega); }
}
// Enforce positivity
if (a[i] < 0.0 && enforce_positivity) {
if (veryverbose) { cout << "Warning: a(" << outputfreq << ")=" << a[i] << endl; }
a[i] = 1e-16;
}
}
}
// Save a map of (double,double) pairs to a file.
void save(const string filename0, const mapdd &m, int iter = 0, double trim = 0.0) {
const string filename = filename0 + (iter > 0 ? tostring(iter) : "") + ".dat";
if (verbose) { cout << "Saving " << filename << endl; }
ofstream F(filename.c_str());
if (!F) {
cerr << "Failed to open " << filename << " for writing." << endl;
exit(1);
}
for (auto I : m) {
if (trim != 0.0 && abs(I.first) < trim) { continue; }
F << I.first << " " << I.second << endl;
}
}
// Save pairs taken respectively from (mesh) and (data).
void save(const string filename0, const vec &mesh, const vec &data, int iter = 0, double trim = 0.0) {
const string filename = filename0 + (iter > 0 ? tostring(iter) : "") + ".dat";
if (verbose) { cout << "Saving " << filename << endl; }
ofstream F(filename.c_str());
if (!F) {
cerr << "Failed to open " << filename << " for writing." << endl;
exit(1);
}
assert(mesh.size() == data.size());
int nr = mesh.size();
for (int i = 0; i < nr; i++) {
const double x = mesh[i];
const double y = data[i];
if (trim != 0.0 && abs(x) < trim) { continue; }
if (std::isfinite(data[i])) {
F << x << " " << y << endl;
} else {
if (veryverbose) { cout << "Warning: " << i << " not finite." << endl; }
}
}
}
// Eq. (7) in the paper of Freyn & Florens
void calc_b(const vec &logd1, const vec &logd2, vec &bb) {
const unsigned int n = logd1.size();
bb.resize(n);
for (unsigned int i = 0; i < n; i++) {
const double part1 = 1.0 / (q + abs(logd1[i]));
const double part2 = 1.0 / (q + abs(logd2[i]));
const double avg = q * (part1 + part2) / 2.0;
bb[i] = b0 * avg;
}
}
// Calculate a logarithmic derivative of (inta).
// We take dlog f/dlog omega = Delta (log f)/Delta (log omega)
// = (log f_1-log f_0)/(log omega_1-log omega_0)
// = log(f_1/f_0) / log(omega_1/omega_0).
void calc_deriv(const vec &inta, vec &deriv) {
if (verbose) { cout << "Calculating a logarithmic derivative." << endl; }
int nr = inta.size();
deriv.resize(nr);
deriv[0] = 0.0;
for (int i = 1; i < nr; i++) {
const double &w0 = mesh[i - 1];
const double &w1 = mesh[i];
const double &f0 = inta[i - 1];
const double &f1 = inta[i];
assert(w1 > w0);
const double log1 = log(f1 / f0);
if (!std::isfinite(log1)) {
if (veryverbose) { cout << "Warning: log1 not finite at w0=" << w0 << endl; }
}
const double log2 = log(abs(w1 / w0));
assert(std::isfinite(log2));
const double d = log1 / log2;
if (std::isfinite(d)) {
deriv[i] = d;
} else {
deriv[i] = 0.0;
}
}
}
typedef pair<double, double> Pair;
using Vec = vector<Pair>;
// Linear interpolation class
class LinInt {
protected:
Vec vec; // tabulated data
int len{}; // length of vec
int index{}; // index of the interval where last x was found
double x0{}, x1{}; // last x was in [x0:x1]
double f0{}, f1{}; // f(x0), f(x1)
double deriv{}; // (f1-f0)/(x1-x0)
bool newintegral_flag{}; // set to true when we switch to a new interval
double xmin{}, xmax{}; // lowest and highest x contained in vec
double fxmin{}, fxmax{}; // f(xmin), f(xmax)
public:
LinInt()= default;
LinInt(Vec &in_vec) : vec(in_vec) {
len = vec.size();
index = -1;
newintegral_flag = false;
xmin = vec.front().first;
fxmin = vec.front().second;
xmax = vec.back().first;
fxmax = vec.back().second;
};
void findindex(double x);
double operator()(double x);
};
// Serach for the interval so that x is contained in [x0:x1].
void LinInt::findindex(double x) {
if (index == -1) {
// When interpolation class object is constructed, index is
// initialized to -1. We have no prior knowledge, thus we search in
// the full interval.
for (int i = 0; i < len - 1; i++) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
} else {
if (x >= x1) {
for (int i = index + 1; i < len - 1; i++) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
} else {
for (int i = index - 1; i >= 0; i--) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
}
}
if (!(0 <= index && index < len && x0 <= x && x <= x1)) {
cerr << "findindex() error."
<< " x=" << x << " x0=" << x0 << " x1=" << x1 << " index=" << index << " len=" << len << endl;
exit(1);
}
f0 = vec[index].second; // f(x0)
f1 = vec[index + 1].second; // f(x1)
double Delta_y = f1 - f0;
double Delta_x = x1 - x0;
deriv = Delta_y / Delta_x;
}
// Return y(x) using linear interpolation between the tabulated values.
double LinInt::operator()(double x) {
// Extrapolate if necessary
if (x <= xmin) { return fxmin; }
if (x >= xmax) { return fxmax; }
if (index == -1 || !(x0 <= x && x < x1)) {
newintegral_flag = true;
findindex(x);
}
double dx = x - x0;
return f0 + deriv * dx;
}
void recalc_b(const vec &mesh, const vec &bpos, const vec &bneg, vec &b) {
if (verbose) { cout << "Recalculating b(omega)" << endl; }
const unsigned int sizepos = bpos.size();
Vec Vecbpos(sizepos);
for (unsigned int i = 0; i < sizepos; i++) {
Vecbpos[i].first = mesh[i];
Vecbpos[i].second = bpos[i];
}
LinInt fpos(Vecbpos);
const unsigned int sizeneg = bneg.size();
Vec Vecbneg(sizeneg);
for (unsigned int i = 0; i < sizeneg; i++) {
Vecbneg[i].first = mesh[i];
Vecbneg[i].second = bneg[i];
}
LinInt fneg(Vecbneg);
for (unsigned int i = 0; i < nr_spec; i++) {
const double new_b = (vfreq[i] < 0.0 ? fneg(vfreq[i]) : fpos(vfreq[i]));
assert(new_b > 0.0);
b[i] = (new_b > bmin ? new_b : bmin);
}
}
// Set default values which depend on the chosen values of other
// parameters.
void defaults() {
if (dyn_mesh > 0.0) {
// Dynamic mesh
if (bmin < 0.0) { bmin = 0.0; }
} else {
// Fixed mesh
if (bmin < 0.0) { bmin = broaden_ratio - 1.0; }
assert(bmin <= b0);
}
if (trim < 0.0) { trim = broaden_min * 10; }
}
int main(int argc, char *argv[]) {
cout << "bw - Adaptive broadening tool - " << VERSION << endl;
cout << "Rok Zitko, rok.zitko@ijs.si, 2009-2010" << endl;
cout << setprecision(16);
cmd_line(argc, argv);
defaults();
read_files();
merge();
make_mesh(mesh);
initial_b(b);
if (savemore) { save("b", vfreq, b, 0, trim); }
for (int iter = 1; iter <= nr_iter; iter++) {
broaden(mesh, a, b);
if (savemore || iter == nr_iter) { save("a", mesh, a, iter, trim); }
integrate_a(a, mesh, inta);
if (saveall) { save("inta", mesh, inta, iter); }
// inta = \int [-infty, omega]
// intb = \int [0, omega]
// intc = \int [+infty, omega]
combinations(mesh, inta, intb, intc);
if (saveall) {
save("intb", mesh, intb, iter);
save("intc", mesh, intc, iter);
}
vec deriva, derivb, derivc;
calc_deriv(inta, deriva);
calc_deriv(intb, derivb);
calc_deriv(intc, derivc);
if (saveall) {
save("deriva", mesh, deriva, iter);
save("derivb", mesh, derivb, iter);
save("derivc", mesh, derivc, iter);
}
vec bpos;
calc_b(derivb, derivc, bpos);
vec bneg;
calc_b(deriva, derivb, bneg);
recalc_b(mesh, bpos, bneg, b);
if (saveall) {
save("bpos", mesh, bpos, iter);
save("bneg", mesh, bneg, iter);
}
if (savemore) { save("b", vfreq, b, iter, trim); }
if (dyn_mesh > 0.0) { refine_mesh(mesh, a); }
}
}
| 21,215
|
C++
|
.cc
| 596
| 31.518456
| 113
| 0.577422
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,545
|
binavg.cc
|
rokzitko_nrgljubljana/tools/binavg/binavg.cc
|
#include <iostream>
#include <iomanip>
#include <string_view>
#include "binavg.hpp"
constexpr std::string_view VERSION = "0.0.2";
const int cout_PREC = 18; // Precision for verbose reporting on console
int main(int argc, char *argv[]) {
std::cout << "binvag - binned binary data averaging tool - " << VERSION << std::endl;
std::cout << "Rok Zitko, rok.zitko@ijs.si, 2013" << std::endl;
std::cout << std::setprecision(cout_PREC);
NRG::BinAvg::BinAvg binavg(argc, argv);
binavg.calc();
}
| 498
|
C++
|
.cc
| 13
| 36.384615
| 87
| 0.693582
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,546
|
resample.cc
|
rokzitko_nrgljubljana/tools/resample/resample.cc
|
#include "resample.hpp"
int main(int argv, char *argc[]) {
NRG::Resample::Resample<double> resample(argv, argc);
resample.run();
}
| 136
|
C++
|
.cc
| 5
| 25.2
| 55
| 0.707692
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,547
|
tdavg.cc
|
rokzitko_nrgljubljana/tools/tdavg/tdavg.cc
|
// tdavg - Averaging with interpolation for thermodynamics
// Part of "NRG Ljubljana", Rok Zitko, rok.zitko@ijs.si, Aug 2009
#define PROGRAM "tdavg"
#define DESCRIPTION "thermodynamics averaging tool"
#define VERSION "0.2.1"
#define USAGE "[-h] [input] [reference]"
#define AUTHOR "Rok Zitko, rok.zitko@ijs.si, 2020"
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cfloat>
#include <utility>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <cstring>
#include <sys/stat.h>
#include <unistd.h>
#include <getopt.h>
using namespace std;
bool verbose = false; // output verbosity level
bool veryverbose = false; // horribly detailed output
string name; // input file
string ref_name; // reference file (to be subtracted element by element)
bool copycomments = false;
string lastcommentline = "";
using dvec = vector<double>;
typedef pair<double, dvec> Line;
using multiVec = vector<Line>;
typedef pair<double, double> dpair;
using Vec = vector<dpair>;
using DataType = vector<multiVec>;
DataType input; // input data
DataType reference; // reference data (to be subtracted element by element)
dvec mesh; // output mesh
unsigned int Nz; // number of data sets (twist parameters z)
unsigned int columns = 0; // number of columns (excluding the first column!)
const int OUTPUT_PRECISION = 16;
void usage(ostream &F = cout) { F << "Usage: " << PROGRAM << " " << USAGE << endl; }
// Check for the existance of a regular file.
bool file_exists(string filename) {
struct stat s{};
int result = stat(filename.c_str(), &s);
if (result == 0 && S_ISREG(s.st_mode)) return true;
return false;
}
void cmd_line(int argc, char *argv[]) {
char c;
while (c = getopt(argc, argv, "hvVc"), c != -1) {
switch (c) {
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'v': verbose = true; break;
case 'V': veryverbose = true; break;
case 'c': copycomments = true; break;
default: abort();
}
}
int remaining = argc - optind; // arguments left
if (remaining > 2) {
usage();
exit(1);
}
if (remaining >= 1) {
name = string(argv[optind]); // Input filename
} else {
name = string("td.dat");
}
if (remaining >= 2) {
ref_name = string(argv[optind+1]); // Reference filename
} else {
const string ref_name_default = "td-ref.dat";
if (file_exists("td-ref.dat")) {
ref_name = ref_name_default;
} else {
ref_name = string("");
}
}
}
// Split a string containing double floating point number into a vector.
// All empty spaces are stripped.
dvec split(const string &s) {
dvec elements;
string::const_iterator i = s.begin();
// Skip to first non-space
while (i != s.end() && isspace(*i)) i++;
while (i != s.end()) {
string substring;
while (i != s.end() && !isspace(*i)) {
substring += *i;
i++;
}
elements.push_back(atof(substring.c_str()));
// Skip to next non-space
while (i != s.end() && isspace(*i)) i++;
}
return elements;
}
ostream &operator<<(ostream &os, const dvec &v) {
for (double i : v) { os << i << " "; }
return os;
}
ostream &operator<<(ostream &os, const Vec &v) {
for (const auto & i : v) { os << i.first << " " << i.second << endl; }
return os;
}
DataType load(const string &filename) {
ifstream f(filename.c_str());
if (!f.good() || f.eof() || !f.is_open()) {
cerr << "Error opening file " << filename << endl;
exit(1);
}
cout << "Reading " << filename << endl;
DataType result;
// skip comment lines and locate the first data block
while (f.good() && f.peek() == '#') {
string line;
getline(f, line);
if (veryverbose) cout << "##" << line << endl;
if (copycomments) lastcommentline = line;
}
do {
multiVec data; // contains data for one block
while (f.good() && f.peek() != '#') {
string line;
getline(f, line);
if (veryverbose) cout << line << endl;
if (f.fail()) break;
dvec elements = split(line);
if (elements.size() == 0) {
cerr << "Error parsing line: " << line << endl;
exit(1);
}
if (columns == 0) {
columns = elements.size() - 1;
} else {
if (elements.size() - 1 != columns) {
cerr << "Unequal number of columns in line: " << endl << line << endl;
exit(1);
}
}
double T = elements[0]; // temperature
dvec values = dvec(elements.begin() + 1, elements.end());
if (veryverbose) cout << T << " " << values << endl;
data.push_back(make_pair(T, values));
}
if (data.size() != 0) {
if (verbose) cout << "Block length " << data.size() << endl;
result.push_back(data); // accumulate results for all blocks
}
// skip comments to next block
while (f.good() && f.peek() == '#') {
string line;
getline(f, line);
if (veryverbose) { cout << "#" << line << endl; }
}
} while (f.good() && !f.eof());
return result;
}
// Load all the input data.
void read_files() {
input = load(name);
Nz = input.size();
if (Nz == 0) {
cerr << "Failed loading the input data!" << endl;
exit(1);
}
if (ref_name != "") {
reference = load(ref_name);
unsigned int Nz_ref = reference.size();
if (Nz != Nz_ref) {
cerr << "Reference data sets do not match the input!" << endl;
exit(1);
}
}
if (verbose) cout << "Nz=" << Nz << " columns=" << columns << endl;
}
// Linear interpolation class
class LinInt {
protected:
Vec vec; // tabulated data
int len{}; // length of vec
int index{}; // index of the interval where last x was found
double x0{}, x1{}; // last x was in [x0:x1]
double f0{}, f1{}; // f(x0), f(x1)
double deriv{}; // (f1-f0)/(x1-x0)
bool newintegral_flag{}; // set to true when we switch to a new interval
double xmin{}, xmax{}; // lowest and highest x contained in vec
double fxmin{}, fxmax{}; // f(xmin), f(xmax)
public:
LinInt()= default;
LinInt(Vec &in_vec) : vec(in_vec) {
len = vec.size();
index = -1;
newintegral_flag = false;
xmin = vec.front().first;
fxmin = vec.front().second;
xmax = vec.back().first;
fxmax = vec.back().second;
};
void findindex(double x);
double operator()(double x);
};
// Serach for the interval so that x is contained in [x0:x1].
void LinInt::findindex(double x) {
if (index == -1) {
// When interpolation class object is constructed, index is
// initialized to -1. We have no prior knowledge, thus we search in
// the full interval.
for (int i = 0; i < len - 1; i++) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
} else {
if (x >= x1) {
for (int i = index + 1; i < len - 1; i++) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
} else {
for (int i = index - 1; i >= 0; i--) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
}
}
if (!(0 <= index && index < len && x0 <= x && x <= x1)) {
cerr << "findindex() error."
<< " x=" << x << " x0=" << x0 << " x1=" << x1 << " index=" << index << " len=" << len << endl;
exit(1);
}
f0 = vec[index].second; // f(x0)
f1 = vec[index + 1].second; // f(x1)
double Delta_y = f1 - f0;
double Delta_x = x1 - x0;
deriv = Delta_y / Delta_x;
}
// Return y(x) using linear interpolation between the tabulated values.
double LinInt::operator()(double x) {
// Extrapolate if necessary
if (x <= xmin) return fxmin;
if (x >= xmax) return fxmax;
if (index == -1 || !(x0 <= x && x < x1)) {
newintegral_flag = true;
findindex(x);
}
double dx = x - x0;
return f0 + deriv * dx;
}
const double EPS = 1e-6;
inline bool eq_approx(double a, double b) { return abs((a - b) / a) < EPS; }
dvec merge_meshes() {
dvec mesh;
for (unsigned int i = 0; i < Nz; i++) {
const unsigned int len = input[i].size();
for (unsigned int j = 0; j < len; j++) { mesh.push_back(input[i][j].first); }
}
sort(mesh.begin(), mesh.end());
auto new_end = unique(mesh.begin(), mesh.end(), eq_approx);
mesh.erase(new_end, mesh.end());
return mesh;
}
using LinIntVector = vector<LinInt>;
using IntType = vector<LinIntVector>;
IntType f, reff; // interpolation objects
IntType interpolate(const DataType &data) {
IntType result;
for (unsigned int i = 0; i < Nz; i++) {
LinIntVector f0;
for (unsigned int j = 0; j < columns; j++) {
unsigned int len = data[i].size();
Vec v(len);
for (unsigned int k = 0; k < len; k++) v[k] = make_pair(data[i][k].first, data[i][k].second[j]);
sort(v.begin(), v.end()); // important!
f0.push_back(LinInt(v));
}
result.push_back(f0);
}
return result;
}
multiVec avg() {
multiVec result;
const unsigned int len = mesh.size();
for (unsigned int j = 0; j < len; j++) {
const double T = mesh[j]; // temperature
dvec sum(columns, 0.0); // vector of column sums
for (unsigned int k = 0; k < columns; k++) {
for (unsigned int i = 0; i < Nz; i++) {
sum[k] += f[i][k](T) / Nz;
if (ref_name != "") sum[k] -= reff[i][k](T) / Nz;
}
}
result.push_back(make_pair(T, sum));
}
return result;
}
void save(const multiVec &result, ostream &f) {
const unsigned int len = result.size();
for (unsigned int j = 0; j < len; j++) {
f << result[j].first << " ";
assert(result[j].second.size() == columns);
for (unsigned int k = 0; k < columns; k++) f << result[j].second[k] << " ";
f << endl;
}
}
void hello() {
cout << PROGRAM << " - " << DESCRIPTION << " - " << VERSION << endl;
cout << AUTHOR << endl;
}
int main(int argc, char *argv[]) {
hello();
cout << setprecision(OUTPUT_PRECISION);
cmd_line(argc, argv);
const string output_name = (name == "td.dat" ? "td-avg.dat" : name + ".avg.dat");
ofstream OF(output_name.c_str());
if (!OF) {
cerr << "Failed opening " << output_name << endl;
exit(1);
}
OF << setprecision(OUTPUT_PRECISION);
read_files();
mesh = merge_meshes();
f = interpolate(input);
if (ref_name != "") reff = interpolate(reference);
multiVec result = avg();
if (copycomments && lastcommentline != "") OF << lastcommentline << endl;
save(result, OF);
}
| 10,781
|
C++
|
.cc
| 346
| 27.138728
| 103
| 0.575425
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,548
|
unitary.cc
|
rokzitko_nrgljubljana/tools/unitary/unitary.cc
|
#include "unitary.hpp"
int main(int argc, char *argv[]) {
using namespace NRG::Unitary;
Unitary unit(argc, argv);
unit.run(argc, argv);
}
| 145
|
C++
|
.cc
| 6
| 22
| 34
| 0.702899
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,549
|
h5write.cc
|
rokzitko_nrgljubljana/tools/h5write/h5write.cc
|
#include "h5write.hpp"
int main(int argc, char *argv[]) {
NRG::H5Write::H5Write h5write(argc, argv);
h5write.run();
}
| 123
|
C++
|
.cc
| 5
| 22.6
| 44
| 0.692308
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,550
|
diag.cc
|
rokzitko_nrgljubljana/tools/diag/diag.cc
|
// Diagonalisation tool
// Computes eigenvalues and eigenvectors of a matrix
// Rok Zitko, rok.zitko@ijs.si, 2009-2024
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cfloat>
#include <utility>
#include <vector>
#include <string>
#include <map>
#include <ctime>
#include <unistd.h>
using namespace std;
using DVEC = std::vector<double>;
bool output_bin = false;
bool output_text = true;
bool quiet = false;
bool verbose = false;
bool veryverbose = false;
const int OUTPUT_PREC = 18;
const char *fn_val = nullptr;
const char *fn_vec = nullptr;
double scale_factor = 1.0;
void about(ostream &OUT = cout) {
if (!quiet) {
OUT << "# diag -- command line eigensolver tool" << endl;
OUT << "# Rok Zitko, rok.zitko@ijs.si, May 2009" << endl;
}
}
inline int MAX(int a, int b) { return (a > b ? a : b); }
#include "lapack.h"
#define IJ(i, j) (dim * (i) + (j))
void diagonalize(unsigned int dim, DVEC &d) {
double *ham = &d[0]; // contiguous storage guaranteed
std::vector<double> eigenvalues(dim); // eigenvalues on exit
char jobz = 'V'; // eigenvalues and eigenvectors
char UPLO = 'L'; // lower triangle of a is stored
int NN = dim; // the order of the matrix
int LDA = dim; // the leading dimension of the array a
int INFO = 0; // 0 on successful exit
int LWORK0 = -1; // length of the WORK array
std::vector<double> WORK0(1);
// Step 1: determine optimal LWORK
LAPACK_dsyev(&jobz, &UPLO, &NN, ham, &LDA, eigenvalues.data(), WORK0.data(), &LWORK0, &INFO);
assert(INFO == 0);
int LWORK = int(WORK0[0]);
if (verbose) { cout << "LWORK=" << LWORK << endl; }
assert(LWORK > 0);
const int minLWORK = MAX(1, 3 * dim - 1); // cf. LAPACK 3.1 dsyev.f
if (LWORK < minLWORK) {
cerr << "Buggy dsyev. Fixing LWORK." << endl;
LWORK = minLWORK;
}
std::vector<double> WORK(LWORK);
// Step 2: perform the diagonalisation
LAPACK_dsyev(&jobz, &UPLO, &NN, ham, &LDA, eigenvalues.data(), WORK.data(), &LWORK, &INFO);
if (INFO != 0) {
cerr << "eigensolver failed. INFO=" << INFO;
abort();
}
// Perform the optional scaling
for (unsigned int r = 0; r < dim; r++) { eigenvalues[r] *= scale_factor; }
if (verbose) {
cout << "Eigenvalues: " << endl;
for (unsigned int r = 0; r < dim; r++) { cout << r + 1 << " " << eigenvalues[r] << endl; }
cout << endl;
}
if (veryverbose) {
cout << "Eigenvectors: " << endl;
for (unsigned int r = 0; r < dim; r++) {
cout << r + 1 << " ";
for (unsigned int j = 0; j < dim; j++) { cout << ham[IJ(r, j)] << (j != dim - 1 ? " " : ""); }
cout << endl;
}
cout << endl;
}
if (fn_val != nullptr) {
if (verbose) { cout << "Saving eigenvalues to " << fn_val << " [text]" << endl; }
ofstream F(fn_val);
if (!F) {
cerr << "Can't open file for writing." << endl;
abort();
}
F << setprecision(OUTPUT_PREC);
for (unsigned int r = 0; r < dim; r++) { F << eigenvalues[r] << endl; }
F.close();
}
if (fn_vec != nullptr && output_text) {
if (verbose) { cout << "Saving eigenvectors to " << fn_vec << " [text]" << endl; }
ofstream F(fn_vec);
if (!F) {
cerr << "Can't open file for writing." << endl;
abort();
}
F << setprecision(OUTPUT_PREC);
for (unsigned int r = 0; r < dim; r++) {
for (unsigned int j = 0; j < dim; j++) { F << ham[IJ(r, j)] << (j != dim - 1 ? " " : ""); }
F << endl;
}
F.close();
}
if (fn_vec != nullptr && output_bin) {
if (verbose) { cout << "Saving eigenvectors to " << fn_vec << " [bin]" << endl; }
ofstream F(fn_vec, ios_base::binary);
if (!F) {
cerr << "Can't open file for writing." << endl;
abort();
}
// Save matrix dimensions
F.write((char *)&dim, sizeof(unsigned int));
F.write((char *)&dim, sizeof(unsigned int));
for (unsigned int r = 0; r < dim; r++) {
for (unsigned int j = 0; j < dim; j++) {
const double el = ham[IJ(r, j)];
F.write((char *)&el, sizeof(double));
}
}
F.close();
}
}
// Diagonalise a matrix obtained by reading data from stream F
void diag_stream(istream &F) {
DVEC data;
while (F.good()) {
double x;
F >> x;
if (!F.fail()) { data.push_back(x); }
}
int size = data.size();
int N = (int)sqrt(size);
if (verbose) { cout << "size=" << size << " N=" << N << endl; }
if (size % (N * N) != 0) { cerr << "ERROR: matrix must be square!" << endl; }
diagonalize(N, data);
}
void usage(ostream &OUT = cout) {
OUT << "Usage: diag [-h] [-t | -T] [-b | -B] [-vVq] [-o fn_val] [-O fn_vec] [-s scale] <input file>" << endl;
}
void parse_param(int argc, char *argv[]) {
char c;
while (c = getopt(argc, argv, "htTbBvVqo:O:s:"), c != -1) {
switch (c) {
case 'h':
usage();
exit(EXIT_SUCCESS);
case 't': output_text = false; break;
case 'T': output_text = true; break;
case 'b': output_bin = false; break;
case 'B': output_bin = true; break;
case 'v': verbose = true; break;
case 'V': veryverbose = true; break;
case 'q': quiet = true; break;
case 'o': fn_val = optarg; break;
case 'O': fn_vec = optarg; break;
case 's': scale_factor = atof(optarg); break;
default: cerr << "Unknown argument " << c << endl; abort();
}
}
}
void run(int argc, char *argv[]) {
int remaining = argc - optind; // arguments left
if (remaining == 1) {
char *filename = argv[optind];
ifstream F(filename);
if (!F) {
cerr << "Error opening file " << filename << endl;
abort();
}
diag_stream(F);
F.close();
return;
}
usage();
}
int main(int argc, char *argv[]) {
clock_t start_clock = clock();
cout << setprecision(OUTPUT_PREC);
parse_param(argc, argv);
about();
run(argc, argv);
clock_t end_clock = clock();
if (!quiet) { cout << "# Elapsed " << double(end_clock - start_clock) / CLOCKS_PER_SEC << " s" << endl; }
}
| 6,098
|
C++
|
.cc
| 186
| 28.72043
| 112
| 0.57238
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,551
|
sym-SPSU2C3.cc
|
rokzitko_nrgljubljana/c++/sym-SPSU2C3.cc
|
#include "nrg-general.hpp"
#include "sym-SPSU2C3-impl.hpp"
#include "sym-SPSU2C3.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<cmpl>> mk_SPSU2C3(const Params &P)
{
return std::make_unique<SymmetrySPSU2C3<cmpl>>(P);
}
}
| 262
|
C++
|
.cc
| 10
| 24.8
| 59
| 0.756
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,552
|
sym-DBLISOSZ.cc
|
rokzitko_nrgljubljana/c++/sym-DBLISOSZ.cc
|
#include "nrg-general.hpp"
#include "sym-DBLISOSZ-impl.hpp"
#include "sym-DBLISOSZ.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_DBLISOSZ(const Params &P)
{
return std::make_unique<SymmetryDBLISOSZ<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_DBLISOSZ(const Params &P)
{
return std::make_unique<SymmetryDBLISOSZ<cmpl>>(P);
}
}
| 402
|
C++
|
.cc
| 15
| 25.333333
| 62
| 0.757813
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,553
|
sym-QSZ.cc
|
rokzitko_nrgljubljana/c++/sym-QSZ.cc
|
#include "nrg-general.hpp"
#include "sym-QSZ-impl.hpp"
#include "sym-QSZ.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_QSZ(const Params &P)
{
return std::make_unique<SymmetryQSZ<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_QSZ(const Params &P)
{
return std::make_unique<SymmetryQSZ<cmpl>>(P);
}
}
| 373
|
C++
|
.cc
| 15
| 23.333333
| 57
| 0.737288
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,554
|
sym-QSZTZ.cc
|
rokzitko_nrgljubljana/c++/sym-QSZTZ.cc
|
#include "nrg-general.hpp"
#include "sym-QSZTZ-impl.hpp"
#include "sym-QSZTZ.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_QSZTZ(const Params &P)
{
return std::make_unique<SymmetryQSZTZ<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_QSZTZ(const Params &P)
{
return std::make_unique<SymmetryQSZTZ<cmpl>>(P);
}
}
| 384
|
C++
|
.cc
| 15
| 24.133333
| 59
| 0.745902
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,555
|
sym-QSZLR.cc
|
rokzitko_nrgljubljana/c++/sym-QSZLR.cc
|
#include "nrg-general.hpp"
#include "sym-QSZLR-impl.hpp"
#include "sym-QSZLR.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_QSZLR(const Params &P)
{
return std::make_unique<SymmetryQSZLR<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_QSZLR(const Params &P)
{
return std::make_unique<SymmetryQSZLR<cmpl>>(P);
}
}
| 384
|
C++
|
.cc
| 15
| 24.133333
| 59
| 0.745902
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,556
|
sym-QST.cc
|
rokzitko_nrgljubljana/c++/sym-QST.cc
|
#include "nrg-general.hpp"
#include "sym-QST-impl.hpp"
#include "sym-QST.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_QST(const Params &P)
{
return std::make_unique<SymmetryQST<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_QST(const Params &P)
{
return std::make_unique<SymmetryQST<cmpl>>(P);
}
}
| 372
|
C++
|
.cc
| 15
| 23.333333
| 57
| 0.737288
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,557
|
sym-QS.cc
|
rokzitko_nrgljubljana/c++/sym-QS.cc
|
#include "nrg-general.hpp"
#include "sym-QS-impl.hpp"
#include "sym-QS.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_QS(const Params &P)
{
return std::make_unique<SymmetryQS<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_QS(const Params &P)
{
return std::make_unique<SymmetryQS<cmpl>>(P);
}
}
| 367
|
C++
|
.cc
| 15
| 22.933333
| 56
| 0.732759
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,558
|
sym-DBLSU2.cc
|
rokzitko_nrgljubljana/c++/sym-DBLSU2.cc
|
#include "nrg-general.hpp"
#include "sym-DBLSU2-impl.hpp"
#include "sym-DBLSU2.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_DBLSU2(const Params &P)
{
return std::make_unique<SymmetryDBLSU2<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_DBLSU2(const Params &P)
{
return std::make_unique<SymmetryDBLSU2<cmpl>>(P);
}
}
| 390
|
C++
|
.cc
| 15
| 24.533333
| 60
| 0.75
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,559
|
sym-DBLQSZ.cc
|
rokzitko_nrgljubljana/c++/sym-DBLQSZ.cc
|
#include "nrg-general.hpp"
#include "sym-DBLQSZ-impl.hpp"
#include "sym-DBLQSZ.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_DBLQSZ(const Params &P)
{
return std::make_unique<SymmetryDBLQSZ<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_DBLQSZ(const Params &P)
{
return std::make_unique<SymmetryDBLQSZ<cmpl>>(P);
}
}
| 391
|
C++
|
.cc
| 15
| 24.533333
| 60
| 0.75
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,560
|
sym-PP.cc
|
rokzitko_nrgljubljana/c++/sym-PP.cc
|
#include "nrg-general.hpp"
#include "sym-PP-impl.hpp"
#include "sym-PP.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_PP(const Params &P)
{
return std::make_unique<SymmetryPP<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_PP(const Params &P)
{
return std::make_unique<SymmetryPP<cmpl>>(P);
}
}
| 366
|
C++
|
.cc
| 15
| 22.933333
| 56
| 0.732759
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,561
|
sym-NONE.cc
|
rokzitko_nrgljubljana/c++/sym-NONE.cc
|
#include "nrg-general.hpp"
#include "sym-NONE-impl.hpp"
#include "sym-NONE.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_NONE(const Params &P)
{
return std::make_unique<SymmetryNONE<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_NONE(const Params &P)
{
return std::make_unique<SymmetryNONE<cmpl>>(P);
}
}
| 378
|
C++
|
.cc
| 15
| 23.733333
| 58
| 0.741667
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,562
|
sym-QSTZ.cc
|
rokzitko_nrgljubljana/c++/sym-QSTZ.cc
|
#include "nrg-general.hpp"
#include "sym-QSTZ-impl.hpp"
#include "sym-QSTZ.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_QSTZ(const Params &P)
{
return std::make_unique<SymmetryQSTZ<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_QSTZ(const Params &P)
{
return std::make_unique<SymmetryQSTZ<cmpl>>(P);
}
}
| 378
|
C++
|
.cc
| 15
| 23.733333
| 58
| 0.741667
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,563
|
sym-QJ.cc
|
rokzitko_nrgljubljana/c++/sym-QJ.cc
|
#include "nrg-general.hpp"
#include "sym-QJ-impl.hpp"
#include "sym-QJ.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_QJ(const Params &P)
{
return std::make_unique<SymmetryQJ<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_QJ(const Params &P)
{
return std::make_unique<SymmetryQJ<cmpl>>(P);
}
}
| 366
|
C++
|
.cc
| 15
| 22.933333
| 56
| 0.732759
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,564
|
sym-QSLR.cc
|
rokzitko_nrgljubljana/c++/sym-QSLR.cc
|
#include "nrg-general.hpp"
#include "sym-QSLR-impl.hpp"
#include "sym-QSLR.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_QSLR(const Params &P)
{
return std::make_unique<SymmetryQSLR<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_QSLR(const Params &P)
{
return std::make_unique<SymmetryQSLR<cmpl>>(P);
}
}
| 378
|
C++
|
.cc
| 15
| 23.733333
| 58
| 0.741667
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,565
|
sym-SPSU2.cc
|
rokzitko_nrgljubljana/c++/sym-SPSU2.cc
|
#include "nrg-general.hpp"
#include "sym-SPSU2-impl.hpp"
#include "sym-SPSU2.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_SPSU2(const Params &P)
{
return std::make_unique<SymmetrySPSU2<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_SPSU2(const Params &P)
{
return std::make_unique<SymmetrySPSU2<cmpl>>(P);
}
}
| 384
|
C++
|
.cc
| 15
| 24.133333
| 59
| 0.745902
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,566
|
sym-SU2.cc
|
rokzitko_nrgljubljana/c++/sym-SU2.cc
|
#include "nrg-general.hpp"
#include "sym-SU2-impl.hpp"
#include "sym-SU2.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_SU2(const Params &P)
{
return std::make_unique<SymmetrySU2<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_SU2(const Params &P)
{
return std::make_unique<SymmetrySU2<cmpl>>(P);
}
}
| 372
|
C++
|
.cc
| 15
| 23.333333
| 57
| 0.737288
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,567
|
sym-P.cc
|
rokzitko_nrgljubljana/c++/sym-P.cc
|
#include "nrg-general.hpp"
#include "sym-P-impl.hpp"
#include "sym-P.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_P(const Params &P)
{
return std::make_unique<SymmetryP<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_P(const Params &P)
{
return std::make_unique<SymmetryP<cmpl>>(P);
}
}
| 360
|
C++
|
.cc
| 15
| 22.533333
| 55
| 0.72807
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,568
|
sym-SL.cc
|
rokzitko_nrgljubljana/c++/sym-SL.cc
|
#include "nrg-general.hpp"
#include "sym-SL-impl.hpp"
#include "sym-SL.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_SL(const Params &P)
{
return std::make_unique<SymmetrySL<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_SL(const Params &P)
{
return std::make_unique<SymmetrySL<cmpl>>(P);
}
}
| 366
|
C++
|
.cc
| 15
| 22.933333
| 56
| 0.732759
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,569
|
sym-ISOSZ.cc
|
rokzitko_nrgljubljana/c++/sym-ISOSZ.cc
|
#include "nrg-general.hpp"
#include "sym-ISOSZ-impl.hpp"
#include "sym-ISOSZ.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_ISOSZ(const Params &P)
{
return std::make_unique<SymmetryISOSZ<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_ISOSZ(const Params &P)
{
return std::make_unique<SymmetryISOSZ<cmpl>>(P);
}
}
| 384
|
C++
|
.cc
| 15
| 24.133333
| 59
| 0.745902
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,570
|
sym-SPSU2T.cc
|
rokzitko_nrgljubljana/c++/sym-SPSU2T.cc
|
#include "nrg-general.hpp"
#include "sym-SPSU2T-impl.hpp"
#include "sym-SPSU2T.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_SPSU2T(const Params &P)
{
return std::make_unique<SymmetrySPSU2T<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_SPSU2T(const Params &P)
{
return std::make_unique<SymmetrySPSU2T<cmpl>>(P);
}
}
| 390
|
C++
|
.cc
| 15
| 24.533333
| 60
| 0.75
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,571
|
sym-SPU1.cc
|
rokzitko_nrgljubljana/c++/sym-SPU1.cc
|
#include "nrg-general.hpp"
#include "sym-SPU1-impl.hpp"
#include "sym-SPU1.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_SPU1(const Params &P)
{
return std::make_unique<SymmetrySPU1<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_SPU1(const Params &P)
{
return std::make_unique<SymmetrySPU1<cmpl>>(P);
}
}
| 378
|
C++
|
.cc
| 15
| 23.733333
| 58
| 0.741667
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,572
|
nrg-lib.cc
|
rokzitko_nrgljubljana/c++/nrg-lib.cc
|
#include "nrg-general.hpp"
// This is compiled n the library only. Should not be used if a cblas library is available.
#ifdef CBLAS_WORKAROUND
#define ADD_
#include "cblas_globals.c"
#include "cblas_dgemm.c"
#include "cblas_zgemm.c"
#include "cblas_xerbla.c"
#endif
namespace NRG {
void print_about_message() {
fmt::print("NRG Ljubljana - (c) rok.zitko@ijs.si\n");
fmt::print("Timestamp: {}\n", __TIMESTAMP__);
fmt::print("Compiled on {} at {}\n\n", __DATE__, __TIME__);
}
template <scalar S>
void run_nrg_master_impl(boost::mpi::environment &mpienv, boost::mpi::communicator &mpiw, std::unique_ptr<Workdir> workdir) {
std::shared_ptr<DiagEngine<S>> eng = std::make_shared<DiagMPI<S>>(mpienv, mpiw);
const bool embedded = false;
NRG_calculation<S> calc(std::move(workdir), eng, embedded);
}
// Called from the NRG stand-alone executable (MPI version)
void run_nrg_master(boost::mpi::environment &mpienv, boost::mpi::communicator &mpiw, std::unique_ptr<Workdir> workdir) {
if (complex_data())
run_nrg_master_impl<std::complex<double>>(mpienv, mpiw, std::move(workdir));
else
run_nrg_master_impl<double>(mpienv, mpiw, std::move(workdir));
}
template <scalar S>
void run_nrg_master_impl(const std::string &dir) {
auto workdir = set_workdir(dir);
std::shared_ptr<DiagEngine<S>> eng = std::make_shared<DiagOpenMP<S>>();
const bool embedded = true;
NRG_calculation<S> calc(std::move(workdir), eng, embedded);
}
// Called from a third-party application
void run_nrg_master(const std::string &dir) {
if (complex_data())
run_nrg_master_impl<std::complex<double>>(dir);
else
run_nrg_master_impl<double>(dir);
}
template<scalar S>
void run_nrg_slave_impl(boost::mpi::environment &mpienv, boost::mpi::communicator &mpiw) {
DiagMPI<S> eng(mpienv, mpiw);
constexpr auto master = 0;
DiagParams DP;
for (;;) {
if (mpiw.iprobe(master, boost::mpi::any_tag)) { // message can be received.
int task = 0;
const auto status = mpiw.recv(master, boost::mpi::any_tag, task);
mpilog("Slave " << mpiw.rank() << " received message with tag " << status.tag());
switch (status.tag()) {
case TAG_SYNC:
DP = eng.receive_params();
break;
case TAG_DIAG:
eng.slave_diag(master, DP);
break;
case TAG_EXIT:
return; // exit from run_slave()
default:
std::cout << "MPI error: unknown tag on " << mpiw.rank() << std::endl;
break;
}
} else usleep(100); // sleep to reduce the load on the computer. (OpenMPI "feature" workaround)
}
}
void run_nrg_slave(boost::mpi::environment &mpienv, boost::mpi::communicator &mpiw) {
if (complex_data())
run_nrg_slave_impl<std::complex<double>>(mpienv, mpiw);
else
run_nrg_slave_impl<double>(mpienv, mpiw);
}
} // namespace
| 2,818
|
C++
|
.cc
| 75
| 33.92
| 125
| 0.675448
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,573
|
sym-ISOLR.cc
|
rokzitko_nrgljubljana/c++/sym-ISOLR.cc
|
#include "nrg-general.hpp"
#include "sym-ISOLR-impl.hpp"
#include "sym-ISOLR.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_ISOLR(const Params &P)
{
return std::make_unique<SymmetryISOLR<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_ISOLR(const Params &P)
{
return std::make_unique<SymmetryISOLR<cmpl>>(P);
}
template <>
std::unique_ptr<Symmetry<double>> mk_ISO2LR(const Params &P)
{
return std::make_unique<SymmetryISO2LR<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_ISO2LR(const Params &P)
{
return std::make_unique<SymmetryISO2LR<cmpl>>(P);
}
}
| 644
|
C++
|
.cc
| 25
| 24.24
| 60
| 0.7443
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,574
|
sym-U1.cc
|
rokzitko_nrgljubljana/c++/sym-U1.cc
|
#include "nrg-general.hpp"
#include "sym-U1-impl.hpp"
#include "sym-U1.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_U1(const Params &P)
{
return std::make_unique<SymmetryU1<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_U1(const Params &P)
{
return std::make_unique<SymmetryU1<cmpl>>(P);
}
}
| 366
|
C++
|
.cc
| 15
| 22.933333
| 56
| 0.732759
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,575
|
nrg.cc
|
rokzitko_nrgljubljana/c++/nrg.cc
|
#define NRG_EXECUTABLE
#include <memory>
#include <string>
#include <vector>
#include <iostream>
#include <cstdlib>
#include "nrg-general.hpp" // common
#include "nrg-lib.hpp" // exposed in library
#include "nrg.hpp" // specific to executable
#include "openmp.hpp" // report_openMP() called from main()
#include "workdir.hpp"
using namespace NRG;
inline void help(int argc, char **argv, std::string help_message)
{
std::vector<std::string> args(argv+1, argv+argc); // NOLINT
if (args.size() >= 1 && args[0] == "-h") {
std::cout << help_message << std::endl;
exit(EXIT_SUCCESS);
}
}
auto set_workdir(int argc, char **argv) { // not inline!
std::string dir = default_workdir; // defined in workdir.h
if (const char *env_w = std::getenv("NRG_WORKDIR")) dir = env_w;
std::vector<std::string> args(argv+1, argv+argc); // NOLINT
if (args.size() == 2 && args[0] == "-w") dir = args[1];
return std::make_unique<Workdir>(dir);
}
int main(int argc, char **argv) {
print_about_message();
boost::mpi::environment mpienv(argc, argv);
boost::mpi::communicator mpiw;
if (mpiw.rank() == 0) {
help(argc, argv, "Usage: nrg [-h] [-w workdir]");
if (!file_exists("data")) {
std::cout << "Input file 'data' does not exist. Terminating." << std::endl;
return 1;
}
if (!file_exists("param")) {
std::cout << "Input file 'param' does not exist. Terminating." << std::endl;
return 1;
}
std::cout << "MPI job running on " << mpiw.size() << " processors." << std::endl << std::endl;
report_openMP();
auto workdir = set_workdir(argc, argv);
run_nrg_master(mpienv, mpiw, std::move(workdir));
} else {
run_nrg_slave(mpienv, mpiw); // slaves do no disk I/O to workdir
}
return 0;
}
| 1,775
|
C++
|
.cc
| 50
| 32.34
| 98
| 0.63409
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,576
|
sym-ISO.cc
|
rokzitko_nrgljubljana/c++/sym-ISO.cc
|
#include "nrg-general.hpp"
#include "sym-ISO-impl.hpp"
#include "sym-ISO.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_ISO(const Params &P)
{
return std::make_unique<SymmetryISO<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_ISO(const Params &P)
{
return std::make_unique<SymmetryISO<cmpl>>(P);
}
template <>
std::unique_ptr<Symmetry<double>> mk_ISO2(const Params &P)
{
return std::make_unique<SymmetryISO2<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_ISO2(const Params &P)
{
return std::make_unique<SymmetryISO2<cmpl>>(P);
}
}
| 624
|
C++
|
.cc
| 25
| 23.44
| 58
| 0.73569
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,577
|
sym-SPU1LR.cc
|
rokzitko_nrgljubljana/c++/sym-SPU1LR.cc
|
#include "nrg-general.hpp"
#include "sym-SPU1LR-impl.hpp"
#include "sym-SPU1LR.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_SPU1LR(const Params &P)
{
return std::make_unique<SymmetrySPU1LR<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_SPU1LR(const Params &P)
{
return std::make_unique<SymmetrySPU1LR<cmpl>>(P);
}
}
| 390
|
C++
|
.cc
| 15
| 24.533333
| 60
| 0.75
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,578
|
sym-ISOSZLR.cc
|
rokzitko_nrgljubljana/c++/sym-ISOSZLR.cc
|
#include "nrg-general.hpp"
#include "sym-ISOSZLR-impl.hpp"
#include "sym-ISOSZLR.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_ISOSZLR(const Params &P)
{
return std::make_unique<SymmetryISOSZLR<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_ISOSZLR(const Params &P)
{
return std::make_unique<SymmetryISOSZLR<cmpl>>(P);
}
}
| 396
|
C++
|
.cc
| 15
| 24.933333
| 61
| 0.753968
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,579
|
sym-SL3.cc
|
rokzitko_nrgljubljana/c++/sym-SL3.cc
|
#include "nrg-general.hpp"
#include "sym-SL3-impl.hpp"
#include "sym-SL3.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_SL3(const Params &P)
{
return std::make_unique<SymmetrySL3<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_SL3(const Params &P)
{
return std::make_unique<SymmetrySL3<cmpl>>(P);
}
}
| 372
|
C++
|
.cc
| 15
| 23.333333
| 57
| 0.737288
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,580
|
sym-SPSU2LR.cc
|
rokzitko_nrgljubljana/c++/sym-SPSU2LR.cc
|
#include "nrg-general.hpp"
#include "sym-SPSU2LR-impl.hpp"
#include "sym-SPSU2LR.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<double>> mk_SPSU2LR(const Params &P)
{
return std::make_unique<SymmetrySPSU2LR<double>>(P);
}
template <>
std::unique_ptr<Symmetry<cmpl>> mk_SPSU2LR(const Params &P)
{
return std::make_unique<SymmetrySPSU2LR<cmpl>>(P);
}
}
| 396
|
C++
|
.cc
| 15
| 24.933333
| 61
| 0.753968
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,581
|
sym-QSC3.cc
|
rokzitko_nrgljubljana/c++/sym-QSC3.cc
|
#include "nrg-general.hpp"
#include "sym-QSC3-impl.hpp"
#include "sym-QSC3.hpp" // include for consistency
namespace NRG {
template <>
std::unique_ptr<Symmetry<cmpl>> mk_QSC3(const Params &P)
{
return std::make_unique<SymmetryQSC3<cmpl>>(P);
}
}
| 250
|
C++
|
.cc
| 10
| 23.6
| 56
| 0.743697
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,582
|
test_clean.hpp
|
rokzitko_nrgljubljana/test/unit/include/test_clean.hpp
|
#pragma once
// test0_clean
auto setup_P_clean(Params &P) {
EXPECT_EQ(P.Lambda.value(), 2.0); // defaults
EXPECT_EQ(P.discretization.value(), "Z"s);
EXPECT_EQ(P.Ninit.value(), 0);
P.Nmax = P.Nlen = 1;
P.keep = 100;
P.ops = "n_f n_f^2";
P.specs = "n_f-n_f";
P.finite = true;
P.cfs = true;
P.fdm = true;
P.dmnrg = true;
P.finitemats = true;
P.fdmmats = true;
P.dmnrgmats = true;
P.mats = 10;
P.T = 0.1; // temperature
}
template<typename S>
auto setup_diag_clean(Params &P, [[maybe_unused]] Symmetry<S> *Sym)
{
std::string data =
"-1 1\n"
"1\n"
"0.\n"
"0 2\n"
"1\n"
"0.\n"
"1 1\n"
"1\n"
"0.\n";
std::istringstream ss(data);
P.absolute = false; // NOTE!!
DiagInfo<S> diag(ss, 3, P);
return diag;
}
template<typename S>
auto setup_opch_clean(const Params &P, [[maybe_unused]] Symmetry<S> *Sym, const DiagInfo<S> &diag) {
std::string str =
"f 0 0\n"
"2\n"
"1 1 0 2\n"
"1.4142135623730951\n"
"0 2 -1 1\n"
"1.\n";
std::istringstream ss(str);
return Opch<double>(ss, diag, P);
}
template<typename S>
auto setup_operators_clean(const DiagInfo<S> &diag)
{
auto op = Operators<S>();
std::string str_f =
"3\n"
"-1 1 -1 1\n"
"0.\n"
"0 2 0 2\n"
"1.\n"
"1 1 1 1\n"
"2.";
std::istringstream ss_f(str_f);
op.ops["n_f"] = MatrixElements<double>(ss_f, diag);
std::string str_f2 =
"3\n"
"-1 1 -1 1\n"
"0.\n"
"0 2 0 2\n"
"1.\n"
"1 1 1 1\n"
"4.";
std::istringstream ss_f2(str_f2);
op.ops["n_f^2"] = MatrixElements<double>(ss_f2, diag);
return op;
}
template<typename S>
auto setup_coef_clean(const Params &P) {
Coef<double> coef(P);
std::string str =
"1\n"
"0.54528747084262258072\n"
"0.41550946829175445321\n"
"1\n"
"0.e-999\n"
"0.e-998\n";
std::istringstream ss(str);
coef.xi.read(ss, P.coefchannels);
coef.zeta.read(ss, P.coefchannels);
return coef;
}
| 1,976
|
C++
|
.h
| 91
| 18.043956
| 100
| 0.582845
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,583
|
compare.hpp
|
rokzitko_nrgljubljana/test/unit/include/compare.hpp
|
#pragma once
#include <complex>
#include <string>
#include <vector>
#include <map>
#include <type_traits>
#include <exception>
#include <traits.hpp>
using namespace NRG;
void compare(const double a, const double b) {
EXPECT_DOUBLE_EQ(a, b);
}
void compare(const std::complex<double> a, const std::complex<double> b) {
EXPECT_DOUBLE_EQ(a.real(), b.real());
EXPECT_DOUBLE_EQ(a.imag(), b.imag());
}
void compare(const std::string &a, const std::string &b) {
EXPECT_EQ(a, b);
}
template<typename U, typename V>
void VECTOR_EQ(const U &A, const V &B)
{
EXPECT_EQ(A.size(), B.size());
for(int i = 0; i < A.size(); i++) EXPECT_EQ(A[i], B[i]);
}
template<typename U, typename V> // XXX: concept matrix: size1(), size2(), (i,j) accessor
void MATRIX_EQ(const U &A, const V &B)
{
EXPECT_EQ(size1(A), size1(B));
EXPECT_EQ(size2(A), size2(B));
for(int i = 0; i < size1(A); i++)
for(int j = 0; j < size2(A); j++)
EXPECT_EQ(A(i,j), B(i,j));
}
template<typename U, typename V> // XXX: concept vector: .size, [] accessor; constrain to double
void VECTOR_DOUBLE_EQ(const U &A, const V &B)
{
EXPECT_EQ(A.size(), B.size());
for(int i = 0; i < A.size(); i++) EXPECT_DOUBLE_EQ(A[i], B[i]);
}
template<typename U, typename V> // XXX: concept matrix: size1(), size2(), (i,j) accessor; constrain to double
void MATRIX_DOUBLE_EQ(const U &A, const V &B)
{
EXPECT_EQ(size1(A), size1(B));
EXPECT_EQ(size2(A), size2(B));
for(int i = 0; i < size1(A); i++)
for(int j = 0; j < size2(A); j++)
EXPECT_DOUBLE_EQ(A(i,j), B(i,j));
}
template<typename T1, typename T2, typename S1, typename S2>
void compare(const std::map<T1,T2> &a, const std::map<S1,S2> &b) {
ASSERT_EQ(a.size(), b.size());
for(auto const& [key, value] : a)
compare(b.at(key), value);
}
template <typename T1, typename T2, int N, int M, int K, int L>
void compare(Eigen::Matrix<T1,N,M> a, Eigen::Matrix<T2,K,L> b) {
ASSERT_EQ(a.rows(), b.rows());
ASSERT_EQ(a.cols(), b.cols());
for(int i = 0; i < a.rows(); i++)
for(int j = 0; j < a.cols(); j++)
compare(a(i,j), b(i,j));
}
template <typename T1, typename T2, int N>
void compare(Eigen::Matrix<T2,N,1> a, std::vector<T1> b) {
ASSERT_EQ(a.size(), b.size());
for(int i = 0; i < a.size(); i++)
compare(a(i), b[i]);
}
template <typename T1, typename T2, int N>
void compare(std::vector<T1> b, Eigen::Matrix<T2,N,1> a) {
compare(a,b);
}
| 2,414
|
C++
|
.h
| 73
| 30.657534
| 110
| 0.632759
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,584
|
test_common.hpp
|
rokzitko_nrgljubljana/test/unit/include/test_common.hpp
|
#pragma once
#include <tuple>
#include <workdir.hpp>
#include <params.hpp>
#include <mk_sym.hpp>
#include <invar.hpp>
#include <eigen.hpp>
using namespace NRG;
template<typename S>
auto setup_Sym(Params &P)
{
return set_symmetry<S>(P, "QS", 1);
}
template<typename S>
auto setup_diag(Params &P, [[maybe_unused]] Symmetry<S> *Sym)
{
std::string data =
"0 1\n"
"2 1 2\n"
"1 2\n"
"3 4 5 6\n";
std::istringstream ss(data);
P.absolute = true; // disable any energy rescaling
DiagInfo<S> diag(ss, 2, P);
return diag;
}
template<typename S>
auto setup_diag3(Params &P, [[maybe_unused]] Symmetry<S> *Sym)
{
std::string data =
"0 1\n"
"2 1 2\n"
"1 2\n"
"3 4 5 6\n"
"2 1\n"
"4 1 2 3 4\n";
std::istringstream ss(data);
P.absolute = true;
DiagInfo<S> diag(ss, 3, P);
return diag;
}
| 858
|
C++
|
.h
| 41
| 17.780488
| 62
| 0.628853
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,585
|
broaden.hpp
|
rokzitko_nrgljubljana/tools/broaden/broaden.hpp
|
// broaden - Finite-temperature raw spectral data broadening tool
// Ljubljana code Rok Zitko, rok.zitko@ijs.si, 2012-2020
#ifndef _broaden_broaden_hpp_
#define _broaden_broaden_hpp_
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cfloat>
#include <utility>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <stdexcept>
#include <numeric>
#include <unistd.h>
#include <getopt.h>
namespace NRG::Broaden {
constexpr double m_SQRTPI = 1.7724538509055160273;
const double R_1_SQRT2PI = 1.0 / sqrt(2.0 * M_PI); // sqrt not constexpr on all platforms (yet)
using std::abs; // important!!
inline std::string tostring(const int i) {
std::ostringstream S;
S << i;
return S.str();
}
template<typename T> auto sqr(const T x) { return x * x; }
inline double gaussian_kernel(const double x, const double y, const double sigma) {
const auto d = (x - y) / sigma;
return R_1_SQRT2PI * exp(-d * d / 2.0) / sigma;
}
// Derivative of the Fermi-Dirac function: -d/dw f_FD(x-y) with effective temperature sigma.
inline double derfd_kernel(const double x, const double y, const double sigma) {
const auto d = (x - y) / sigma;
return 1.0 / ((1.0 + cosh(d)) * 2.0 * sigma);
}
template<typename S, typename T, typename FNC>
void convolve(const std::vector<S> &mesh, std::vector<T> &a, const double sigma,
FNC kernel, const double cutoff_ratio = 100) {
const auto nr_mesh = mesh.size();
auto b(a); // source
a[0] = b[0];
a[nr_mesh - 1] = b[nr_mesh - 1];
for (auto i = 1; i < nr_mesh - 1; i++) {
const auto x = mesh[i];
if (abs(x) < cutoff_ratio * sigma) {
auto sum = 0.0;
auto sum_kernel = 0.0;
for (auto j = 1; j < nr_mesh - 1; j++) {
const auto y = mesh[j];
const auto width = (mesh[j + 1] + mesh[j]) / 2.0 - (mesh[j - 1] + mesh[j]) / 2.0;
const auto kw = kernel(x, y, sigma) * width;
assert(std::isfinite(kw));
sum += b[j] * kw;
sum_kernel += kw;
}
a[i] = sum;
} else {
// High temperatures: convolution not necessary
a[i] = b[i];
}
}
}
template<typename S, typename T>
void save(const std::string &filename, const std::vector<S> &x, const std::vector<T> &y,
bool verbose, const int SAVE_PREC = 18) {
if (verbose) { std::cout << "Saving " << filename << std::endl; }
std::ofstream F(filename.c_str());
if (!F) throw std::runtime_error("Failed to open " + filename + " for writing.");
F << std::setprecision(SAVE_PREC);
assert(x.size() == y.size());
const auto nr = x.size();
for (auto i = 0; i < nr; i++) { F << x[i] << " " << y[i] << std::endl; }
}
// Estimate the weight using the trapezoidal rule. The x array must be sorted.
template<typename T> T trapez(const std::vector<T> &x, const std::vector<T> &y) {
T weight = 0.0;
assert(x.size() == y.size());
const auto nr = x.size();
for (auto i = 1; i < nr; i++) {
assert(x[i] >= x[i-1]);
weight += (y[i-1] + y[i]) / 2 * (x[i] - x[i-1]);
}
return weight;
}
// Create a mesh on which the output spectral function will be computed. a is the accumulation point of the mesh.
auto make_mesh(const double min, const double max, const double ratio,
const double a, const bool add_positive = true, const bool add_negative = false) {
assert(min < max);
assert(ratio > 1.0);
const auto rescale_factor = (max-a)/max;
std::vector<double> mesh;
for (double z = max; z > min; z /= ratio) {
const auto x = a + z * rescale_factor;
if (add_positive) mesh.push_back(x);
if (add_negative) mesh.push_back(-x);
}
std::sort(mesh.begin(), mesh.end());
return mesh;
}
auto file_size(std::ifstream &f) {
f.seekg(0, std::ios::beg);
const auto begin_pos = f.tellg();
f.seekg(0, std::ios::end);
const auto end_pos = f.tellg();
return end_pos - begin_pos;
}
auto nr_doubles(std::ifstream &f) {
const auto len = file_size(f);
assert(len % sizeof(double) == 0);
return len/sizeof(double);
}
auto nr_rows(std::ifstream &f, const int cols) {
const auto d = nr_doubles(f);
assert(d % cols == 0);
return d / cols;
}
// Load a file containing binary representation of raw spectral density. The grid is not assumed to be uniform.
auto load(const std::string &filename, const int nrcol, const bool verbose) {
std::ifstream f(filename.c_str(), std::ios::in | std::ios::binary);
if (!f.good() || f.eof() || !f.is_open())
throw std::runtime_error("Error opening file " + filename + " for reading.");
if (verbose) { std::cout << "Reading " << filename << std::endl; }
const auto len = file_size(f); // in bytes
const auto cols = 1 + nrcol;
const auto rows = nr_rows(f, cols);
if (verbose) { std::cout << "len=" << len << ", " << rows << " data points" << std::endl; }
auto buffer = std::vector<double>(cols*rows);
f.seekg(0, std::ios::beg); // Return to the beginning of the file.
f.read((char *)buffer.data(), len);
if (f.fail()) throw std::runtime_error("Error reading " + filename);
f.close();
return buffer;
}
class Broaden {
private:
bool verbose = false; // output verbosity level
bool sumrules = false; // compute the integrals for testing the T!=0 sum rules
bool cumulative = false; // output of integrated spectral function
double broaden_min = 1e-7; // parameters defining the frequency mesh
double broaden_max = 2.0;
double broaden_ratio = 1.01;
double alpha; // broadening parameter alpha
double ggamma, dgamma; // broadening parameter gamma (final Gaussian, derFD)
double T; // temperature parameter
double omega0_ratio; // omega0=omega0_ratio*T
double omega0;
double accumulation = 0.0; // accumpulation point for the mesh
bool one = false; // For Nz=1, no subdir.
bool normalization = false; // What cross-over function to use?
double filterlow = 0.0; // filter all input data points with |omega|<filterlow
double filterhigh = DBL_MAX; // filter all input data points with |omega|>filterhigh
bool keeppositive = true; // Keep omega>0 data points when reading input data
bool keepnegative = true; // Keep omega<0 data points when reading input data
bool meshpositive = true; // Make omega>0 output mesh
bool meshnegative = true; // Make omega<0 output mesh
bool gaussian = false; // Gaussian broadening scheme
bool finalgaussian = false; // Final pass of Gaussian broadening of width ggamma*T
bool finalderfd = false; // Final pass of broadening with a derivative of FD distribution
int nrcol = 1; // Number of columns
int col = 1; // Which y column are we interested in?
std::string name; // filename of binary files containing the raw data
int Nz; // Number of spectra (1..Nz)
const std::string output_filename = "spec.dat";
const std::string cumulative_filename = "cumulative.dat";
std::vector<std::vector<double>> buffers; // binary data buffers
using mapdd = std::map<double, double>;
using vec = std::vector<double>;
mapdd spec; // Spectrum
unsigned int nr_spec; // Number of raw spectrum points
vec vfreq, vspec; // Same info as spectrum, but in vector<double> form
vec mesh; // Frequency mesh
vec a; // Spectral function
vec c; // Cumulative spectrum = int_{-inf}^omega a(x)dx.
void usage(std::ostream &F = std::cout) {
F << "Usage: broaden <name> <Nz> <alpha> <T> [omega0_ratio]" << std::endl;
F << std::endl;
F << "Optional parameters:" << std::endl;
F << " -h -- show help (when used as sole cmd line switch)" << std::endl;
F << " -v -- verbose" << std::endl;
F << " -m <min> -- minimal mesh frequency" << std::endl;
F << " -M <max> -- maximal mesh frequency" << std::endl;
F << " -r <ratio> -- ratio between two consecutive frequency points" << std::endl;
F << " -o -- one .dat file" << std::endl;
F << " -2 -- use the 2nd column for weight values (complex spectra)" << std::endl;
F << " -3 -- use the 3rd column for weight values (complex spectra)" << std::endl;
F << " -n -- normalization-conserving broadening kernel" << std::endl;
F << " -s -- compute weighted integrals for testing sum-rules" << std::endl;
F << " -c -- compute cumulative spectrum" << std::endl;
F << " -g -- Gaussian broadening (width alpha)" << std::endl;
F << " -f -- final Gaussian broadening pass" << std::endl;
F << " -x -- final derFD broadening pass" << std::endl;
F << " -a -- accumulation point for the mesh" << std::endl;
F << " -l -- filter out low-frequency raw data" << std::endl;
F << " -h -- filter out high-frequency raw data" << std::endl;
F << " -P -- keep only positive input frequencies" << std::endl;
F << " -N -- keep only negative input frequencies" << std::endl;
F << " -A -- output only positive frequencies" << std::endl;
F << " -B -- output only negative frequencies" << std::endl;
}
void cmd_line(int argc, char *argv[]) {
if (argc == 2 && std::string(argv[1]) == "-h") {
usage();
exit(EXIT_SUCCESS);
}
char c;
while (c = getopt(argc, argv, "vm:M:r:o23nscgf:x:a:l:h:PNAB"), c != -1) {
switch (c) {
case 'c': cumulative = true; break;
case 's': sumrules = true; break;
case 'v': verbose = true; break;
case 'm':
broaden_min = atof(optarg);
if (verbose) { std::cout << "broaden_min=" << broaden_min << std::endl; }
break;
case 'M':
broaden_max = atof(optarg);
if (verbose) { std::cout << "broaden_max=" << broaden_max << std::endl; }
break;
case 'r':
broaden_ratio = atof(optarg);
if (verbose) { std::cout << "broaden_ratio=" << broaden_ratio << std::endl; }
break;
case 'o': one = true; break;
case '2':
nrcol = 2;
col = 1;
break;
case '3':
nrcol = 2;
col = 2;
break;
case 'n': normalization = true; break;
case 'g': gaussian = true; break;
case 'f':
finalgaussian = true;
ggamma = atof(optarg);
if (verbose) { std::cout << "final Gaussian with gamma=" << ggamma << std::endl; }
break;
case 'x':
finalderfd = true;
dgamma = atof(optarg);
if (verbose) { std::cout << "final derFD with gamma=" << dgamma << std::endl; }
break;
case 'a':
accumulation = atof(optarg);
if (verbose) { std::cout << "accumulation=" << accumulation << std::endl; }
break;
case 'l':
filterlow = atof(optarg);
if (verbose) { std::cout << "filterlow=" << filterlow << std::endl; }
break;
case 'h':
filterhigh = atof(optarg);
if (verbose) { std::cout << "filterhigh=" << filterhigh << std::endl; }
break;
case 'P': keepnegative = false; break;
case 'N': keeppositive = false; break;
case 'A': meshnegative = false; break;
case 'B': meshpositive = false; break;
default: abort();
}
}
auto remaining = argc - optind; // arguments left
if (remaining != 5 && remaining != 4) {
usage();
exit(1);
}
name = std::string(argv[optind]); // Name of spectral density files
Nz = atoi(argv[optind + 1]); // Number of z-values
assert(Nz >= 1);
alpha = atof(argv[optind + 2]); // High-energy broadening parameter
assert(alpha > 0.0);
T = atof(argv[optind + 3]); // Temperature
assert(T > 0.0);
if (remaining == 5) {
omega0_ratio = atof(argv[optind + 4]); // omega0/T
assert(omega0_ratio > 0.0);
omega0 = omega0_ratio * T;
}
if (remaining == 4) {
omega0_ratio = 1e-9; // Effectively zero
omega0 = omega0_ratio * T;
}
std::cout << "Processing: " << name << std::endl;
if (verbose) { std::cout << "Nz=" << Nz << " alpha=" << alpha << " T=" << T << " omega0_ratio=" << omega0_ratio << std::endl; }
}
void check_buffer_normalisation(const std::vector<double> &buffer, const int col) {
const auto cols = 1 + nrcol;
const auto rows = buffer.size()/cols;
auto sum = 0.0;
for (auto j = 0; j < rows; j++) sum += buffer[cols * j + col];
std::cout << "Weight=" << sum << std::endl;
}
// Load all the input data.
void read_files() {
buffers.resize(Nz+1);
for (auto i = 1; i <= Nz; i++) {
buffers[i] = load(one && Nz == 1 ? name : tostring(i) + "/" + name, nrcol, verbose);
if (verbose) check_buffer_normalisation(buffers[i], col);
}
}
// Combine data from all NRG runs (z-averaging).
void merge() {
const auto cols = 1 + nrcol; // number of elements in a line
// Sum weight corresponding to equal frequencies. Map of (frequency,weight) pairs is used for this purpose.
for (auto i = 1; i <= Nz; i++) {
for (auto l = 0; l < buffers[i].size()/cols; l++) {
auto freq = buffers[i][cols * l];
auto value = buffers[i][cols * l + col];
spec[freq] += value;
}
}
nr_spec = spec.size();
if (verbose) { std::cout << nr_spec << " unique frequencies." << std::endl; }
// Normalize weight by 1/Nz, determine total weight, and store the (frequency,weight) data in the form of linear
// vectors for faster access in the ensuing calculations.
auto sum = 0.0;
for (auto & I : spec) {
const auto weight = (I.second /= Nz); // Normalize weight on the fly
const auto freq = I.first;
vfreq.push_back(freq);
vspec.push_back(weight);
sum += weight;
}
if (verbose) { std::cout << "Total weight=" << sum << std::endl; }
assert(vfreq.size() == nr_spec && vspec.size() == nr_spec);
}
void filter() {
for (auto j = 0; j < nr_spec; j++) {
if (abs(vfreq[j]) < filterlow) { vspec[j] = 0.0; }
if (abs(vfreq[j]) > filterhigh) { vspec[j] = 0.0; }
}
for (auto j = 0; j < nr_spec; j++) {
if (!keeppositive && vfreq[j] >= 0) { vspec[j] = 0.0; }
if (!keepnegative && vfreq[j] < 0) { vspec[j] = 0.0; }
}
}
void integrals_for_sumrules() {
const auto nr = vfreq.size();
auto sum = 0.0;
auto sumpos = 0.0;
auto sumneg = 0.0;
auto sumfermi = 0.0;
auto sumbose = 0.0;
auto sumfermiinv = 0.0;
auto sumboseinv = 0.0;
for (int i = 0; i < nr; i++) {
const auto omega = vfreq[i];
const auto w = vspec[i];
sum += w;
if (omega > 0.0) { sumpos += w; }
if (omega < 0.0) { sumneg += w; }
const auto f = 1 / (1 + exp(-omega / T));
const auto b = 1 / (1 - exp(-omega / T));
const auto fi = 1 / (1 + exp(+omega / T)); // fi=1-f
const auto bi = 1 / (1 - exp(+omega / T)); // bi=1-b
if (std::isfinite(f)) { sumfermi += f * w; }
if (std::isfinite(f)) { sumbose += b * w; }
if (std::isfinite(fi)) { sumfermiinv += fi * w; }
if (std::isfinite(bi)) { sumboseinv += bi * w; }
}
std::cout << "Total weight=" << sum << std::endl;
std::cout << "Positive-omega weight=" << sumpos << std::endl;
std::cout << "Negative-omega weight=" << sumneg << std::endl;
std::cout << "Integral with fermionic kernel=" << sumfermi << std::endl;
std::cout << "Integral with bosonic kernel=" << sumbose << std::endl;
std::cout << "Integral with fermionic kernel (omega -> -omega)=" << sumfermiinv << std::endl;
std::cout << "Integral with bosonic kernel (omega -> -omega)=" << sumboseinv << std::endl;
}
// Modified log-Gaussian broadening kernel. For gamma=alpha/4, the kernel is symmetric in both arguments. e is the
// energy of the spectral function point being computed. ept is the energy of point.
inline auto BR_L_orig(const double e, const double ept) {
if ((e < 0.0 && ept > 0.0) || (e > 0.0 && ept < 0.0)) return 0.0;
if (ept == 0.0) return 0.0;
const auto gamma = alpha / 4;
return exp(-sqr(log(e / ept) / alpha - gamma)) / (alpha * abs(e) * m_SQRTPI);
}
// As above, with support for a shifted accumulation point
inline auto BR_L_acc(const double e0, const double ept0) {
auto e = e0;
auto ept = ept0;
if (e > accumulation && ept > accumulation) {
const auto shift = accumulation;
e = e - shift;
ept = ept - shift;
}
if (e < -accumulation && ept < -accumulation) {
const auto shift = -accumulation; // note the sign!
e = e - shift;
ept = ept - shift;
}
if ((e < 0.0 && ept > 0.0) || (e > 0.0 && ept < 0.0)) return 0.0;
if (ept == 0.0) return 0.0;
const auto gamma = alpha / 4;
return exp(-sqr(log(e / ept) / alpha - gamma)) / (alpha * abs(e) * m_SQRTPI);
}
#define BR_L BR_L_acc
// Normalized to 1, width omega0. The kernel is symmetric in both arguments.
inline auto BR_G(const double e, const double ept) {
return exp(-sqr((e - ept) / omega0)) / (omega0 * m_SQRTPI);
}
inline auto BR_G_alpha(const double e, const double ept) {
const auto width = alpha;
return exp(-sqr((e - ept) / width)) / (width * m_SQRTPI);
}
inline auto BR_h0(const double x) {
const auto absx = abs(x);
return absx > omega0 ? 1.0 : exp(-sqr(log(absx / omega0) / alpha));
}
// normalization = true: Cross-over funciton as proposed by A. Weichselbaum et al.
// normalization = false: BR_h is a function of 'e', not of 'ept'! This breaks the normalization at finite
// temperatures. It gives nicer spectra, especially in combination with the self-energy trick.
inline auto BR_h(const double e, const double ept) {
return normalization ? BR_h0(ept) : BR_h0(e);
}
// e - output energy
// ept - energy of the delta peak (data point)
auto bfnc(const double e, const double ept) {
if (gaussian) {
return BR_G_alpha(e, ept);
} else {
const auto part_l = BR_L(e, ept);
const auto part_g = BR_G(e, ept);
const auto h = BR_h(e, ept);
assert(h >= 0.0 && h <= 1.0);
return part_l * h + part_g * (1.0 - h);
}
}
vec broaden(const vec &mesh) {
if (verbose) { std::cout << "Broadening. Number of mesh points = " << mesh.size() << std::endl; }
vec result(mesh.size());
std::transform(mesh.begin(), mesh.end(), result.begin(), [this](const auto m) {
return std::transform_reduce(vspec.begin(), vspec.end(), vfreq.begin(), 0.0, std::plus<>(),
[this,m](const auto weight, const auto freq) {
return weight * bfnc(m, freq); }); });
return result;
}
// Cumulative spectrum
void calc_cumulative(const vec &mesh, vec &c) {
const auto nr_mesh = mesh.size();
if (verbose) std::cout << "Calculating cumulative spectrum." << std::endl;
c.resize(nr_mesh);
auto sum = 0.0;
auto j = 0;
for (auto i = 0; i < nr_mesh; i++) {
const auto max_freq = mesh[i];
while (vfreq[j] < max_freq) {
sum += vspec[j];
j++;
}
c[i] = sum;
}
std::cout << "End sum=" << sum << std::endl;
}
void check_normalizations(const vec &x) {
vec y(x.size());
// For a range of delta peak positions, compute the total weight of the resulting broadened spectra.
for (auto z = 1e-10; z < 1.0; z *= 10) {
const auto nr = x.size();
for (auto i = 0; i < nr; i++) { y[i] = bfnc(x[i], z); }
std::cout << "z=" << z << " weight=" << trapez(x, y) << std::endl;
}
}
public:
Broaden(int argc, char *argv[]) {
cmd_line(argc, argv);
}
void calc() {
read_files();
merge();
filter();
if (sumrules) integrals_for_sumrules();
mesh = make_mesh(broaden_min, broaden_max, broaden_ratio, accumulation, meshpositive, meshnegative);
if (verbose) check_normalizations(mesh);
a = broaden(mesh);
if (finalgaussian) convolve(mesh, a, ggamma * T, gaussian_kernel);
if (finalderfd) convolve(mesh, a, dgamma * T, derfd_kernel);
std::cout << "Estimated weight (trapezoidal rule)=" << trapez(mesh, a) << std::endl;
save(output_filename, mesh, a, verbose);
if (cumulative) {
calc_cumulative(mesh, c);
save(cumulative_filename, mesh, c, verbose);
}
}
};
} // namespace
#endif
| 20,724
|
C++
|
.h
| 492
| 36.489837
| 132
| 0.582982
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,586
|
lambda.h
|
rokzitko_nrgljubljana/tools/nrgchain/lambda.h
|
// Discretization ODE solver for NRG
//
// ** LAMBDA class
//
// Rok Zitko, zitko@theorie.physik.uni-goettingen.de, Dec 2008
// $Id: lambda.h,v 1.1 2009/03/20 09:53:41 rok Exp $
// All things Lambda (stored to avoid recomputing).
class LAMBDA {
private:
double Lambda, logLambda{}, factorLambda{};
public:
LAMBDA() { Lambda = -1; };
LAMBDA(double in_Lambda) {
Lambda = in_Lambda;
logLambda = log(Lambda);
factorLambda = (1.0 - 1.0 / Lambda) / log(Lambda);
}
inline operator const double &() { return Lambda; }
inline double logL() { return logLambda; }
inline double factor() { return factorLambda; }
inline double power(double x) { return pow(Lambda, x); }
};
| 705
|
C++
|
.h
| 22
| 29.454545
| 62
| 0.670588
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,587
|
parser.h
|
rokzitko_nrgljubljana/tools/nrgchain/parser.h
|
// Discretization ODE solver for NRG
//
// ** Parsing of the parameter file
//
// Rok Zitko, zitko@theorie.physik.uni-goettingen.de, Dec 2008
// $Id: parser.h,v 1.1 2009/03/20 09:53:41 rok Exp $
map<string, string> params;
// Locate block [name] in a file stream. Returns true if succeessful.
bool find_block(ifstream &F, const string &s) {
string target = "[" + s + "]";
F.clear();
F.seekg(0, ios::beg);
while (F) {
string line;
getline(F, line);
if (F && target.compare(line) == 0) { break; }
}
return bool(F); // True if found.
}
// Return a parameter of type double, use default value if not found.
double P(const string &keyword, double def) {
if (params.count(keyword) == 0) return def;
return atof(params[keyword]);
}
int Pint(const string &keyword, int def) {
if (params.count(keyword) == 0) return def;
return atoi(params[keyword]);
}
string Pstr(const string &keyword, string def) {
if (params.count(keyword) == 0) return def;
return params[keyword];
}
bool Pbool(const string &keyword, bool def) {
if (params.count(keyword) == 0) return def;
return params[keyword] == "true";
}
// Parse a block of "keyword=value" lines.
void parse_block(ifstream &F) {
while (F) {
string line;
getline(F, line);
if (!F) { break; }
if (line[0] == '[') // new block, we're done!
break;
if (line.length() == 0) // skip empty lines
continue;
if (line[0] == '#') // skip comment lines
continue;
string::size_type pos_eq = line.find_first_of('=');
if (pos_eq == string::npos) // not found
continue;
string keyword = line.substr(0, pos_eq);
string value = line.substr(pos_eq + 1);
params[keyword] = value;
}
}
void parser(const string &filename) {
ifstream F;
safe_open(F, filename);
if (find_block(F, "param")) { parse_block(F); }
}
| 1,861
|
C++
|
.h
| 61
| 27.262295
| 69
| 0.647389
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,588
|
calc.h
|
rokzitko_nrgljubljana/tools/nrgchain/calc.h
|
// Discretization ODE solver for NRG
//
// ** Integration code
//
// Rok Zitko, zitko@theorie.physik.uni-goettingen.de, Dec 2008
// $Id: calc.h,v 1.1 2009/03/20 09:53:41 rok Exp $
#include <algorithm>
// Integrate a vector using the trapezoidal rule (this is consistent with
// linear interpolation between the tabulated function values). Returns the
// value of the integral over all data points.
double integrate(Vec &vec) {
Vec temp(vec); // store copy
int len = vec.size();
assert(len >= 2);
double sum = 0.0;
for (int i = 1; i < len; i++) {
double dx = vec[i].first - vec[i - 1].first;
double yavg = (temp[i].second + temp[i - 1].second) / 2.0;
sum += dx * yavg;
vec[i].second = sum; // total so far
}
vec[0].second = 0.0;
return sum;
}
// Integrate a tabulated function using the trapezoidal rule on the
// interval [a:b]. It is assued that the upper boundary 'b' is within the
// interval of tabulation, while the lower boundary 'a' is below it
// (typically a=0); to obtain the contribution from 'a' to the beginning of
// the tabulation interval, an extrapolation could be performed. [IT ISN'T !!!]
double integrate_ab(const Vec &vec, [[maybe_unused]] double a, double b) {
assert(a < b);
Vec temp(vec); // We need to make a copy to sort the table.
sort(temp.begin(), temp.end());
int len = temp.size();
double sum = 0.0;
for (int i = 1; i < len; i++) {
double x0 = temp[i - 1].first;
double x1 = temp[i].first;
double yavg = (temp[i].second + temp[i - 1].second) / 2.0;
double dx;
if (x0 < b && x1 <= b) {
dx = x1 - x0;
} else if (x0 < b && x1 > b) {
dx = b - x0;
} else {
dx = 0.0;
}
sum += dx * yavg;
}
return sum;
}
| 1,745
|
C++
|
.h
| 51
| 31.117647
| 79
| 0.629959
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,589
|
linint.h
|
rokzitko_nrgljubljana/tools/nrgchain/linint.h
|
// Discretization ODE solver for NRG
//
// ** Interpolation code
//
// Rok Zitko, zitko@theorie.physik.uni-goettingen.de, Dec 2008
// $Id: linint.h,v 1.1 2009/03/20 09:53:41 rok Exp $
// Structures for storing tabulated data, such as rho(omega).
typedef pair<double, double> Pair;
using Vec = vector<Pair>;
// Linear interpolation class
class LinInt {
protected:
Vec vec; // tabulated data
int len{}; // length of vec
int index{}; // index of the interval where last x was found
double x0{}, x1{}; // last x was in [x0:x1]
double f0{}, f1{}; // f(x0), f(x1)
double deriv{}; // (f1-f0)/(x1-x0)
bool newintegral_flag{}; // set to true when we switch to a new interval
double xmin{}, xmax{}; // lowest and highest x contained in vec
double fxmin{}, fxmax{}; // f(xmin), f(xmax)
public:
LinInt()= default;
LinInt(Vec &in_vec) : vec(in_vec) {
len = vec.size();
if (len < 2) {
cerr << "At least two data points required for interpolation." << endl;
exit(1);
}
index = -1;
newintegral_flag = false;
xmin = vec.front().first;
fxmin = vec.front().second;
xmax = vec.back().first;
fxmax = vec.back().second;
};
void findindex(double x);
double operator()(double x);
bool flag() { return newintegral_flag; }
void clear_flag() { newintegral_flag = false; }
};
// Integral of a linear interpolation class
class IntLinInt : public LinInt {
protected:
Vec intvec;
double intfxmin{}, intfxmax{}; // int f(x) @ xmin and @ xmax
public:
IntLinInt()= default;
IntLinInt(Vec &in_vec, Vec &in_intvec) : LinInt(in_vec), intvec(in_intvec) {
intfxmin = intvec.front().second;
intfxmax = intvec.back().second;
};
double operator()(double x);
};
// Serach for the interval so that x is contained in [x0:x1].
void LinInt::findindex(double x) {
if (index == -1) {
// When interpolation class object is constructed, index is
// initialized to -1. We have no prior knowledge, thus we search in
// the full interval.
for (int i = 0; i < len - 1; i++) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
} else {
if (x >= x1) {
for (int i = index + 1; i < len - 1; i++) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
} else {
for (int i = index - 1; i >= 0; i--) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
}
}
if (!(0 <= index && index < len && x0 <= x && x <= x1)) {
cerr << "findindex() error."
<< " x=" << x << " x0=" << x0 << " x1=" << x1 << " index=" << index << " len=" << len << endl;
exit(1);
}
f0 = vec[index].second; // f(x0)
f1 = vec[index + 1].second; // f(x1)
double Delta_y = f1 - f0;
double Delta_x = x1 - x0;
deriv = Delta_y / Delta_x;
}
// Return y(x) using linear interpolation between the tabulated values.
double LinInt::operator()(double x) {
// Extrapolate if necessary
if (x <= xmin) { return fxmin; }
if (x >= xmax) { return fxmax; }
if (index == -1 || !(x0 <= x && x < x1)) {
newintegral_flag = true;
findindex(x);
}
double dx = x - x0;
return f0 + deriv * dx;
}
// Return int(y(x),x) using quadratic formula in the integral [x0:x1]. The
// results of the integration is thus consistent with linear interpolation
// between the tabulated data.
double IntLinInt::operator()(double x) {
// Extrapolate if necessary. Consistent with constant function
// extrapolations in LinInt.
if (x <= xmin) { return intfxmin + fxmin * (x - xmin); }
if (x >= xmax) { return intfxmax + fxmax * (x - xmax); }
// As opposed to LinInt, here we don't set newintegral_flag! The
// integral may be considered smooth as compared to rho itself, thus the
// advantage of breaking the integration intervals into piecewise 2nd
// order polynomials for the int[rho] brings little additional benefit.
if (index == -1 || !(x0 <= x && x < x1)) { findindex(x); }
double dx = x - x0;
double int_from_0 = intvec[index].second;
return int_from_0 + dx * f0 + dx * dx * deriv / 2.0;
}
| 4,451
|
C++
|
.h
| 129
| 30.364341
| 103
| 0.574048
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,590
|
io.h
|
rokzitko_nrgljubljana/tools/nrgchain/io.h
|
// Discretization ODE solver for NRG
//
// ** Input/output code
//
// Rok Zitko, zitko@theorie.physik.uni-goettingen.de, Dec 2008
// $Id: io.h,v 1.1 2009/03/20 09:53:41 rok Exp $
inline double atof(const string &s) { return atof(s.c_str()); }
inline int atoi(const string &s) { return atoi(s.c_str()); }
void safe_open(ifstream &F, const string &filename) {
F.open(filename.c_str());
if (!F) {
cerr << "Can't open " << filename << " for reading." << endl;
exit(1);
}
}
const int PREC = 16;
void safe_open(ofstream &F, const string &filename) {
F.open(filename.c_str());
if (!F) {
cerr << "Can't open " << filename << " for writing." << endl;
exit(1);
}
F << setprecision(PREC);
}
// Get next line from stream F, skipping empty lines and comments.
string getnextline(ifstream &F) {
string line;
while (F) {
getline(F, line);
if (!F) // bail out
break;
if (line.length() == 0) // skip empty lines
continue;
if (line[0] == '#') // skip comment lines
continue;
return line;
}
return ""; // error
}
| 1,079
|
C++
|
.h
| 39
| 24.487179
| 66
| 0.619787
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,591
|
load.h
|
rokzitko_nrgljubljana/tools/nrgchain/load.h
|
// Discretization ODE solver for NRG
//
// ** Loading (and parsing) of tabulated data
#include <algorithm>
// Split a string 's' into substrings. Leading spaces are ignored.
vector<string> split_string(const string &s, unsigned int atleast = 0) {
int index = 0;
int len = s.length();
while (index < len && isspace(s[index])) { index++; }
vector<string> substrings;
while (index < len) {
string substr = "";
// Copy string until space or end of string
while (index < len && !isspace(s[index])) {
substr += s[index];
index++;
}
substrings.push_back(substr);
// Locate new substring
while (index < len && isspace(s[index])) { index++; }
}
if (substrings.size() < atleast) {
cerr << "ERROR: At least " << atleast << " columns expected." << endl;
exit(1);
}
return substrings;
}
Vec load_g(const string &filename) {
ifstream F;
safe_open(F, filename);
Vec vecg;
while (F) {
string line = getnextline(F);
if (!F) break;
vector<string> columns = split_string(line, 2);
double x = atof(columns[0]);
double y = atof(columns[1]);
vecg.push_back(make_pair(x, y));
}
if (vecg.size() == 0) {
cerr << "ERROR: No data found." << endl;
exit(1);
}
return vecg;
}
void rescalevecxy(Vec &vec, double factorx, double factory) {
const int len = vec.size();
for (int i = 0; i < len; i++) {
vec[i].first *= factorx;
vec[i].second *= factory;
}
cout << "Rescaled to the interval [ " << vec.front().first << " : " << vec.back().first << " ]" << endl;
}
// Show minimal and maximal y in a table.
void minmaxvec(Vec &vec, string name) {
double miny = DBL_MAX;
double maxy = 0;
const int len = vec.size();
for (int i = 0; i < len; i++) {
double y = vec[i].second;
if (y > maxy) { maxy = y; }
if (y < miny) { miny = y; }
}
cout << "# min[" << name << "]=" << miny;
cout << " max[" << name << "]=" << maxy << endl;
}
enum SIGN { POS, NEG }; // positive vs. negative energies
// Load positive (sign=POS) or negative (sogn=NEG) part of the
// hybridisation function into a vector.
Vec load_rho(const string &filename, SIGN sign) {
ifstream F;
safe_open(F, filename);
Vec vecrho;
while (F) {
string line = getnextline(F);
if (!F) break;
vector<string> columns = split_string(line, 2);
double x = atof(columns[0]);
double y = atof(columns[1]);
if ((sign == POS && x > 0) || (sign == NEG && x < 0)) {
// y must be positive (or zero)
if (y < 0.0) {
cerr << "ERROR: Negative y found." << endl;
exit(1);
}
// Disregard sign of x !
vecrho.push_back(make_pair(abs(x), y));
}
}
if (vecrho.size() == 0) {
cerr << "ERROR: No data found." << endl;
exit(1);
}
sort(vecrho.begin(), vecrho.end());
cout << "# " << filename << " ";
cout << "- " << (sign == POS ? "POS" : "NEG") << " ";
cout << "- interval [ " << vecrho.front().first << " : ";
cout << vecrho.back().first << " ]" << endl;
return vecrho;
}
#include <algorithm>
#include <iterator>
#include <sstream>
string tostring(const Pair &p) {
ostringstream str;
str << p.first << " " << p.second;
return str.str();
}
void save(const string &fn, const Vec &v) {
ofstream F(fn.c_str());
if (!F) {
cerr << "Failed to open " << fn << " for writing." << endl;
exit(1);
}
transform(v.begin(), v.end(), ostream_iterator<string>(F, "\n"), tostring);
}
void save(const string &fn, const vector<double> &v) {
ofstream F(fn.c_str());
if (!F) {
cerr << "Failed to open " << fn << " for writing." << endl;
exit(1);
}
F << setprecision(18);
copy(v.begin(), v.end(), ostream_iterator<double>(F, "\n"));
}
void load(const string &fn, vector<double> &v) {
ifstream F;
safe_open(F, fn);
v.clear();
while (F) {
string line = getnextline(F);
if (!F) break;
const double x = atof(line.c_str());
v.push_back(x);
}
}
| 3,979
|
C++
|
.h
| 136
| 25.529412
| 106
| 0.582851
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,592
|
kk.hpp
|
rokzitko_nrgljubljana/tools/kk/kk.hpp
|
// Kramers-Kronig transformation tool
// Part of "NRG Ljubljana"
// Rok Zitko, rok.zitko@ijs.si, 2007-2020
// The input file must consist of a table of space-separated (energy, value) pairs. The energy grid must be symmetric
// with respect to zero and the file must contain an even number of lines. Gauss-Kronrod quadrature rules are used.
// At singularity points the derivative is computed using GSL interpolation routines (cubic splines).
// NOTE about Gauss-Kronrod: The higher-order rules give better accuracy for smooth functions, while lower-order
// rules save time when the function contains local difficulties, such as discontinuities. [GSL manual] On each
// iteration the adaptive integration strategy bisects the interval with the largest error estimate. The subintervals
// and their results are stored in the memory provided by workspace. The maximum number of subintervals is given by
// limit, which may not exceed the allocated size of the workspace. [GSL manual]
#ifndef _kk_kk_hpp_
#define _kk_kk_hpp_
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <utility>
#include <cassert>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <functional>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_integration.h>
#include <unistd.h>
namespace NRG::KK {
using XYPOINT = std::pair<double, double>;
using XYFUNC = std::vector<XYPOINT>;
using DVEC = std::vector<double>;
// number of digits of precision in the generated output file
constexpr auto OUTPUT_PRECISION = 16;
// Output width for verbose mode
constexpr auto WIDTH = 24;
// Read data from stream F.
inline auto read(std::istream &F) {
XYFUNC v;
while (F) {
if (F.peek() == '#') { // skip comment lines
std::string line;
std::getline(F, line);
} else {
double x, y;
F >> x >> y;
if (F.fail()) break;
assert(std::isfinite(x) && std::isfinite(y));
v.push_back({x, y});
}
}
return v;
}
inline void write(const XYFUNC &re, std::ostream &F, const int prec = OUTPUT_PRECISION) {
F << std::setprecision(prec);
for (const auto & [x,y] : re) F << x << " " << y << std::endl;
}
inline auto x_range(const XYFUNC &l)
{
return std::make_pair(l.front().first, l.back().first);
}
// Transform a vector of pairs into a pair of vectors
template<typename S, typename T>
auto split_vector_of_pairs(const std::vector<std::pair<S,T>> &v)
{
std::vector<S> x;
x.reserve(v.size());
std::vector<T> y;
y.reserve(v.size());
for (const auto &[i,j]: v) {
x.push_back(i);
y.push_back(j);
}
return std::make_pair(x,y);
}
inline double unwrap(const double x, void *p) {
auto fp = static_cast<std::function<double(double)> *>(p);
return (*fp)(x);
}
// mode==FILES: we read from a file and write to a file
// mode==STD: we read from stdin and write to stdout. No other output is sent to stdout (errors are reported to stderr).
enum class MODE { LIBRARY, FILES, STD };
class KK {
private:
bool verbose = false;
bool veryverbose = false;
MODE mode = MODE::LIBRARY;
int len; // number of data points
DVEC Xpts, Ypts;
DVEC Xpos; // Only positive X points [grid]
double Xmin, Xmax; // Interval boundaries for the frequency grid
gsl_interp_accel *acc;
gsl_spline *spline;
gsl_integration_workspace *w;
std::ifstream Fin;
std::ofstream Fout;
inline static const size_t workspace_limit = 1000; // workspace size for integration routine
// Initialize the KK transformer
void init(XYFUNC im) { // pass by value
std::sort(im.begin(), im.end());
len = im.size();
assert(len % 2 == 0);
std::tie (Xmin, Xmax) = x_range(im);
if (mode == MODE::FILES) std::cout << "Range: [" << Xmin << " ; " << Xmax << "]" << std::endl;
if (gsl_fcmp(-Xmin, Xmax, 1.e-8) != 0) throw std::runtime_error("Only symmetric intervals are supported!");
tie(Xpts, Ypts) = split_vector_of_pairs(im);
acc = gsl_interp_accel_alloc();
// NOTE: With akime splines the might be problems with the loss of the floating point precision in the numeric
// integration step. In cubic splines instead no such difficulties seem to appear.
// gsl_interp_linear;
// gsl_interp_cspline;
const auto Interp_type = gsl_interp_akima;
spline = gsl_spline_alloc(Interp_type, len);
gsl_spline_init(spline, Xpts.data(), Ypts.data(), len);
const auto sum = gsl_spline_eval_integ(spline, Xmin, Xmax, acc);
if (!std::isfinite(sum)) throw std::runtime_error("Error: Integral is not a finite number.");
if (mode == MODE::FILES) std::cout << "Sum=" << sum << std::endl;
const auto nr = Xpts.size()/2;
for (auto i = nr; i < len; i++)
assert(gsl_fcmp(Xpts[len - i - 1], -Xpts[i], 1e-8) == 0); // Check for the symmetry of the grid
Xpos = DVEC(nr); // Xpos are positive and increasing!
std::copy(Xpts.begin() + nr, Xpts.end(), Xpos.begin());
w = gsl_integration_workspace_alloc(workspace_limit);
gsl_set_error_handler_off();
}
// Integrand. Method: we take a sum of the contributions for positive and negative x and return their sum. This is
// helpful for even integrands, since it leads to possible cancellations and better accuracy of the final result, in
// particular for small Z.
auto f(const double X, const double Z) const {
// [ f(x) - f(z) ] / (x-z)
const auto a = X != Z ? (gsl_spline_eval(spline, X, acc) - gsl_spline_eval(spline, Z, acc)) / (X - Z)
: gsl_spline_eval_deriv(spline, X, acc);
// [ f(-x) - f(z) ] / (-x-z)
const auto b = -X != Z ? (gsl_spline_eval(spline, -X, acc) - gsl_spline_eval(spline, Z, acc)) / (-X - Z)
: gsl_spline_eval_deriv(spline, -X, acc);
return a + b;
}
void handle_qag(const int status) {
if (status && veryverbose) std::cerr << "WARNING - qag error: " << status << " -- " << gsl_strerror(status) << std::endl;
}
class Wrap {
private:
gsl_function F;
std::function<double(double)> fnc;
public:
Wrap(std::function<double(double)> fnc_) : fnc(fnc_) {
F.function = &unwrap;
F.params = &fnc;
}
auto get() { return &F; }
};
void gsl_done() {
gsl_spline_free(spline);
gsl_interp_accel_free(acc);
gsl_integration_workspace_free(w);
}
void about() {
std::cout << "Kramers-Kronig transformation tool, RZ 2007-2020" << std::endl;
}
void usage() {
std::cout << "\nUsage: kk [-h] <input> <output>\n";
std::cout << "\nAlternative usage: kk -\n";
std::cout << "\nIn this mode, kk reads from STDIN and outputs to STDOUT." << std::endl;
}
void parse_cmd_line(int argc, char *argv[]) {
if (argc == 2 && strcmp(argv[1], "-h") == 0) {
usage();
exit(EXIT_SUCCESS);
}
if (argc == 3) mode = MODE::FILES;
if (argc == 2 && strcmp(argv[1], "-") == 0) mode = MODE::STD;
if (mode != MODE::STD) about();
if (mode == MODE::LIBRARY) {
usage();
exit(1);
}
if (mode == MODE::FILES) {
const std::string inputfn = argv[1];
const std::string outputfn = argv[2];
std::cout << inputfn << " --> " << outputfn << std::endl;
Fin.open(inputfn);
if (!Fin) {
std::cerr << "Can't open " << inputfn << " for reading." << std::endl;
exit(2);
}
Fout.open(outputfn);
if (!Fout) {
std::cerr << "Can't open " << outputfn << " for writing." << std::endl;
exit(2);
}
}
}
public:
// Perform the calculation for one point. Note: this is the critical part of the code, both for computational
// requirements as for the accuracy of the results. Optimise wisely!
auto calc(const double Z,
const double EPSABS = 1e-12, // numeric integration epsilon (absolute)
const double EPSREL = 1e-8) // numeric integration epsilon (relative)
{
auto F = Wrap([Z,this](double X) -> double { return f(X,Z); }); // wrap a C++ lambda for the C interface of GSL
double integral;
double integration_error;
int status = gsl_integration_qag(F.get(), // integrand
0, // lower integration boundary
Xmax, // upper integration boundary
EPSABS, EPSREL, // convergence criteria
workspace_limit, // size of workspace w
GSL_INTEG_GAUSS15, // Gauss-Kronrod rule
w, // integration workspace
&integral, // final approximation
&integration_error); // estimate of absolute error
handle_qag(status);
// Add an approximation of the (-inf,-Xmax] and [Xmax,+inf) intervals.
const auto correction = std::abs(Z) != Xmax ? -gsl_spline_eval(spline, Z, acc) * 2. * gsl_atanh(Z / Xmax) : 0.0;
const auto sum = integral + correction;
if (mode != MODE::STD && verbose) {
std::cout << std::scientific;
std::cout << std::setw(WIDTH) << Z << " t=" << std::setw(WIDTH) << integral / M_PI << " c=" << std::setw(WIDTH) << correction / M_PI << " ratio=" << std::setw(WIDTH)
<< correction / integral << std::endl;
std::cout.unsetf(std::ios_base::scientific);
}
return sum/M_PI; // Divide by pi in the definition of the KK relation!
}
// Perform the calculations for all points on a grid
auto calc(const DVEC &grid) {
XYFUNC result;
result.reserve(grid.size());
for (const auto x : grid) result.push_back({x, calc(x)});
return result;
}
// Legacy interface when kk is used as a command-line tool
KK(int argv, char *argc[]) {
parse_cmd_line(argv, argc);
const auto im = read(mode == MODE::FILES ? Fin : std::cin);
init(im);
const auto re = calc(Xpts);
write(re, mode == MODE::FILES ? Fout : std::cout);
std::cout << "KK done!" << std::endl;
}
// Modern interface when kk is used as a library
KK(XYFUNC im) {
init(im);
}
~KK() { gsl_done(); }
};
} // namespace
#endif
| 10,431
|
C++
|
.h
| 247
| 36.186235
| 172
| 0.608258
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,593
|
hilb.hpp
|
rokzitko_nrgljubljana/tools/hilb/hilb.hpp
|
// Computes \int rho(E)/(z-E) dE for given z and tabulated density of states rho(E).
//
// Legacy modes:
// Mode 1: <Re z> <Im z> as input. Returns Im part by default, or both Re and Im parts if the -G switch is used.
// Mode 2: read x and y from a file.
// Mode 3: convert imsigma/resigma.dat to imaw/reaw.dat files in the DMFT loop.
//
// Rok Zitko, rok.zitko@ijs.si, 2009-2020
#ifndef _hilb_hilb_hpp_
#define _hilb_hilb_hpp_
#include <iostream>
#include <fstream>
#include <iomanip>
#include <complex>
#include <utility>
#include <functional>
#include <vector>
#include <string>
#include <map>
#include <optional>
#include <ctime>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cfloat>
#include <unistd.h>
#include <gsl/gsl_errno.h> // GNU scientific library
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
namespace NRG::Hilb {
inline auto atof(const std::string &s) { return ::atof(s.c_str()); }
// Unwrap a lambda expression and evaluate it at x
// https://martin-ueding.de/articles/cpp-lambda-into-gsl/index.html
inline auto unwrap(const double x, void *p) {
auto fp = static_cast<std::function<double(double)> *>(p);
return (*fp)(x);
}
// Wrap around GSL integration routines
class integrator {
private:
size_t limit; // size of workspace
bool throw_on_error; // if true, integration error will trigger a hard error
gsl_integration_workspace *work = nullptr; // work space
gsl_function F; // GSL function struct for evaluation of the integrand
public:
void initF() noexcept {
F.function = &unwrap; // the actual function (lambda expression) will be provided as an argument to operator()
F.params = nullptr;
}
integrator(size_t _limit = 1000, bool _throw_on_error = false) : limit{_limit}, throw_on_error{_throw_on_error} {
work = gsl_integration_workspace_alloc(limit);
initF();
}
integrator(const integrator &X) : limit{X.limit}, throw_on_error{X.throw_on_error} {
// keep the same workspace
initF();
}
integrator(integrator &&X) : limit{X.limit}, throw_on_error{X.throw_on_error} {
work = X.work; // steal workspace
X.work = nullptr;
initF();
}
integrator &operator=(const integrator &X) {
if (this == &X) return *this;
limit = X.limit;
throw_on_error = X.throw_on_error;
// keep the same workspace
initF();
return *this;
}
integrator &operator=(integrator &&X) {
if (this == &X) return *this;
limit = X.limit;
throw_on_error = X.throw_on_error;
work = X.work; // steal workspace
X.work = nullptr;
initF();
return *this;
}
~integrator() {
if (work) { gsl_integration_workspace_free(work); }
}
/**
* Integrate function f on [a:b].
*
* @param f Function to be integrated
* @param a Lower integration range boundary
* @param b Upper integration range boundary
* @param epsabs numeric integration epsilon (absolute)
* @param epsrel numeric integration epsilon (relative)
*/
auto operator()(std::function<double(double)> f, const double a, const double b, const double epsabs = 1e-14, const double epsrel = 1e-10) {
F.params = &f;
double result, error;
const auto status = gsl_integration_qag(&F, a, b, epsabs, epsrel, limit, GSL_INTEG_GAUSS15, work, &result, &error);
if (status && std::abs(result) > epsabs && throw_on_error) throw std::runtime_error("qag error: " + std::to_string(status) + " -- " + gsl_strerror(status));
return result;
}
};
// Wrap around GSL interpolation routines
class interpolator {
private:
size_t len; // number of data points
std::vector<double> X, Y; // X and Y tables
double Xmin, Xmax; // boundary points
double oob_value; // out-of-boundary value
gsl_interp_accel *acc = nullptr; // workspace
gsl_spline *spline = nullptr; // spline data
public:
interpolator(const std::vector<double> &_X, const std::vector<double> &_Y, const double _oob_value = 0.0) : X{_X}, Y{_Y}, oob_value{_oob_value} {
assert(std::is_sorted(X.begin(), X.end()));
assert(X.size() == Y.size());
acc = gsl_interp_accel_alloc();
len = X.size();
spline = gsl_spline_alloc(gsl_interp_cspline, len);
gsl_spline_init(spline, X.data(), Y.data(), len);
Xmin = X.front();
Xmax = X.back();
}
interpolator(const interpolator &I) : len{I.len}, X{I.X}, Y{I.Y}, Xmin{I.Xmin}, Xmax{I.Xmax}, oob_value{I.oob_value} {
// keep the same accelerator workspace
if (spline) { gsl_spline_free(spline); } // we need new spline data object
spline = gsl_spline_alloc(gsl_interp_cspline, len);
gsl_spline_init(spline, X.data(), Y.data(), len);
}
interpolator(interpolator &&I) : len{I.len}, X{I.X}, Y{I.Y}, Xmin{I.Xmin}, Xmax{I.Xmax}, oob_value{I.oob_value} {
acc = I.acc; // steal workspace
I.acc = nullptr;
spline = I.spline; // steal spline data
I.spline = nullptr;
}
interpolator &operator=(const interpolator &I) {
if (this == &I) return *this;
len = I.len;
X = I.X;
Y = I.Y;
Xmin = I.Xmin;
Xmax = I.Xmax;
oob_value = I.oob_value;
// keep the same accelerator workspace
if (spline) { gsl_spline_free(spline); } // we need new spline data object
spline = gsl_spline_alloc(gsl_interp_cspline, len);
gsl_spline_init(spline, X.data(), Y.data(), len);
return *this;
}
interpolator &operator=(interpolator &&I) {
if (this == &I) return *this;
len = I.len;
X = std::move(I.X);
Y = std::move(I.Y);
Xmin = I.Xmin;
Xmax = I.Xmax;
oob_value = I.oob_value;
acc = I.acc; // steal workspace
I.acc = nullptr;
spline = I.spline; // steal spline data
I.spline = nullptr;
return *this;
}
~interpolator() {
if (spline) { gsl_spline_free(spline); }
if (acc) { gsl_interp_accel_free(acc); }
}
auto operator()(const double x) { return (Xmin <= x && x <= Xmax ? gsl_spline_eval(spline, x, acc) : oob_value); }
};
// Square of x
inline auto sqr(const double x) { return x * x; }
// Result of Integrate[(-y/(y^2 + (x - omega)^2)), {omega, -B, B}] (atg -> imQ).
inline auto imQ(const double x, const double y, const double B) { return atan((-B + x) / y) - atan((B + x) / y); }
// Result of Integrate[((x - omega)/(y^2 + (x - omega)^2)), {omega, -B, B}] (logs -> reQ).
inline auto reQ(const double x, const double y, const double B) { return (-log(sqr(B - x) + sqr(y)) + log(sqr(B + x) + sqr(y))) / 2.0; }
// Calculate the (half)bandwidth, i.e., the size B of the enclosing interval [-B:B].
inline auto bandwidth(const std::vector<double> &X) {
assert(std::is_sorted(X.begin(), X.end()));
const auto Xmin = X.front();
const auto Xmax = X.back();
return std::max(abs(Xmin), abs(Xmax));
}
/**
* Calculate the Hilbert transform of a given spectral function at fixed complex value z. This is the low-level routine, called from
* other interfaces. The general strategy is to perform a direct integration of the defining integral for cases where z has a sufficiently
* large imaginary part, otherwise the singularity is subtracted out and the calculation of the transformed integrand is performed using
* an integration-variable substitution to better handle small values.
*
* @param rhor Real part of the spectral function
* @param rhoi Imaginary part of the spectral function
* @param B Half-bandwidth, i.e., the support of the spectral function is [-B:B]
* @param z The complex value for which to evaluate the Hilbert transform
* @param lim_direct value of y=Im(z) above which rho(E)/(x+Iy-E) is directly integrated, and below which the singularity is removed
*/
template <typename FNCR, typename FNCI> auto hilbert_transform(FNCR rhor, FNCI rhoi, const double B, const std::complex<double> z, const double lim_direct = 1e-3) {
// Initialize GSL and set up the interpolation
gsl_set_error_handler_off();
integrator integr;
const auto x = real(z);
const auto y = imag(z);
// Low-level Hilbert-transform routines. calcA routine handles the case with removed singularity and
// perform the integration after a change of variables. calcB routine directly evaluates the defining
// integral of the Hilbert transform. Real and imaginary parts are determined in separate steps.
auto calcA = [&integr, x, y, B](auto f3p, auto f3m, auto d) -> double {
const double W1 = (x - B) / abs(y); // Rescaled integration limits. Only the absolute value of y matters here.
const double W2 = (B + x) / abs(y);
assert(W2 >= W1);
// Determine the integration limits depending on the values of (x,y).
double lim1down = 1.0, lim1up = -1.0, lim2down = 1.0, lim2up = -1.0;
bool inside;
if (W1 < 0 && W2 > 0) { // x within the band
const double ln1016 = -36.8; // \approx log(10^-16)
lim1down = ln1016;
lim1up = log(-W1);
lim2down = ln1016;
lim2up = log(W2);
inside = true;
} else if (W1 > 0 && W2 > 0) { // x above the band
lim2down = log(W1);
lim2up = log(W2);
inside = false;
} else if (W1 < 0 && W2 < 0) { // x below the band
lim1down = log(-W2);
lim1up = log(-W1);
inside = false;
} else { // special case: boundary points
inside = true;
}
const auto result1 = (lim1down < lim1up ? integr(f3p, lim1down, lim1up) : 0.0);
const auto result2 = (lim2down < lim2up ? integr(f3m, lim2down, lim2up) : 0.0);
const auto result3 = (inside ? d : 0.0);
return result1 + result2 + result3;
};
auto calcB = [&integr, B](auto f0) -> double { return integr(f0, -B, B); }; // direct integration
auto calc = [y, lim_direct, calcA, calcB](auto f3p, auto f3m, auto d, auto f0) { return (abs(y) < lim_direct ? calcA(f3p, f3m, d) : calcB(f0)); };
// Re part of rho(omega)/(z-omega)
auto ref0 = [x, y, &rhor, &rhoi](double omega) -> double { return (rhor(omega) * (x - omega) + rhoi(omega) * y) / (sqr(y) + sqr(x - omega)); };
// Im part of rho(omega)/(z-omega)
auto imf0 = [x,y,&rhor,&rhoi](double omega) -> double { return (rhor(omega)*(-y) + rhoi(omega)*(x-omega) )/(sqr(y)+sqr(x-omega)); };
// Re part of rho(omega)/(z-omega) with the singularity subtracted out.
auto ref1 = [x, y, &rhor, &rhoi](double omega) -> double {
return ((rhor(omega) - rhor(x)) * (x - omega) + (rhoi(omega) - rhoi(x)) * (y)) / (sqr(y) + sqr(x - omega));
};
auto ref2 = [x, y, ref1](double W) -> double { return abs(y) * ref1(abs(y) * W + x); };
auto ref3p = [ref2](double r) -> double { return ref2(exp(r)) * exp(r); };
auto ref3m = [ref2](double r) -> double { return ref2(-exp(r)) * exp(r); };
auto red = rhor(x) * reQ(x, y, B) - rhoi(x) * imQ(x, y, B);
// Im part of rho(omega)/(z-omega) with the singularity subtracted out.
auto imf1 = [x, y, &rhor, &rhoi](double omega) -> double {
return ((rhor(omega) - rhor(x)) * (-y) + (rhoi(omega) - rhoi(x)) * (x - omega)) / (sqr(y) + sqr(x - omega));
};
auto imf2 = [x, y, imf1](double W) -> double { return abs(y) * imf1(abs(y) * W + x); };
auto imf3p = [imf2](double r) -> double { return imf2(exp(r)) * exp(r); };
auto imf3m = [imf2](double r) -> double { return imf2(-exp(r)) * exp(r); };
auto imd = rhor(x) * imQ(x, y, B) + rhoi(x) * reQ(x, y, B);
return std::complex(calc(ref3p, ref3m, red, ref0), calc(imf3p, imf3m, imd, imf0));
}
/*
* @param Xpts Frequency mesh
* @param Rpts Real part of the spectral function
* @param Ipts Imaginary part of the spectral function
*/
template <typename T> auto hilbert_transform(const T &Xpts, const T &Rpts, const T &Ipts, const std::complex<double> z, const double lim_direct = 1e-3) {
interpolator rhor(Xpts, Rpts);
interpolator rhoi(Xpts, Ipts);
const double B = bandwidth(Xpts);
return hilbert_transform(rhor, rhoi, B, z, lim_direct);
}
class Hilb {
private:
double scale = 1.0; // scale factor
double B = 1.0 / scale; // half-bandwidth
double Xmin = -B;
double Xmax = +B;
const int OUTPUT_PREC = 16; // digits of output precision
bool verbose = false;
bool G = false; // G(z). Reports real and imaginary part.
std::vector<double> Xpts, Ypts, Ipts;
bool tabulated = false; // Use tabulated DOS. If false, use rho_Bethe().
auto hilbert(const double x, const double y) {
auto Bethe_fnc = [this](const auto w) { return abs(w*scale) < 1.0 ? 2.0 / M_PI * scale * sqrt(1 - sqr(w * scale)) : 0.0; };
auto zero_fnc = []([[maybe_unused]] const auto w) { return 0.0; };
const auto z = std::complex(x,y);
return tabulated ? hilbert_transform(Xpts, Ypts, Ipts, z) : hilbert_transform(Bethe_fnc, zero_fnc, B, z);
}
void do_one(const double x, const double y, std::ostream &OUT) {
if (verbose)std::cout << "z=" << std::complex(x, y) << std::endl;
const auto res = hilbert(x, y);
if (!G)
OUT << res.imag() << std::endl;
else
OUT << res << std::endl;
}
void do_stream(std::istream &F, std::ostream &OUT) {
while (F.good()) {
double label, x, y;
F >> label >> x >> y;
if (!F.fail()) {
const auto res = hilbert(x, y);
if (!G)
OUT << label << " " << res.imag() << std::endl;
else
OUT << label << " " << res.real() << " " << res.imag() << std::endl;
}
}
}
void do_hilb(std::istream &Fr, std::istream &Fi, std::ostream &Or, std::ostream &Oi) {
while (Fr.good()) {
double label1, label2, x, y;
Fr >> label1 >> x;
Fi >> label2 >> y;
if (!Fr.fail() && !Fi.fail()) {
if (abs(label1 - label2) > 1e-6) throw std::runtime_error("Frequency mismatch in do_hilb()");
// Ensure ImSigma is negative
const double CLIPPING = 1e-8;
y = std::min(y, -CLIPPING);
// The argument to calcre/im() is actually omega-Sigma(omega)
x = label1 - x;
y = -y;
const auto res = hilbert(x, y);
double resre = res.real();
double resim = res.imag();
if (!G) {
// We include the -1/pi factor here
resre /= -M_PI;
resim /= -M_PI;
} // Otherwise we are saving the Green's function G itself and no factor is required!
Or << label1 << " " << resre << std::endl;
Oi << label2 << " " << resim << std::endl;
}
}
}
auto safe_open_rd(const std::string &filename) {
std::ifstream F(filename);
if (!F) throw std::runtime_error("Error opening file " + filename + " for reading.");
return F;
}
auto safe_open_wr(const std::string &filename) {
std::ofstream F(filename);
if (!F) throw std::runtime_error("Error opening file " + filename + " for writing.");
F << std::setprecision(OUTPUT_PREC);
return F;
}
void load_dos(const std::string &filename) {
if (verbose) { std::cout << "Density of states filename: " << filename << std::endl; }
auto F = safe_open_rd(filename);
while (F) {
double x, y;
F >> x >> y;
if (!F.fail()) {
assert(std::isfinite(x) && std::isfinite(y));
Xpts.push_back(x);
Ypts.push_back(y);
Ipts.push_back(0);
}
}
}
void report_dos() {
Xmin = Xpts.front();
Xmax = Xpts.back();
assert(Xmin < Xmax);
B = std::max(std::abs(Xmin), std::abs(Xmax));
interpolator rho(Xpts, Ypts);
integrator integr;
const auto sum = integr(rho, -B, B);
if (!std::isfinite(sum)) throw std::runtime_error("Error: Integral is not a finite number.");
if (verbose)std::cout << "Sum=" << sum << std::endl;
}
void info() {
if (tabulated)
std::cout << "Xmin=" << Xmin << " Xmax=" << Xmax << std::endl;
else
std::cout << "Semicircular DOS. scale=" << scale << std::endl;
std::cout << "B=" << B << std::endl;
}
void about() {
std::cout << "# hilb -- Hilbert transformer for arbitrary density of states." << std::endl;
std::cout << "# Rok Zitko, rok.zitko@ijs.si, 2009-2020" << std::endl;
}
void usage() {
std::cout << "Usage (1): hilb [options] <x> <y>" << std::endl;
std::cout << "Usage (2): hilb [options] <inputfile>" << std::endl;
std::cout << "Usage (3): hilb [options] <resigma.dat> <imsigma.dat> <reaw.dat> <imaw.dat>" << std::endl;
std::cout << std::endl;
std::cout << "Options:" << std::endl;
std::cout << "-h show help" << std::endl;
std::cout << "-d <dos> Load the density of state data from file 'dos'" << std::endl;
std::cout << " If this option is not used, the Bethe lattice DOS is assumed." << std::endl;
std::cout << "-v Increase verbosity" << std::endl;
std::cout << "-s Rescale factor 'scale' for the DOS." << std::endl;
std::cout << "-B Half-bandwidth 'B' of the Bethe lattice DOS." << std::endl;
std::cout << " Use either -s or -B. Default is scale=B=1." << std::endl;
std::cout << "-G Compute the Green's function. hilb then returns Re[G(z)] Im[G(z)]" << std::endl;
}
void parse_param_run(int argc, char *argv[]) {
std::optional<std::ofstream> OUTFILE;
char c;
while (c = getopt(argc, argv, "hGd:vVs:B:o:"), c != -1) {
switch (c) {
case 'h': usage(); exit(EXIT_SUCCESS);
case 'G': G = true; break;
case 'd':
tabulated = true;
load_dos(optarg);
report_dos();
break;
case 'v': verbose = true; break;
case 's':
scale = atof(optarg);
B = 1 / scale;
Xmin = -B;
Xmax = +B;
if (verbose) { std::cout << "scale=" << scale << " B=" << B << std::endl; }
break;
case 'B':
B = atof(optarg);
scale = 1 / B;
Xmin = -B;
Xmax = +B;
if (verbose) { std::cout << "scale=" << scale << " B=" << B << std::endl; }
break;
case 'o':
OUTFILE = safe_open_wr(optarg);
if (verbose) { std::cout << "Output file: " << optarg << std::endl; }
break;
default: abort();
}
}
const auto remaining = argc - optind; // arguments left
const std::vector<std::string> args(argv+optind, argv+argc); // NOLINT
// Usage case 1: real (x,y) pairs from an input file.
if (remaining == 1) {
about();
if (verbose) info();
auto F = safe_open_rd(args[0]);
do_stream(F, OUTFILE ? OUTFILE.value() : std::cout);
return;
}
// Usage case 2: real a single (x,y) pair from the command line.
if (remaining == 2) {
const auto x = atof(args[0]);
const auto y = atof(args[1]);
do_one(x, y, OUTFILE ? OUTFILE.value() : std::cout);
return;
}
// Usage case 3: convert self-energy to a spectral function
if (remaining == 4) {
about();
if (verbose) info();
auto Frs = safe_open_rd(args[0]); // Re[Sigma]
auto Fis = safe_open_rd(args[1]); // Im[Sigma]
auto Fra = safe_open_wr(args[2]); // Re[G] or Re[Aw] = -1/pi Re[G]
auto Fia = safe_open_wr(args[3]); // Im[G] or Im[Aw] = -1/pi Im[G]
do_hilb(Frs, Fis, Fra, Fia);
return;
}
about();
usage();
}
public:
Hilb(int argc, char *argv[]) {
std::cout << std::setprecision(OUTPUT_PREC);
gsl_set_error_handler_off();
parse_param_run(argc, argv);
}
};
} // namespace
#endif
| 19,671
|
C++
|
.h
| 464
| 37.579741
| 164
| 0.595097
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,594
|
parser.hh
|
rokzitko_nrgljubljana/tools/matrix/parser.hh
|
/* A Bison parser, made by GNU Bison 2.5. */
/* Bison interface for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2011 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
/* Put the tokens into the symbol table, so that GDB and other debuggers
know about them. */
enum yytokentype {
STRING = 258,
NAME = 259,
NUMBER = 260,
INTEGER = 261,
UMINUS = 262,
PARSE = 263,
EXIT = 264,
GAMMAPOLCH = 265,
COEFZETA = 266,
COEFXI = 267
};
#endif
/* Tokens. */
#define STRING 258
#define NAME 259
#define NUMBER 260
#define INTEGER 261
#define UMINUS 262
#define PARSE 263
#define EXIT 264
#define GAMMAPOLCH 265
#define COEFZETA 266
#define COEFXI 267
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE
{
/* Line 2068 of yacc.c */
#line 40 "parser.yy"
double dval;
int ival;
char *str;
struct vec *dvec;
struct mat *dmat;
struct symtab *symp;
/* Line 2068 of yacc.c */
#line 85 "parser.hh"
} YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
#endif
extern YYSTYPE yylval;
| 2,571
|
C++
|
.h
| 72
| 32.305556
| 77
| 0.74056
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,595
|
matrix.h
|
rokzitko_nrgljubljana/tools/matrix/matrix.h
|
#define NSYMS 200 /* maximum number of symbols */
struct symtab {
char *name;
double (*funcptr)(double);
double value;
};
struct symtab *symlook(char *);
struct vec {
double val;
struct vec *next;
};
struct mat {
struct vec *vec;
struct mat *next;
};
| 269
|
C++
|
.h
| 15
| 15.733333
| 49
| 0.696
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,596
|
load.hpp
|
rokzitko_nrgljubljana/tools/adapt/load.hpp
|
// Discretization ODE solver for NRG
// ** Loading (and parsing) of tabulated data
#ifndef _adapt_load_hpp_
#define _adapt_load_hpp_
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <cctype>
#include <cstdlib>
namespace NRG::Adapt {
enum class Sign { POS, NEG }; // positive vs. negative energies
// Split a string 's' into substrings. Leading spaces are ignored.
inline auto split_string(const std::string &s, unsigned int atleast = 0) {
const int len = s.length();
int index = 0;
while (index < len && isspace(s[index])) { index++; }
std::vector<std::string> substrings;
while (index < len) {
std::string substr = "";
// Copy string until space or end of string
while (index < len && !isspace(s[index])) {
substr += s[index];
index++;
}
substrings.push_back(substr);
// Locate new substring
while (index < len && isspace(s[index])) { index++; }
}
if (substrings.size() < atleast)
throw std::runtime_error("At least " + std::to_string(atleast) + " columns expected.");
return substrings;
}
inline auto load_g(const std::string &filename) {
std::ifstream F;
safe_open(F, filename);
Vec vecg;
while (F) {
const auto line = getnextline(F);
if (!F) break;
const auto columns = split_string(line, 2);
vecg.emplace_back(std::make_pair(atof(columns[0]), atof(columns[1])));
}
if (vecg.size() == 0)
throw std::runtime_error("No data found.");
return vecg;
}
inline void rescalevecxy(Vec &vec, const double factorx, const double factory) {
for (int i = 0; i < vec.size(); i++) {
vec[i].first *= factorx;
vec[i].second *= factory;
}
std::cout << "Rescaled to the interval [ " << vec.front().first << " : " << vec.back().first << " ]" << std::endl;
}
// Show minimal and maximal y in a table.
inline void minmaxvec(const Vec &vec, const std::string name) {
auto miny = DBL_MAX;
auto maxy = 0;
for (int i = 0; i < vec.size(); i++) {
const auto y = vec[i].second;
if (y > maxy) { maxy = y; }
if (y < miny) { miny = y; }
}
std::cout << "# min[" << name << "]=" << miny << " max[" << name << "]=" << maxy << std::endl;
}
// Load positive (sign=POS) or negative (sogn=NEG) part of the hybridisation function into a vector.
inline Vec load_rho(const std::string &filename, const Sign sign) {
std::ifstream F;
safe_open(F, filename);
Vec vecrho;
while (F) {
const auto line = getnextline(F);
if (!F) break;
const auto columns = split_string(line, 2);
const auto x = atof(columns[0]);
const auto y = atof(columns[1]);
if ((sign == Sign::POS && x > 0) || (sign == Sign::NEG && x < 0)) {
// y must be positive (or zero)
if (y < 0.0)
throw std::runtime_error("Negative y found.");
// Disregard sign of x !
vecrho.emplace_back(std::make_pair(abs(x), y));
}
}
if (vecrho.size() == 0)
throw std::runtime_error("No data found.");
std::sort(vecrho.begin(), vecrho.end());
std::cout << "# " << filename << " ";
std::cout << "- " << (sign == Sign::POS ? "POS" : "NEG") << " ";
std::cout << "- interval [ " << vecrho.front().first << " : ";
std::cout << vecrho.back().first << " ]" << std::endl;
return vecrho;
}
inline std::string tostring(const Pair &p) {
std::ostringstream str;
str << p.first << " " << p.second;
return str.str();
}
inline void save(const std::string &fn, const Vec &v) {
std::ofstream F(fn.c_str());
if (!F)
throw std::runtime_error("Failed to open " + fn + " for writing.");
std::transform(v.begin(), v.end(), std::ostream_iterator<std::string>(F, "\n"), tostring);
}
inline void save(const std::string &fn, const std::vector<double> &v) {
std::ofstream F(fn.c_str());
if (!F)
throw std::runtime_error("Failed to open " + fn + " for writing.");
F << std::setprecision(18);
std::copy(v.begin(), v.end(), std::ostream_iterator<double>(F, "\n"));
}
inline void load(const std::string &fn, std::vector<double> &v) {
std::ifstream F;
safe_open(F, fn);
v.clear();
while (F) {
const auto line = getnextline(F);
if (!F) break;
const auto x = atof(line.c_str());
v.push_back(x);
}
}
} // namespace
#endif
| 4,267
|
C++
|
.h
| 126
| 30.539683
| 116
| 0.615124
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,597
|
calc.hpp
|
rokzitko_nrgljubljana/tools/adapt/calc.hpp
|
// Discretization ODE solver for NRG
// ** Integration code
#ifndef _adapt_calc_hpp_
#define _adapt_calc_hpp_
#include <vector>
#include <algorithm>
#include <cassert>
namespace NRG::Adapt {
// Integrate a vector using the trapezoidal rule (this is consistent with
// linear interpolation between the tabulated function values). Returns the
// value of the integral over all data points.
auto integrate(Vec &vec) {
Vec temp(vec);
const int len = vec.size();
assert(len >= 2);
auto sum = 0.0;
for (int i = 1; i < len; i++) {
const auto [x0, y0] = temp[i-1];
const auto [x1, y1] = temp[i];
const auto dx = x1-x0;
const auto yavg = (y1+y0) / 2.0;
sum += dx * yavg;
vec[i].second = sum; // total so far
}
vec[0].second = 0.0;
return sum;
}
// Integrate a tabulated function using the trapezoidal rule on the
// interval [a:b]. It is assued that the upper boundary 'b' is within the
// interval of tabulation, while the lower boundary 'a' is below it
// (typically a=0); to obtain the contribution from 'a' to the beginning of
// the tabulation interval, an extrapolation is performed. XXX: IS IT?
auto integrate_ab(const Vec &vec, [[maybe_unused]] const double a, const double b) {
assert(a < b);
Vec temp(vec); // We need to make a copy to sort the table.
std::sort(temp.begin(), temp.end());
const int len = temp.size();
auto sum = 0.0;
for (int i = 1; i < len; i++) {
const auto [x0, y0] = temp[i-1];
const auto [x1, y1] = temp[i];
const auto yavg = (y1+y0) / 2.0;
double dx;
if (x0 < b && x1 <= b) {
dx = x1 - x0;
} else if (x0 < b && x1 > b) {
dx = b - x0;
} else {
dx = 0.0;
}
sum += dx * yavg;
}
return sum;
}
} // namespace
#endif
| 1,757
|
C++
|
.h
| 56
| 28.232143
| 84
| 0.635719
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,598
|
linint.hpp
|
rokzitko_nrgljubljana/tools/adapt/linint.hpp
|
// Discretization ODE solver for NRG
// ** Interpolation code
#ifndef _adapt_linint_hpp_
#define _adapt_linint_hpp_
#include <utility>
#include <vector>
#include <stdexcept>
namespace NRG::Adapt {
// Structures for storing tabulated data, such as rho(omega).
using Pair = std::pair<double, double>;
using Vec = std::vector<Pair>;
// Linear interpolation class
class LinInt {
protected:
Vec vec; // tabulated data
int len{}; // length of vec
int index{}; // index of the interval where last x was found
double x0{}, x1{}; // last x was in [x0:x1] XXX: mutable?
double f0{}, f1{}; // f(x0), f(x1)
double deriv{}; // (f1-f0)/(x1-x0)
bool newintegral_flag{}; // set to true when we switch to a new interval
double xmin{}, xmax{}; // lowest and highest x contained in vec
double fxmin{}, fxmax{}; // f(xmin), f(xmax)
public:
LinInt() = default;
LinInt(const Vec &in_vec) : vec(in_vec) {
len = vec.size();
if (len < 2)
std::runtime_error("At least two data points required for interpolation.");
index = -1;
newintegral_flag = false;
xmin = vec.front().first;
fxmin = vec.front().second;
xmax = vec.back().first;
fxmax = vec.back().second;
}
void findindex(const double x);
double operator()(const double x);
bool flag() const { return newintegral_flag; }
void clear_flag() { newintegral_flag = false; }
};
// Integral of a linear interpolation class
class IntLinInt : public LinInt {
protected:
Vec intvec;
double intfxmin{}, intfxmax{}; // int f(x) @ xmin and @ xmax
public:
IntLinInt()= default;
IntLinInt(Vec &in_vec, Vec &in_intvec) : LinInt(in_vec), intvec(in_intvec) {
intfxmin = intvec.front().second;
intfxmax = intvec.back().second;
}
double operator()(const double x);
};
// Serach for the interval so that x is contained in [x0:x1].
void LinInt::findindex(const double x) {
if (index == -1) {
// When the interpolation object is constructed, index is initialized to -1. We have no prior
// knowledge, thus we search in the full interval.
for (int i = 0; i < len - 1; i++) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
} else {
if (x >= x1) {
for (int i = index + 1; i < len - 1; i++) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
} else {
for (int i = index - 1; i >= 0; i--) {
x0 = vec[i].first;
x1 = vec[i + 1].first;
if (x0 <= x && x <= x1) {
index = i;
break;
}
}
}
}
if (!(0 <= index && index < len && x0 <= x && x <= x1))
throw std::runtime_error("Failed to find the index.");
f0 = vec[index].second; // f(x0)
f1 = vec[index + 1].second; // f(x1)
const auto Delta_y = f1 - f0;
const auto Delta_x = x1 - x0;
deriv = Delta_y / Delta_x;
}
// Return y(x) using linear interpolation between the tabulated values.
double LinInt::operator()(const double x) {
// Extrapolate if necessary
if (x <= xmin) { return fxmin; }
if (x >= xmax) { return fxmax; }
if (index == -1 || !(x0 <= x && x < x1)) {
newintegral_flag = true;
findindex(x);
}
const auto dx = x - x0;
return f0 + deriv * dx;
}
// Return int(y(x),x) using quadratic formula in the integral [x0:x1]. The
// results of the integration is thus consistent with linear interpolation
// between the tabulated data.
double IntLinInt::operator()(const double x) {
// Extrapolate if necessary. Consistent with constant function
// extrapolations in LinInt.
if (x <= xmin) { return intfxmin + fxmin * (x - xmin); }
if (x >= xmax) { return intfxmax + fxmax * (x - xmax); }
// As opposed to LinInt, here we don't set newintegral_flag! The
// integral may be considered smooth as compared to rho itself, thus the
// advantage of breaking the integration intervals into piecewise 2nd
// order polynomials for the int[rho] brings little additional benefit.
if (index == -1 || !(x0 <= x && x < x1)) { findindex(x); }
const auto dx = x - x0;
const auto int_from_0 = intvec[index].second;
return int_from_0 + dx * f0 + dx * dx * deriv / 2.0;
}
} // namespace
#endif
| 4,447
|
C++
|
.h
| 127
| 31.094488
| 97
| 0.594802
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,599
|
io.hpp
|
rokzitko_nrgljubljana/tools/adapt/io.hpp
|
// Discretization ODE solver for NRG
// ** Input/output code
#ifndef _adapt_io_hpp_
#define _adapt_io_hpp_
#include <string>
#include <cstdlib>
#include <fstream>
#include <string>
#include <stdexcept>
namespace NRG::Adapt {
inline double atof(const std::string &s) { return std::atof(s.c_str()); }
inline int atoi(const std::string &s) { return std::atoi(s.c_str()); }
inline void safe_open(std::ifstream &F, const std::string &filename) {
F.open(filename.c_str());
if (!F)
throw std::runtime_error("Can't open " + filename + " for reading.");
}
inline void safe_open(std::ofstream &F, const std::string &filename, const int PREC = 16) {
F.open(filename.c_str());
if (!F)
throw std::runtime_error("Can't open " + filename + " for writing.");
F << std::setprecision(PREC);
}
// Get next line from stream F, skipping empty lines and comments.
inline std::string getnextline(std::ifstream &F) {
std::string line;
while (F) {
std::getline(F, line);
if (!F) // bail out
break;
if (line.length() == 0) // skip empty lines
continue;
if (line[0] == '#') // skip comment lines
continue;
return line;
}
return ""; // error
}
} // namespace
#endif
| 1,211
|
C++
|
.h
| 40
| 27.45
| 91
| 0.660069
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,600
|
parser.hpp
|
rokzitko_nrgljubljana/tools/adapt/parser.hpp
|
// Discretization ODE solver for NRG
// ** Parsing of the parameter file
#ifndef _adapt_parser_hpp_
#define _adapt_parser_hpp_
#include <map>
#include <string>
#include <iostream>
#include <fstream>
#include <stdexcept>
namespace NRG::Adapt {
// Locate block [name] in a file stream. Returns true if succeessful.
inline bool find_block(std::ifstream &F, const std::string &s) {
std::string target = "[" + s + "]";
F.clear();
F.seekg(0, std::ios::beg);
while (F) {
std::string line;
std::getline(F, line);
if (F && target.compare(line) == 0) { break; }
}
return bool(F); // True if found.
}
class Params : public std::map<std::string, std::string> {
private:
// Parse a block of "keyword=value" lines.
void parse_block(std::ifstream &F) {
while (F) {
std::string line;
std::getline(F, line);
if (!F) { break; }
if (line[0] == '[') // new block, we're done!
break;
if (line.length() == 0) // skip empty lines
continue;
if (line[0] == '#') // skip comment lines
continue;
const auto pos_eq = line.find_first_of('=');
if (pos_eq == std::string::npos) // not found
continue;
const auto keyword = line.substr(0, pos_eq);
const auto value = line.substr(pos_eq + 1);
this->insert_or_assign(keyword, value);
}
}
public:
Params(const std::string &filename) {
std::ifstream F;
safe_open(F, filename);
if (find_block(F, "param")) { parse_block(F); }
}
// Return a parameter of type double, use default value if not found.
auto P(const std::string &keyword, const double def) const {
if (this->count(keyword) == 0) return def;
return atof(this->at(keyword));
}
auto Pint(const std::string &keyword, const int def) const {
if (this->count(keyword) == 0) return def;
return atoi(this->at(keyword));
}
auto Pstr(const std::string &keyword, const std::string &def) const {
if (this->count(keyword) == 0) return def;
return this->at(keyword);
}
auto Pbool(const std::string &keyword, const bool def) const {
if (this->count(keyword) == 0) return def;
return this->at(keyword) == "true";
}
};
} // namespace
#endif
| 2,256
|
C++
|
.h
| 70
| 27.542857
| 72
| 0.614961
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,601
|
lambda.hpp
|
rokzitko_nrgljubljana/tools/adapt/lambda.hpp
|
// Discretization ODE solver for NRG
// ** LAMBDA class
#ifndef _adapt_lambda_hpp_
#define _adapt_lambda_hpp_
#include <cmath>
namespace NRG::Adapt {
// All things Lambda (stored to avoid recomputing).
class LAMBDA {
private:
double Lambda, logLambda {}, factorLambda {};
public:
LAMBDA() : Lambda(-1) {}
explicit LAMBDA(const double l) : Lambda(l), logLambda(log(l)), factorLambda((1.0-1.0/l)/log(l)) {}
inline operator const double &() const { return Lambda; }
inline double logL() const { return logLambda; }
inline double factor() const { return factorLambda; }
inline double power(double x) const { return pow(Lambda, x); }
};
} // namespace
#endif
| 683
|
C++
|
.h
| 20
| 31.7
| 102
| 0.704718
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,602
|
adapt.hpp
|
rokzitko_nrgljubljana/tools/adapt/adapt.hpp
|
#ifndef _adapt_adapt_hpp_
#define _adapt_adapt_hpp_
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cfloat>
#include <utility>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
#include <functional>
using namespace std;
using namespace std::string_literals;
#include "lambda.hpp"
#include "linint.hpp"
#include "io.hpp"
#include "parser.hpp"
#include "load.hpp"
#include "calc.hpp"
namespace NRG::Adapt {
inline void add_zero_point(Vec &v, const double small = 1e-99)
{
const auto [x0,y0] = v.front();
if (x0 > small)
v.emplace_back(std::make_pair(small, y0));
std::sort(begin(v), end(v));
}
class Adapt {
public:
Params P;
Sign sign; // positive or negative frequencies
LAMBDA Lambda; // discretization parameter
Vec vecrho; // Density of states (rho) in tabulated form
LinInt rho; // Linear interpolation object
IntLinInt intrho1, intrho2; // Integrated interpolation function objects
LinInt g;
double x; // running x
double y; // running y(x)
double max_error; // maximum error in Delta(y)
double allowed_error; // maximum error allowed
int max_subdiv; // maximum number of interval subdivisions
double xmax, xfine, output_step, dx_fine, dx_fast; // described in set_parameters()
double convergence_eps = 1e-4; // Convergence epsilon for secant method
double factor0 = 1.0 + 1e-7; // Shift of A in secant method
int max_iter = 10; // Maximum number of iterations in the secant method
double max_abs = 100.0; // Maximum value of |f(x)|.
double bandrescale = 1.0; // Rescale the input data by this scale factor
bool adapt; // If adapt=false --> g(x)=1.
bool hardgap;
double boundary;
double intA; // intA=int_0^1 rho(w) dw (trapezoidal method).
double A; // parameter in the shooting method. Initially A=intA. Equal to intA if adapt=false.
// Right-hand-side of the differential equation. y=g !
auto rhs_G(const double x, const double y) {
const auto powL = Lambda.power(2.0 - x);
return Lambda.logL() * (y - A / rho(y * powL));
}
void save(std::ostream &OUT) { OUT << x << " " << y << std::endl; }
template<typename FNC> auto rk_step(const double dx, FNC rhs)
{
const auto k1 = dx * rhs(x, y);
const auto k2 = dx * rhs(x + dx / 2.0, y + k1 / 2.0);
const auto k3 = dx * rhs(x + dx / 2.0, y + k2 / 2.0);
const auto k4 = dx * rhs(x + dx, y + k3);
return (k1 + 2 * k2 + 2 * k3 + k4) / 6.0;
}
template<typename FNC> auto heun_step(const double dx, FNC rhs)
{
const auto k1 = dx * rhs(x, y);
const auto k2 = dx * rhs(x + dx, y + k1);
return (k1 + k2) / 2.0;
}
// Perform a step of length (at most) try_dx. Returns actual dx used.
template<typename FNC> double timestep(const double try_dx, FNC rhs, bool check_f) {
double dx = try_dx; // Current step length
double dy, error;
int subdivision = 0;
// Approach: we attempt Runge-Kutta steps, reducing dx if necessary so as to avoid crossing the tabulation data
// interval boundaries (with too large steps) and to avoid too large errors.
int cnt = 0;
const int max_cnt = 2 * max_subdiv;
while (true) {
assert(std::isfinite(dx));
rho.clear_flag();
dy = rk_step(dx, rhs);
// Have we crossed the interval boundary ?
if (rho.flag()) {
if (subdivision < max_subdiv) {
subdivision++;
dx /= 2.0;
continue;
}
}
// Calculate a second-order result using Heun's formula and estimate the error in y.
const auto dy_heun = heun_step(dx, rhs);
error = abs(dy_heun - dy);
max_error = std::max(max_error, error); // update max_error
// Check the flags for k2_heun evaluation.
if (rho.flag()) {
if (subdivision < max_subdiv) {
subdivision++;
dx /= 2.0;
continue;
}
}
// Error too large? Then try again!
if (error > allowed_error) {
if (subdivision < max_subdiv) {
subdivision++;
dx /= 2.0;
continue;
}
// If we cannot subdivide, we need to give up and break from the loop!
break;
}
cnt++;
if (cnt > max_cnt)
throw std::runtime_error("Number of subdivisions exceeded.");
break; // exit loop here: the RK step is appropriate
}
if (check_f) {
// Sanity checks
const double dEdx = dy/dx - y*Lambda.logL();
const double tolerance = 1e-5;
if (dEdx >= 0.0) { // E(x) must be monotonously decreasing!
std::cerr << "WARNING: dE/dx is not negative." << std::endl;
std::cerr << " x=" << x << " y=" << y << " dEdx=" << dEdx << " dy/dx=" << dy/dx << " y*log(Lambda)=" << y*Lambda.logL() << std::endl;
}
if (dEdx > tolerance)
throw std::runtime_error("Tolerance criterium not satisfied.");
}
x += dx;
y += dy;
return dx;
}
// Integrate with step dx up to xf. max_diff_x = maximum discrepancy in x when approaching mesh points.
template<typename FNC>
void int_with_to(const double dx, const double xf, FNC rhs, const bool check_f, const double max_diff_x = 1e-10, const int max_cnt = 1000000) {
int cnt = 0;
do {
const double steplength = x+dx < xf ? dx : xf-x; // If dx is too long, steplength should be decreased to xf-x.
timestep(steplength, rhs, check_f);
cnt++;
if (cnt > max_cnt)
std::runtime_error("Number of subdivisions exceeded. max_subdiv should be increased.");
} while (abs(x-xf) > max_diff_x); // x is a global variable, updated in timestep()
}
// returns the g(xmax)/[A/rho(0)] ratio and vecg
auto shoot_g() {
const std::string filename_g = "GSOL" + std::string(sign == Sign::POS ? "" : "NEG") + ".dat";
std::ofstream OUTG;
safe_open(OUTG, filename_g);
std::cout << "# A=" << A << std::endl;
Vec vecg;
rho(1); // NECESSARY!
double dx = dx_fine; // initial step size
// Initial conditions
x = 2.0;
y = 1.0; // y=g here!
max_error = 0.0;
save(OUTG); // save x=2 data point
vecg.emplace_back(std::make_pair(x, y));
double x_st = x; // Target x for next output line
do {
x_st += output_step;
int_with_to(dx, x_st, [this](const auto x, const auto y) { return rhs_G(x, y); }, false); // rhs_G !!
save(OUTG);
vecg.emplace_back(std::make_pair(x, y));
if (x > xfine) { dx = dx_fast; }
} while (x < xmax);
const auto factor = A / rho(0);
const auto ratio = y / factor;
std::cout << "# x_last=" << x << " " << "g_last/factor=" << ratio << std::endl;
std::cout << "# eps_last=" << y * Lambda.power(2 - x) << " max_error=" << max_error << std::endl;
return std::make_pair(ratio, vecg);
}
void init_A() {
intA = integrate_ab(vecrho, 0.0, 1.0);
std::cout << "# intA=" << intA << std::endl;
A = intA;
}
Vec calc_g() {
const auto [ratio1, vecg1] = shoot_g();
if (abs(ratio1 - 1.0) < convergence_eps) // We're done
return vecg1;
// Otherwise more effort is required...
A = ratio1 > 1.0 ? A * factor0 : A / factor0;
const auto [ratio2, vecg2] = shoot_g();
if (abs(ratio2 - 1.0) < convergence_eps) // We're done
return vecg2;
// Refine using secant method
double x0 = intA;
double x1 = A;
double y0 = ratio1 - 1.0;
double y1 = ratio2 - 1.0;
int iter = 0;
double ynew;
do {
const auto xnew = x1 - (x1 - x0) / (y1 - y0) * y1;
A = xnew;
const auto [rationew,vecg] = shoot_g();
ynew = rationew - 1.0;
if (abs(rationew-1) < convergence_eps)
return vecg;
// Shift
x0 = x1;
y0 = y1;
x1 = xnew;
y1 = ynew;
iter++;
} while (iter < max_iter);
throw std::runtime_error("Secant method failed to converge in " + std::to_string(max_iter) + " steps.");
}
// Rescaling of omega for excluding finite intervals around omega=0. The new accumulation point is determined by
// the variable 'boundary'.
auto rescale(const double omega) { return (1.0 - boundary) * omega + boundary; }
// eps(x) = D g(x) Lambda^(2-x) for x>2.
auto eps(const double x) {
const auto gx = adapt ? g(x) : 1.0;
double epsilon = x <= 2.0 ? 1.0 : gx * Lambda.power(2.0-x);
if (hardgap) { epsilon = rescale(epsilon); }
return epsilon;
}
// Eps(x) = D f(x) Lambda^(2-x)
inline auto Eps(const double x, const double f) {
assert(x >= 1 && f > 0);
return f * Lambda.power(2.0-x);
}
// Right-hand-side of the differential equation. y=f !
auto rhs_F(const double x, const double y) {
assert(std::isfinite(x));
assert(std::isfinite(y));
const double term1 = Lambda.logL() * y;
const double integral = intrho2(eps(x)) - intrho1(eps(x + 1));
const double powL = Lambda.power(2.0 - x);
const double denom = powL * rho(y * powL);
double term2 = integral / denom;
if (denom == 0.0) {
std::cout << "# Warning: denom=0 with integral=" << integral << " at x=" << x << std::endl;
std::cout << "# (denom=0 may arise from zeros in the hybridisation function)" << std::endl;
term2 = 0.0;
}
assert(std::isfinite(term2));
return term1 - term2;
}
void load_init_rho() {
std::string rhofn = P.Pstr("dos", "Delta.dat");
vecrho = load_rho(rhofn, sign);
add_zero_point(vecrho);
rescalevecxy(vecrho, 1.0/bandrescale, bandrescale);
minmaxvec(vecrho, "rho");
rho = LinInt(vecrho);
std::cout << "# rho(0)=" << rho(0) << " rho(1)=" << rho(1) << std::endl;
Vec vecintrho(vecrho);
integrate(vecintrho);
intrho1 = IntLinInt(vecrho, vecintrho);
intrho2 = intrho1; // trick: two objects, one at upper, another at lower boundary. significant performance improvement!
}
void report_parameters() {
std::cout << "# ++ " << (adapt ? "ADAPTIVE" : "FIXED-GRID") << std::endl;
std::cout << "# Lambda=" << Lambda;
std::cout << " bandrescale=" << bandrescale;
std::cout << " xmax=" << xmax;
std::cout << " xfine=" << xfine;
std::cout << " output_step=" << output_step;
std::cout << " dx_fine=" << dx_fine << " dx_fast=" << dx_fast;
std::cout << std::endl;
std::cout << "# allowed_error=" << allowed_error;
std::cout << " max_subdiv=" << max_subdiv;
std::cout << " max_abs=" << max_abs;
std::cout << std::endl;
}
void set_parameters(const int PREC = 16) {
std::cout << std::setprecision(PREC);
Lambda = LAMBDA(P.P("Lambda", 2.0));
assert(Lambda > 1.0);
adapt = P.Pbool("adapt", false); // Enable adaptable g(x)? Default is false!!
hardgap = P.Pbool("hardgap", false); // Exclude an interval around omega=0 ?
boundary = P.P("boundary", 0.0); // The boundary of the exclusion interval.
bandrescale = P.P("bandrescale", 1.0); // band rescaling parameter
xmax = P.P("xmax", 30); // Integrate over [1..xmax]
assert(xmax > 1);
xfine = P.P("xfine", 5); // Fine stepsize integral [1..xfine]
assert(xfine > 1);
output_step = P.P("outputstep", 1.0 / 64.0); // Stepsize for output file
assert(output_step <= 1.0);
dx_fine = P.P("dx_fine", 1e-5); // Integration stepsize in [1..xfine]
dx_fast = P.P("dx_fast", 1e-4); // Integration stepsize in [xfine..xmax]
allowed_error = P.P("allowed_error", 1e-10); // error control for adaptable stepsize
max_subdiv = P.Pint("max_subdiv", 10); // maximum nr of integ. step subdivisions
assert(dx_fine * pow(0.5, max_subdiv) > DBL_EPSILON);
max_abs = P.P("max_abs", 100.0); // Maximal |f(x)|
assert(max_abs > 0.0);
convergence_eps = P.P("secant_eps", 1e-4);
factor0 = 1.0 + P.P("secant_factor", 1e-7);
max_iter = P.Pint("secant_max_iter", 10);
}
Adapt(const Params &P, const Sign &sign) : P(P), sign(sign) {
set_parameters();
report_parameters();
}
auto g_fn(const Sign &sign) { return "GSOL" + (sign == Sign::POS ? ""s : "NEG"s) + ".dat"; }
auto f_fn(const Sign &sign) { return "FSOL" + (sign == Sign::POS ? ""s : "NEG"s) + ".dat"; }
void load_or_calc_g() {
const auto vecg = P.Pbool("loadg", false) ? load_g(g_fn(sign)) : calc_g();
minmaxvec(vecg, "g");
g = LinInt(vecg);
}
void report() {
const double factor = Lambda.factor() * A / rho(0);
std::cout << "# x_last=" << x << std::endl;
std::cout << "# f_last=" << y << " [f_last/factor=" << y / factor << "]" << std::endl;
std::cout << "# eps_last=" << eps(x) << " (smallest energy point considered [input])" << std::endl;
std::cout << "# Eps_last=" << y * Lambda.power(2 - x) << " (smallest energy scale obtained [output])" << std::endl;
std::cout << "# max_error=" << max_error << " (maximum integration error)" << std::endl;
}
void calc_f() {
std::ofstream OUTF;
safe_open(OUTF, f_fn(sign));
rho(1); // NECESSARY!
double dx = dx_fine; // initial step size
// Initial conditions
x = 1.0;
y = 1.0 / Lambda; // y=f here!
max_error = 0.0;
save(OUTF); // save x=1 data point
double x_st = x; // Target x for next output line
do {
x_st += output_step;
int_with_to(dx, x_st, [this](const auto x, const auto y){ return rhs_F(x, y); }, true); // rhs_F !!
save(OUTF);
if (x > xfine) { dx = dx_fast; }
if (abs(y) > max_abs) {
std::cout<< "***** y=" << y << " |y|>max_abs=" << max_abs << std::endl;
std::cout<< "***** Terminating!" << std::endl;
}
} while (x < xmax && abs(y) <= max_abs);
}
void run() {
load_init_rho();
init_A();
if (adapt) { load_or_calc_g(); }
calc_f();
report();
}
};
} // namespace
#endif
| 14,477
|
C++
|
.h
| 352
| 35.357955
| 146
| 0.561389
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,603
|
binavg.hpp
|
rokzitko_nrgljubljana/tools/binavg/binavg.hpp
|
#ifndef _binavg_binavg_hpp_
#define _binavg_binavg_hpp_
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cfloat>
#include <utility>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <unistd.h> // getopt
namespace NRG::BinAvg {
inline std::string tostring(const int i) {
std::ostringstream S;
S << i;
return S.str();
}
class BinAvg {
private:
bool verbose = false; // output verbosity level
bool one = false; // For Nz=1, no subdir.
int nrcol = 1; // Number of columns
int col = 1; // Which y column are we interested in?
std::string name; // filename of binary files containing the raw data
int Nz; // Number of spectra (1..Nz)
double **buffers; // binary data buffers
int *sizes; // sizes of buffers
typedef std::map<double, double> mapdd;
using vec = std::vector<double>;
mapdd spec; // Spectrum
unsigned int nr_spec; // Number of raw spectrum points
vec vfreq, vspec; // Same info as spectrum, but in vector<double> form
void usage(std::ostream &F = std::cout) {
F << "Usage: binavg <name> <Nz>" << std::endl;
F << std::endl;
F << "Optional parameters:" << std::endl;
F << " -h -- show help" << std::endl;
F << " -v -- verbose" << std::endl;
F << " -o -- one .dat file" << std::endl;
F << " -2 -- use the 2nd column for weight values (complex spectra)" << std::endl;
F << " -3 -- use the 3rd column for weight values (complex spectra)" << std::endl;
}
void cmd_line(int argc, char *argv[]) {
char c;
while (c = getopt(argc, argv, "hvo23"), c != -1) {
switch (c) {
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'v': verbose = true; break;
case 'o': one = true; break;
case '2':
nrcol = 2;
col = 1;
break;
case '3':
nrcol = 2;
col = 2;
break;
default: abort();
}
}
int remaining = argc - optind; // arguments left
if (remaining != 2) {
usage();
exit(1);
}
name = std::string(argv[optind]); // Name of spectral density files
Nz = atoi(argv[optind + 1]); // Number of z-values
assert(Nz >= 1);
std::cout << "Processing: " << name << std::endl;
std::cout << "Nz=" << Nz << std::endl;
}
// Load a file containing binary representation of raw spectral density. The grid is not assumed to be uniform.
void load(const int i) {
// i-th z-value defines the name of the directory where the results of the NRG calculation are contained.
std::string filename = one && Nz == 1 ? name : tostring(i) + "/" + name;
std::ifstream f(filename.c_str(), std::ios::in | std::ios::binary);
if (!f.good() || f.eof() || !f.is_open()) {
std::cerr << "Error opening file " << filename << std::endl;
exit(1);
}
if (verbose) { std::cout << "Reading " << filename << std::endl; }
const int rows = 1 + nrcol; // number of elements in a line
// Determine the number of records
f.seekg(0, std::ios::beg);
const auto begin_pos = f.tellg();
f.seekg(0, std::ios::end);
const auto end_pos = f.tellg();
const long len = end_pos - begin_pos;
assert(len % (rows * sizeof(double)) == 0);
const int nr = len / (rows * sizeof(double)); // number of lines
if (verbose) { std::cout << "len=" << len << " nr=" << nr << " data points" << std::endl; }
// Allocate the read buffer. The data will be kept in memory for the duration of the calculation!
auto *buffer = new double[rows * nr];
f.seekg(0, std::ios::beg); // Return to the beginning of the file.
f.read((char *)buffer, len);
if (f.fail()) {
std::cerr << "Error reading " << filename << std::endl;
exit(1);
}
f.close();
// Keep record of the the buffer and its size.
buffers[i] = buffer;
sizes[i] = nr;
if (verbose) {
// Check normalization.
double sum = 0.0;
for (int j = 0; j < nr; j++) sum += buffer[rows * j + col];
std::cout << "Weight=" << sum << std::endl;
}
}
// Load all the input data.
void read_files() {
buffers = new double *[Nz + 1];
sizes = new int[Nz + 1];
for (int i = 1; i <= Nz; i++) { load(i); }
}
// Combine data from all NRG runs (z-averaging).
void merge() {
const int rows = 1 + nrcol; // number of elements in a line
// Sum weight corresponding to equal frequencies. Map of (frequency,weight) pairs is used for this purpose.
for (int i = 1; i <= Nz; i++) {
for (int l = 0; l < sizes[i]; l++) {
double &freq = buffers[i][rows * l];
double &value = buffers[i][rows * l + col];
auto I = spec.find(freq);
if (I == spec.end()) {
spec[freq] = value;
} else {
I->second += value;
}
}
}
nr_spec = spec.size();
if (verbose) { std::cout << nr_spec << " unique frequencies." << std::endl; }
// Normalize weight by 1/Nz, determine total weight, and store the (frequency,weight) data in the form of linear
// vectors for faster access in the ensuing calculations.
double sum = 0.0;
for (auto & I : spec) {
const double weight = (I.second /= Nz); // Normalize weight on the fly
const double freq = I.first;
vfreq.push_back(freq);
vspec.push_back(weight);
sum += weight;
}
if (verbose) { std::cout << "Total weight=" << sum << std::endl; }
assert(vfreq.size() == nr_spec && vspec.size() == nr_spec);
}
// Save a map of (double,double) pairs to a BINARY file.
void save_binary(const std::string filename, const vec &x, const vec &y, const int SAVE_PREC = 18) {
if (verbose) { std::cout << "Saving " << filename << std::endl; }
std::ofstream F(filename.c_str(), std::ios::out | std::ios::binary);
if (!F) {
std::cerr << "Failed to open " << filename << " for writing." << std::endl;
exit(1);
}
F << std::setprecision(SAVE_PREC);
assert(x.size() == y.size());
unsigned int nr = x.size();
for (unsigned int i = 0; i < nr; i++) {
const double vx = x[i];
F.write((char *)&vx, sizeof(double));
const double vy = y[i];
F.write((char *)&vy, sizeof(double));
}
}
public:
BinAvg(int argc, char *argv[]) {
cmd_line(argc, argv);
}
void calc() {
read_files();
merge();
save_binary(one ? "spec.bin" : name, vfreq, vspec);
}
};
} // namespace
#endif
| 6,721
|
C++
|
.h
| 184
| 30.744565
| 117
| 0.565598
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,604
|
resample.hpp
|
rokzitko_nrgljubljana/tools/resample/resample.hpp
|
// Resample a tabulated function on a new X grid using smooth interpolation functions (GSL).
// Rok Zitko, rok.zitko@ijs.si, May 2014
// The input file must consist of a table of space-separated (energy,
// value) pairs. Gauss-Kronrod quadrature rules are used.
// CHANGE LOG
// 22.5.2014 - first version
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <utility>
#include <cassert>
#include <string>
using namespace std::string_literals;
#include <cstring>
#include <algorithm>
#include <optional>
#include <memory>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_integration.h>
#include <unistd.h>
#include <getopt.h>
#include "misc.hpp"
#include "basicio.hpp"
using namespace NRG;
namespace NRG::Resample{
struct gsl_acc_del{
void operator()(gsl_interp_accel* acc) {
if (acc) gsl_interp_accel_free(acc);
}
};
struct gsl_spline_del{
void operator()(gsl_spline* spline){
if(spline) gsl_spline_free(spline);
}
};
template <typename T>
class Resample
{
private:
// Dump additional information to stdout?
std::string inputfn; // Filename for input data
std::string gridfn; // Filename for a new X grid
std::optional<std::string> outputfn; // Filename for resampled data. May be the same as gridfn.
bool verbose = false; // enable with -v
int output_precision = 16; // number of digits of precision in the output
std::unique_ptr<gsl_interp_accel, gsl_acc_del> acc;
std::unique_ptr<gsl_spline, gsl_spline_del> spline;
std::vector<std::pair<T, T>> grid;
void usage()
{
std::cout << "\nUsage: resample [-h] [-v] <input> <grid> <output>" << std::endl;
std::cout << "-v: toggle verbose messages (now=" << verbose << ")" << std::endl;
}
void parse_param(int argc, char *argv[])
{
char c;
while (c = getopt(argc, argv, "hvp:"), c != -1)
{
switch (c)
{
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'v': verbose = true; break;
case 'p': output_precision = atoi(optarg); break;
default: throw std::runtime_error("Unknown argument "s + c);
}
}
int remaining = argc - optind;
if (remaining != 3) {
about();
usage();
exit(1);
}
inputfn = std::string(argv[optind++]);
gridfn = std::string(argv[optind++]);
outputfn = std::string(argv[optind++]);
}
void about()
{
std::cout << "Resampling tool" << std::endl;
#ifdef __TIMESTAMP__
std::cout << "Timestamp: " << __TIMESTAMP__ << std::endl;
#endif
std::cout << "Compiled on " << __DATE__ << " at " << __TIME__ << std::endl;
}
public:
Resample(int argv, char *argc[])
{
parse_param(argv, argc);
if (verbose) about();
std::vector<std::pair<T, T>> f = readtable<T,T>(inputfn, verbose);
grid = readtable<T,T>(gridfn, verbose);
init(f);
}
Resample(std::string inputfn, std::string gridfn, std::optional<std::string> outputfn = std::nullopt, bool verbose = false, int output_precision = 16):
inputfn(inputfn), gridfn(gridfn), outputfn(outputfn), verbose(verbose), output_precision(output_precision)
{
std::vector<std::pair<T, T>> f = readtable<T,T>(inputfn, verbose);
grid = readtable<T,T>(gridfn, verbose);
init(f);
}
Resample(std::vector<std::pair<T, T>> f, std::vector<std::pair<T, T>> grid, std::optional<std::string> outputfn = std::nullopt, bool verbose = false, int output_precision = 16):
grid(grid), outputfn(outputfn), verbose(verbose), output_precision(output_precision)
{
init(f);
}
std::optional<std::vector<std::pair<T, T>>> run()
{
resample(grid);
if (outputfn)
{
writetable(grid, *outputfn, output_precision);
return std::nullopt;
}
else return grid;
}
void init(std::vector<std::pair<T, T>> &im)
{
int len; // number of data points
T Xmin, Xmax; // the interval boundaries
std::vector<T> Xpts, Ypts;
std::sort(im.begin(), im.end());
len = im.size();
Xmin = im.front().first;
Xmax = im.back().first;
if (verbose) std::cout << "Range: [" << Xmin << " ; " << Xmax << "]" << std::endl;
std::transform(im.begin(), im.end(), std::back_inserter(Xpts), [] (const auto& pair){return pair.first;});
std::transform(im.begin(), im.end(), std::back_inserter(Ypts), [] (const auto& pair){return pair.second;});
acc.reset(gsl_interp_accel_alloc());
const gsl_interp_type *Interp_type = gsl_interp_akima;
spline.reset(gsl_spline_alloc(Interp_type, len));
gsl_spline_init(spline.get(), Xpts.data(), Ypts.data(), len);
gsl_set_error_handler_off();
}
void resample(std::vector<std::pair<T, T>> &grid)
{
for (auto & i : grid) i.second = gsl_spline_eval(spline.get(), i.first, acc.get());
}
};
} //namespace
| 5,573
|
C++
|
.h
| 143
| 29.769231
| 185
| 0.552203
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,605
|
unitary.hpp
|
rokzitko_nrgljubljana/tools/unitary/unitary.hpp
|
// Unitary transformation tool
// Rotates matrices by performing unitary transformations
// Rok Zitko, rok.zitko@ijs.si, 2009-2020
#ifndef _unitary_unitary_hpp_
#define _unitary_unitary_hpp_
#include <iostream>
#include <fstream>
#include <iomanip>
#include <utility>
#include <vector>
#include <string>
using namespace std::string_literals;
#include <map>
#include <ctime>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cfloat>
#include <cstdint>
#include <unistd.h>
#include <basicio.hpp>
#include <io.hpp>
#include <numerics.hpp>
namespace NRG::Unitary {
class Unitary {
private:
bool quiet = false;
bool verbose = false;
bool veryverbose = false;
bool transpose_first = false;
bool transpose_last = false;
double scale_factor = 1.0;
double chop_tol = 1e-14;
bool input_ac_bin = false;
std::optional<std::string> output_filename;
void usage(std::ostream &F = std::cout) {
F << "Usage: unitary [-h] [-b | -B] [-qvV] [-tl] [-s scale] [-o output_fn] [-c chop_tol] <A> <B> <C>" << std::endl;
}
void parse_param(int argc, char *argv[]) {
char c;
while (c = getopt(argc, argv, "hbBqvVtls:o:c:"), c != -1) {
switch (c) {
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'b': input_ac_bin = false; break;
case 'B': input_ac_bin = true; break;
case 'q': quiet = true; break;
case 'v': verbose = true; break;
case 'V': veryverbose = true; break;
case 't': transpose_first = true; break;
case 'l': transpose_last = true; break;
case 's': scale_factor = atof(optarg); break;
case 'o': output_filename = std::string(optarg); break;
case 'c': chop_tol = atof(optarg); break;
default: throw std::runtime_error("Unknown argument "s + c);
}
}
}
void about() {
if (!quiet) {
std::cout << "# unitary -- command line unitary transformation tool" << std::endl;
std::cout << "# Rok Zitko, rok.zitko@ijs.si, 2009-2020" << std::endl;
}
}
public:
template<real_matrix RM>
void run(const RM &A_, const RM &B, const RM &C_) {
auto A = transpose_first ? NRG::trans(A_) : A_;
auto C = transpose_last ? NRG::trans(C_) : C_;
assert(size2(A) == size1(B));
assert(size2(B) == size1(C));
auto N = matrix_prod<double>(B, C); // XXX: use rotate() instead?
auto M = matrix_prod<double>(A, N);
if (scale_factor != 1.0) M = scale_factor * M;
if (veryverbose) std::cout << "M=" << M << std::endl;
if (output_filename) save_matrix(output_filename.value(), M, verbose, chop_tol);
}
void run(const std::string &fnA, const std::string &fnB, const std::string &fnC) {
auto A = read_matrix(fnA, input_ac_bin, verbose, veryverbose);
const auto B = read_matrix(fnB, false);
auto C = read_matrix(fnC, input_ac_bin, verbose, veryverbose);
run(A, B, C);
}
void run(int argc, char *argv[]) {
const auto remaining = argc - optind; // arguments left after switch parsing
if (remaining == 3) {
const std::string fnA = argv[optind];
const std::string fnB = argv[optind+1];
const std::string fnC = argv[optind+2];
run(fnA, fnB, fnC);
} else {
usage();
}
}
Unitary(int argc, char *argv[]) {
parse_param(argc, argv);
about();
}
};
} // namespace
#endif
| 3,442
|
C++
|
.h
| 102
| 28.901961
| 120
| 0.60779
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,606
|
h5write.hpp
|
rokzitko_nrgljubljana/tools/h5write/h5write.hpp
|
#ifndef _h5write_h5write_hpp_
#define _h5write_h5write_hpp_
#include <iostream>
#include <traits.hpp>
#include <basicio.hpp>
#include <io.hpp>
#include <misc.hpp>
#include <h5.hpp>
namespace NRG::H5Write {
using namespace NRG;
void h5_copy_matrix_from_file(H5Easy::File &file, const std::string &path, const std::string &input_filename) {
const auto M = read_matrix_text(generate_matrix<double>, input_filename);
h5_dump_matrix(file, path, M);
}
class H5Write {
private:
bool truncate = false;
bool scalar = false;
std::string filename_h5;
std::string ds_path;
std::string input;
std::unique_ptr<H5Easy::File> h5;
void usage() {
std::cout << "\nUsage: h5write [-h] [-s] [-t] <hdf5 file> <path> <input_file|scalar>\n";
}
void parse_cmd_line(int argc, char *argv[]) {
char c;
while (c = getopt(argc, argv, "hst"), c != -1) {
switch (c) {
case 'h': usage(); exit(EXIT_SUCCESS);
case 's': scalar = true; break;
case 't': truncate = true; break;
default:
usage();
throw std::runtime_error("Invalid input switch.");
}
}
const auto remaining = argc-optind;
if (remaining != 3) {
usage();
throw std::runtime_error("Invalid number of parameters.");
}
const std::vector<std::string> args(argv+optind, argv+argc);
filename_h5 = args[0];
ds_path = args[1];
input = args[2];
}
public:
H5Write(int argc, char *argv[]) {
parse_cmd_line(argc, argv);
}
void run() {
h5 = std::make_unique<H5Easy::File>(filename_h5, truncate ? H5Easy::File::Truncate : H5Easy::File::ReadWrite);
if (scalar)
h5_dump_scalar(*h5, ds_path, atof(input));
else
h5_copy_matrix_from_file(*h5, ds_path, input);
}
};
} // namespace
#endif
| 1,818
|
C++
|
.h
| 61
| 25.131148
| 115
| 0.625215
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,609
|
workdir.hpp
|
rokzitko_nrgljubljana/c++/workdir.hpp
|
#ifndef _workdir_hpp_
#define _workdir_hpp_
#include <memory>
#include <string>
#include <optional>
#include <cstring> // strncpy
#include <cstdlib> // mkdtemp, getenv
#include "portabil.hpp" // remove(std::string)
#include <cstdio> // C remove()
namespace NRG {
using namespace std::string_literals;
inline const auto default_workdir{"."s};
// create a unique directory
inline auto dtemp(const std::string &path, const std::string &pattern = "/XXXXXX"s)
{
const auto workdir_template = path + pattern;
const auto len = workdir_template.length()+1;
auto x = std::make_unique<char[]>(len);
strncpy(x.get(), workdir_template.c_str(), len);
char *w = mkdtemp(x.get());
return w ? std::optional<std::string>(w) : std::nullopt;
}
// Note: This will remove a directory only if it is empty!
inline int remove(const std::string &filename) { return std::remove(filename.c_str()); }
class Workdir {
private:
const std::string workdir {};
bool remove_at_exit {true}; // XXX: tie to P.removefiles?
public:
explicit Workdir(const std::string &dir, const bool quiet = false) : workdir(dtemp(dir).value_or(default_workdir)) {
if (!quiet) std::cout << "workdir=" << workdir << std::endl << std::endl;
}
explicit Workdir() : Workdir(default_workdir, true) {} // defaulted version (for testing purposes)
Workdir(const Workdir &) = delete;
Workdir(Workdir &&) = delete;
Workdir & operator=(const Workdir &) = delete;
Workdir & operator=(Workdir &&) = delete;
[[nodiscard]] auto get() const { return workdir; }
[[nodiscard]] auto rhofn(const size_t N, const std::string &filename) const { // density matrix files
return workdir + "/" + filename + std::to_string(N);
}
[[nodiscard]] auto unitaryfn(const size_t N, const std::string &filename = "unitary"s) const { // eigenstates files
return workdir + "/" + filename + std::to_string(N);
}
void remove_workdir() {
if (workdir != "") NRG::remove(workdir);
}
~Workdir() {
if (remove_at_exit) remove_workdir();
}
};
inline auto set_workdir(const std::string &dir_) {
std::string dir = default_workdir;
if (const char *env_w = std::getenv("NRG_WORKDIR")) dir = env_w;
if (!dir_.empty()) dir = dir_;
return std::make_unique<Workdir>(dir);
}
} // namespace
#endif
| 2,296
|
C++
|
.h
| 59
| 36.084746
| 119
| 0.678042
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,610
|
traits.hpp
|
rokzitko_nrgljubljana/c++/traits.hpp
|
// traits.hpp - data types definitions
// Copyright (C) 2009-2024 Rok Zitko
#ifndef _traits_hpp_
#define _traits_hpp_
#include <concepts>
#include <complex>
#include <type_traits> // is_same_v, is_floating_point_v
#include <boost/serialization/vector.hpp> // for the plugin!
#define EIGEN_DENSEBASE_PLUGIN "EigenBoostSerialization.h"
#define EIGEN_USE_BLAS
#include <Eigen/Dense>
namespace NRG {
template <typename T> concept floating_point = std::is_floating_point_v<T>;
template <typename T> struct is_complex : std::false_type {};
template <floating_point T> struct is_complex<std::complex<T>> : std::true_type {};
template <typename T> concept scalar = floating_point<T> || is_complex<T>::value;
template <scalar S> using EigenMatrix = Eigen::Matrix<S, -1, -1, Eigen::RowMajor>;
template <scalar S> using EigenVector = Eigen::Matrix<S, -1, 1>;
template <scalar S> constexpr auto is_row_ordered([[maybe_unused]] const EigenMatrix<S> &m) { return true; }
template <scalar S> size_t size1(const EigenMatrix<S> &m) { return m.rows(); } // keep size_t here!
template <scalar S> size_t size2(const EigenMatrix<S> &m) { return m.cols(); }
template <scalar S> auto size1(const Eigen::Block<EigenMatrix<S>> &m) { return m.rows(); }
template <scalar S> auto size2(const Eigen::Block<EigenMatrix<S>> &m) { return m.cols(); }
template <scalar S> auto size1(const Eigen::Block<const EigenMatrix<S>> &m) { return m.rows(); }
template <scalar S> auto size2(const Eigen::Block<const EigenMatrix<S>> &m) { return m.cols(); }
template <typename T>
concept matrix = requires(T a, T b, size_t i, size_t j) {
{ size1(a) }; // -> std::convertible_to<std::size_t>;
{ size2(a) }; // -> std::convertible_to<std::size_t>;
{ a(i,j) };
{ a = b };
{ a.swap(b) };
typename T::value_type;
};
template <typename T> concept real_matrix = matrix<T> && floating_point<typename T::value_type>;
template <typename T> concept complex_matrix = matrix<T> && is_complex<typename T::value_type>::value;
template <typename T> struct is_Eigen_object : std::false_type {};
template <scalar S> struct is_Eigen_object<EigenMatrix<S>> : std::true_type {};
template <scalar S> struct is_Eigen_object<Eigen::Block<const EigenMatrix<S>>> : std::true_type {};
template <typename T> concept Eigen_matrix = matrix<T> && is_Eigen_object<T>::value;
template <typename T> concept real_Eigen_matrix = real_matrix<T> && is_Eigen_object<T>::value;
template <typename T> concept complex_Eigen_matrix = complex_matrix<T> && is_Eigen_object<T>::value;
template <typename T>
concept vector = requires(T a, size_t i) {
{ a.size() };
{ a[i] };
{ a.data() };
{ a.begin() };
{ a.end() };
{ a.resize(i) };
typename T::value_type;
};
// We encapsulate the differences between real-value and complex-value versions of the code in class traits.
template <scalar S> struct traits {};
template <> struct traits<double> {
using t_matel = double; // type for the matrix elements
using t_coef = double; // type for the Wilson chain coefficients & various prefactors
using t_expv = double; // type for expectation values of operators
using t_eigen = double; // type for the eigenvalues (always real)
using t_temp = t_eigen; // type for temperatures
using t_weight = std::complex<double>; // spectral weight accumulators (always complex)
using evec = std::vector<double>; // vector of eigenvalues type (always real) // YYY
using RVector = std::vector<double>; // vector of eigenvalues type (always real)
using Matrix = EigenMatrix<t_matel>; // matrix type
};
template <> struct traits<std::complex<double>> {
using t_matel = std::complex<double>;
using t_coef = std::complex<double>;
using t_expv = std::complex<double>; // we allow the calculation of expectation values of non-Hermitian operators!
using t_eigen = double;
using t_temp = t_eigen;
using t_weight = std::complex<double>;
using evec = std::vector<double>;
using RVector = std::vector<double>;
using Matrix = EigenMatrix<t_matel>; // matrix type
};
template <scalar S> using matel_traits = typename traits<S>::t_matel;
template <scalar S> using coef_traits = typename traits<S>::t_coef;
template <scalar S> using expv_traits = typename traits<S>::t_expv;
template <scalar S> using eigen_traits = typename traits<S>::t_eigen;
template <scalar S> using weight_traits = typename traits<S>::t_weight;
template <scalar S> using evec_traits = typename traits<S>::evec;
template <scalar S> using RVector_traits = typename traits<S>::RVector;
template <scalar S> using Matrix_traits = typename traits<S>::Matrix;
template <matrix M> auto nrvec(const M &m) { return size1(m); }
template <matrix M> auto dim(const M &m) { return size2(m); }
} // namespace
#endif
| 4,803
|
C++
|
.h
| 88
| 52.125
| 120
| 0.701874
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,611
|
portabil.hpp
|
rokzitko_nrgljubljana/c++/portabil.hpp
|
// portabil.h - Portability code. Low-level stuff belongs here.
// Copyright (C) 2005-2020 Rok Zitko
#ifndef _portabil_hpp_
#define _portabil_hpp_
#include <stdexcept>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <optional>
#include <cmath> // isfinite
#include <cstdlib> // exit, atol
#include <complex>
#define BOOST_STACKTRACE_GNU_SOURCE_NOT_REQUIRED
#include <boost/stacktrace.hpp>
#if defined(__APPLE__) && defined(__MACH__)
#include <mach/mach_init.h>
#include <mach/task.h>
#endif
namespace NRG {
using namespace std::string_literals;
inline void print_trace() {
std::cerr << "Backtrace:" << std::endl << boost::stacktrace::stacktrace() << std::endl;
}
// Support for compiler dependant optimizations
#define assert_isfinite(x) finite_test_fnc(x, __FILE__, __LINE__)
inline bool my_isfinite(const double x) { return std::isfinite(x); }
inline bool my_isfinite(std::complex<double> z) { return std::isfinite(z.real()) && std::isfinite(z.imag()); }
inline int isfinite(std::complex<double> z) { return (std::isfinite(z.real()) && std::isfinite(z.imag()) ? 1 : 0); }
template <typename T>
inline T finite_test_fnc(T x, const char *file, const int line) {
if (!my_isfinite(x)) {
std::cout << "#### EXITING DUE TO FAILED ASSERTION." << std::endl;
std::cout << "File " << file << ", line " << line << "." << std::endl;
std::cout << "Finiteness assertion" << std::endl;
print_trace();
exit(1);
}
return x;
}
#define my_assert(x) \
do { \
if (!(x)) { \
std::stringstream my_assert_o; \
my_assert_o << "#### EXITING DUE TO FAILED ASSERTION." << std::endl; \
my_assert_o << "File " << __FILE__ << ", line " << __LINE__ << "." << std::endl; \
my_assert_o << #x << std::endl; \
print_trace(); \
throw std::runtime_error(my_assert_o.str()); \
} \
} while(0)
// Assert a==b
#define my_assert_equal(a, b) \
do { \
if (!(a == b)) { \
std::cout << "#### EXITING DUE TO FAILED ASSERTION." << std::endl; \
std::cout << "File " << __FILE__ << ", line " << __LINE__ << "." << std::endl; \
std::cout << #a << "=" << a << std::endl; \
std::cout << #b << "=" << b << std::endl; \
std::cout << "Exiting." << std::endl; \
print_trace(); \
exit(1); \
} \
} while (0)
#define my_assert_not_reached() \
do { \
std::cout << "#### EXITING DUE TO FAILED ASSERTION." << std::endl; \
std::cout << "File " << __FILE__ << ", line " << __LINE__ << "." << std::endl; \
std::cout << "Should never be reached." << std::endl; \
print_trace(); \
exit(1); \
} while (0)
// Workaround
#ifndef __TIMESTAMP__
#define __TIMESTAMP__ ""
#endif
// *** Memory usage
#if defined(__APPLE__) && defined(__MACH__)
// Source: http://blog.kuriositaet.de/?p=257
inline int getmem(unsigned int *rss, unsigned int *vs) {
struct task_basic_info t_info{};
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
if (KERN_SUCCESS != task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count)) { return -1; }
*rss = t_info.resident_size;
*vs = t_info.virtual_size;
return 0;
}
inline int memoryused() {
unsigned int rss = 0;
unsigned int vs = 0;
getmem(&rss, &vs);
return rss / 1024; // result in kB block of memory!
}
#define HAS_MEMORY_USAGE
#endif
// Finds a line containing string 'keyword' in a stream, erases that string, and returns the rest of the line.
inline std::optional<std::string> parse_string(std::istream &F, const std::string &keyword) {
while (F) {
std::string line;
std::getline(F, line);
if (auto found = line.find(keyword); found != std::string::npos)
return line.replace(found, keyword.length(), "");
}
return std::nullopt;
}
inline auto parse_string(const std::string &filename, const std::string &keyword) {
std::ifstream F(filename);
return parse_string(F, keyword);
}
#if defined(__linux)
// Returns the number of kB blocks of memory used by this process (self).
// See /usr/src/linux/Documentation/filesystems/proc.txt
inline long memoryused() {
try {
return atol(parse_string("/proc/self/status", "VmPeak:").value_or("0"s).c_str());
}
catch (...) {
return 0;
}
}
#define HAS_MEMORY_USAGE
#endif
// Fall-back
#if !defined(HAS_MEMORY_USAGE)
inline int memoryused() { return 0; }
#endif
} // namespace
#endif
| 7,734
|
C++
|
.h
| 129
| 56.891473
| 186
| 0.353407
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,612
|
nrg.hpp
|
rokzitko_nrgljubljana/c++/nrg.hpp
|
#ifndef _nrg_hpp_
#define _nrg_hpp_
namespace NRG {
// This header is included in the executable only.
} // namespace
#endif
| 129
|
C++
|
.h
| 6
| 19.833333
| 50
| 0.747899
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,614
|
step.hpp
|
rokzitko_nrgljubljana/c++/step.hpp
|
#ifndef _step_hpp_
#define _step_hpp_
#include <algorithm>
#include "params.hpp"
#include "numerics.hpp"
#include "io.hpp"
#include <fmt/format.h>
namespace NRG {
class Step {
private:
// N denotes the order of the Hamiltonian. N=0 corresponds to H_0, i.e. the initial Hamiltonian
int trueN = 0; // "true N", sets the energy scale, it may be negative, trueN <= ndxN
size_t ndxN = 0; // "index N", iteration step, used as an array index, ndxN >= 0
const Params &P; // reference to parameters (beta, T)
RUNTYPE runtype; // NRG vs. DM-NRG run
public:
void set(const int newN) noexcept {
trueN = newN;
ndxN = std::max(newN, 0);
}
void init() noexcept { set(int(P.Ninit)); }
Step(const Params &P_, const RUNTYPE runtype_ = RUNTYPE::NRG) noexcept : P(P_), runtype(runtype_) { init(); }
void next() noexcept { trueN++; ndxN++; }
[[nodiscard]] constexpr auto N() const noexcept { return ndxN; }
[[nodiscard]] constexpr auto ndx() const noexcept { return ndxN; }
[[nodiscard]] auto energyscale() const noexcept { return P.SCALE(trueN+1); } // current energy scale in units of bandwidth D
[[nodiscard]] auto scale() const noexcept { // scale factor as used in the calculation
return P.absolute ? 1.0 : energyscale();
}
[[nodiscard]] auto unscale() const noexcept { // 'unscale' parameter for dimensionless quantities
return P.absolute ? energyscale() : 1.0;
}
[[nodiscard]] auto Teff() const noexcept { return energyscale()/P.betabar; } // effective temperature for thermodynamic calculations
[[nodiscard]] auto TD_factor() const noexcept { return P.betabar / unscale(); }
[[nodiscard]] auto scT() const noexcept { return scale()/P.T; } // scT = scale*P.T, scaled physical temperature that appears in the exponents in spectral function calculations (Boltzmann weights)
[[nodiscard]] std::pair<size_t, size_t> NM() const noexcept {
const size_t N = ndxN / P.channels;
const size_t M = ndxN - N*P.channels; // M ranges 0..channels-1
return {N, M};
}
void infostring() const {
auto info = fmt::format(" ***** [{}] Iteration {}/{} (scale {}) ***** ", runtype == RUNTYPE::NRG ? "NRG"s : "DM"s,
ndxN+1, int(P.Nmax), energyscale());
info += P.substeps ? fmt::format(" step {} substep {}", NM().first+1, NM().second+1) : "";
color_print(P.pretty_out, fmt::emphasis::bold, "\n{}\n", info);
}
void set_ZBW() noexcept {
trueN = int(P.Ninit) - 1; // if Ninit=0, trueN will be -1 (this is the only exceptional case)
ndxN = P.Ninit;
}
// Return true if the spectral-function merging is to be performed at the current step
[[nodiscard]] auto N_for_merging() const noexcept {
if (P.NN1) return true;
if (P.NN2avg) return true;
return P.NN2even ? is_even(ndxN) : is_odd(ndxN);
}
[[nodiscard]] size_t firstndx() const noexcept { return P.Ninit; }
[[nodiscard]] size_t lastndx() const noexcept { return P.ZBW() ? P.Ninit : P.Nmax-1; }
// Return true if this is the first step of the NRG iteration
[[nodiscard]] auto first() const noexcept { return ndxN == firstndx(); }
// Return true if N is the last step of the NRG iteration
[[nodiscard]] auto last(int N) const noexcept {
return N == lastndx() || (P.ZBW() && N == firstndx()); // special case!
}
[[nodiscard]] auto last() const noexcept { return last(int(ndxN)); }
[[nodiscard]] auto end() const noexcept { return ndxN >= P.Nmax; } // ndxN is outside the allowed range
void set_last() noexcept {
set(int(lastndx()));
if (P.ZBW()) set_ZBW();
}
// NOTE: for ZBW calculations, Ninit=0 and Nmax=0, so that first() == true and last() == true for ndxN=0.
[[nodiscard]] constexpr auto nrg() const noexcept { return runtype == RUNTYPE::NRG; }
[[nodiscard]] constexpr auto dmnrg() const noexcept { return runtype == RUNTYPE::DMNRG; }
// Index 'n' of the last site in the existing chain, f_n (at iteration 'N'). The site being added is f_{n+1}. This
// is the value that we use in building the matrix.
[[nodiscard]] constexpr auto getnn() const noexcept { return ndxN; }
[[nodiscard]] constexpr auto get_trueN() const noexcept { return trueN; }
[[nodiscard]] constexpr auto get_ndxN() const noexcept { return ndxN; }
[[nodiscard]] constexpr auto get_runtype() const noexcept { return runtype; }
[[nodiscard]] constexpr bool operator==(const Step &other) const noexcept {
return trueN == other.get_trueN() && ndxN == other.get_ndxN() && runtype == other.get_runtype();
}
};
} // namespace
#endif
| 4,598
|
C++
|
.h
| 85
| 49.741176
| 198
| 0.654981
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,615
|
basicio.hpp
|
rokzitko_nrgljubljana/c++/basicio.hpp
|
#ifndef _basicio_hpp_
#define _basicio_hpp_
#include <algorithm> // copy
#include <string>
#include <complex>
#include <set>
#include <fstream>
#include <iostream>
#include <iomanip> // set_precision
#include <iterator> // ostream_iterator
#include <stdexcept>
#include <fmt/format.h>
#include <boost/lexical_cast.hpp>
#include "portabil.hpp"
#include "traits.hpp"
#define HIGHPREC(val) std::setprecision(std::numeric_limits<double>::max_digits10) << (val)
namespace NRG {
template <class T>
inline T from_string(const std::string &str) {
T result;
try {
result = boost::lexical_cast<T>(str);
} catch (boost::bad_lexical_cast &) { throw std::runtime_error(fmt::format("Lexical cast [{}] failed.", str)); }
return result;
}
template <>
inline bool from_string(const std::string &str) { return (strcasecmp(str.c_str(), "true") == 0 ? true : false); }
// for T=int, std::to_string is used
template <class T>
inline std::string to_string(const T &val) { return boost::lexical_cast<std::string>(val); }
inline std::string to_string(const std::complex<double> &z) {
std::ostringstream s;
s << z;
return s.str();
}
template <typename T>
std::ostream & operator<<(std::ostream &os, const std::set<T> &x) {
std::copy(x.cbegin(), x.cend(), std::ostream_iterator<T>(os, " "));
return os;
}
template <typename T1, typename T2>
std::ostream &operator<<(std::ostream &os, const std::pair<T1, T2> &p) {
return os << p.first << ' ' << p.second;
}
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &vec) {
for (const auto &x : vec) os << x << " ";
return os;
}
// Returns a string with a floating value in fixed (non-exponential) format with N digits of precision after the
// decimal point.
inline std::string prec(const double x, const int N)
{
std::ostringstream s;
s << std::fixed << std::setprecision(N) << x;
return s.str();
}
inline std::string prec3(const double x) { return prec(x, 3); }
template <typename T>
inline bool negligible_imag_part(const std::complex<T> &z, const double output_imag_eps = 1e-13) {
return abs(z.imag()) < abs(z.real()) * output_imag_eps;
}
inline std::ofstream safe_open(const std::string &filename, const bool binary = false) {
my_assert(filename != "");
std::ios::openmode flag = std::ios::out;
if (binary) flag |= std::ios::binary;
std::ofstream F(filename, flag);
if (!F) throw std::runtime_error(fmt::format("Can't open {} for writing", filename));
return F;
}
inline std::ifstream safe_open_for_reading(const std::string &filename, const bool binary = false) {
my_assert(filename != "");
std::ios::openmode flag = std::ios::in;
if (binary) flag |= std::ios::binary;
std::ifstream F(filename, flag);
if (!F) throw std::runtime_error(fmt::format("Can't open {} for reading", filename));
return F;
}
inline bool file_exists(const std::string &fn)
{
std::ofstream F(fn, std::ios::binary | std::ios::out);
return bool(F);
}
inline size_t count_words_in_string(const std::string &s) { // size_t because it should be unsigned
std::stringstream stream(s);
return std::distance(std::istream_iterator<std::string>(stream), std::istream_iterator<std::string>());
}
// Read one object of type S from an object F which has an extractor operator. Use as read_one<S>(F).
template<typename S, typename T>
inline auto read_one(T &F) {
S value;
F >> value;
return value;
}
// Determine the matrix dimensions from a stream of rows of white-space-separated tabulated values
inline auto get_dims(std::istream &F) {
size_t dim1 = 0; // number of rows
size_t dim2 = 0; // number of columns
while (F.good()) {
std::string s;
std::getline(F, s);
if (!F.fail()) {
auto n = count_words_in_string(s);
if (dim2 > 0 && dim2 != n) throw std::runtime_error("All matrix rows must be equally long");
dim2 = n;
dim1++;
}
}
return std::make_pair(dim1, dim2);
}
// Read 'size' values of type T into a std::vector<T>.
template <scalar T> auto read_std_vector(std::istream &F, const size_t size) {
std::vector<T> vec(size);
for (auto j = 0; j < size; j++)
vec[j] = read_one<T>(F);
if (F.fail()) throw std::runtime_error("read_std_vector() error. Input file is corrupted.");
return vec;
}
// Read values of type T into a std::vector<T>. First value to be read, 'nr', is either vector dimension or
// the value of maximum index.
template <scalar T> auto read_std_vector(std::istream &F, const bool nr_is_max_index = false) {
const auto nr = read_one<size_t>(F);
const auto len = nr_is_max_index ? nr+1 : nr;
return read_std_vector<T>(F, len);
}
} // namespace
#endif
| 4,658
|
C++
|
.h
| 127
| 34.330709
| 114
| 0.682282
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,616
|
diag_serial.hpp
|
rokzitko_nrgljubljana/c++/diag_serial.hpp
|
#ifndef _diag_serial_hpp_
#define _diag_serial_hpp_
#include "traits.hpp"
#include "step.hpp"
#include "operators.hpp"
#include "coef.hpp"
#include "eigen.hpp"
#include "output.hpp"
#include "invar.hpp"
#include "params.hpp"
#include "symmetry.hpp"
#include "diagengine.hpp"
namespace NRG {
template<scalar S>
class DiagSerial : public DiagEngine<S> {
public:
DiagInfo<S> diagonalisations(const Step &step, const Opch<S> &opch, const Coef<S> &coef, const DiagInfo<S> &diagprev, const Output<S> &output,
const std::vector<Invar> &tasks, const DiagParams &DP, const Symmetry<S> *Sym, const Params &P) {
DiagInfo<S> diagnew;
for (const auto &I: tasks) {
auto h = hamiltonian(step, I, opch, coef, diagprev, output, Sym, P);
nrglog('(', "[serial] Diagonalizing " << I << " dim=" << dim(h));
auto e = diagonalise(h, DP, -1); // -1 = not using MPI
diagnew[I] = Eigen(std::move(e), step);
}
return diagnew;
}
};
}
#endif
| 1,004
|
C++
|
.h
| 30
| 29.433333
| 145
| 0.651187
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,617
|
constants.hpp
|
rokzitko_nrgljubljana/c++/constants.hpp
|
#ifndef _constants_hpp_
#define _constants_hpp_
inline const size_t MAX_NDX = 1000; // max index number, req'd in read-input.h & stats.h
#endif
| 146
|
C++
|
.h
| 4
| 35
| 88
| 0.735714
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,619
|
openmp.hpp
|
rokzitko_nrgljubljana/c++/openmp.hpp
|
#ifndef _openmp_hpp_
#define _openmp_hpp_
#include <iostream>
#include <omp.h>
#ifdef MKL
#include <mkl_service.h>
#endif
namespace NRG {
// Report OpenMP parallelization settings
inline void report_openMP(std::ostream &s = std::cout) {
s << "[OpenMP] Max. number of threads: " << omp_get_max_threads() << std::endl;
s << "[OpenMP] Number of processors: " << omp_get_num_procs() << std::endl;
s << "[OpenMP] Dynamic thread adjustment: " << omp_get_dynamic() << std::endl;
#ifdef MKL
MKLVersion version;
mkl_get_version(&version);
s << "Using Intel MKL library " << version.MajorVersion << "." << version.MinorVersion << "." << version.UpdateVersion << std::endl;
s << "Processor optimization: " << version.Processor << std::endl;
const int max_threads = mkl_get_max_threads();
// Portability hack
# ifdef MKL_DOMAIN_BLAS
# define NRG_MKL_DOMAIN_BLAS MKL_DOMAIN_BLAS
# else
# define NRG_MKL_DOMAIN_BLAS MKL_BLAS
# endif
const int blas_max_threads = mkl_domain_get_max_threads(NRG_MKL_DOMAIN_BLAS);
const int dynamic = mkl_get_dynamic();
s << "max_threads=" << max_threads << " blas_max_threads=" << blas_max_threads << " dynamic=" << dynamic << std::endl << std::endl;
#endif
s << std::endl;
}
} // namespace
#endif
| 1,258
|
C++
|
.h
| 33
| 36.151515
| 134
| 0.677605
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,620
|
invar.hpp
|
rokzitko_nrgljubljana/c++/invar.hpp
|
// Quantum numbers
// Rok Zitko, rok.zitko@ijs.si, 2006-2020
#ifndef _nrg_invar_hpp_
#define _nrg_invar_hpp_
#include <utility>
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <stdexcept>
#include <boost/serialization/vector.hpp> // for InvType = std::vector<int>
#include <fmt/format.h>
#include "portabil.hpp"
namespace NRG {
// Conversion functions: multiplicity (integer) -> quantum number (floating point)
// WARNING: avoid using S as template variable in places where S() is used!!!
inline double S(const int SS) { return (SS - 1.0) / 2.0; }
inline double ISO(const int II) { return (II - 1.0) / 2.0; }
inline double SZ(const int SSZ) { return (SSZ - 1.0) / 2.0; }
using InvType = std::vector<int>;
constexpr int multiplicative = 0;
constexpr int additive = 1;
constexpr int mod3 = 3;
inline auto typestr(const int t) {
switch (t) {
case multiplicative: return "multiplicative";
case additive: return "additive";
case mod3: return "mod3";
default: my_assert_not_reached();
}
}
class Invar {
private:
InvType data;
friend class boost::serialization::access;
template <class Archive> void serialize(Archive &ar, [[maybe_unused]] const unsigned int version) { ar &data; }
public:
inline static std::vector<int> qntype; // must be defined before calls to Invar::combine() and Invar::invert()
inline static std::map<std::string, int> names; // must be defined before calls to Invar::get()
// invdim holds the number of quantum numbers required to specify the invariant subspaces (representations), i.e. (in
// more fancy terms) the dimension of the Cartan subalgebra of the full symmetry algebra.
inline static size_t invdim = 0; // 0 before initialization!
Invar() : data(invdim) {}
explicit Invar(const InvType &d) {
my_assert(d.size() == data.size());
data = d;
}
explicit Invar(const int i0) : data{i0} {} // (int) constructor
explicit Invar(const int i0, const int i1) : data{i0, i1} {} // (int,int) constructor
explicit Invar(const int i0, const int i1, const int i2) : data{i0, i1, i2} {} // (int,int,int) constructor
std::ostream &insertor(std::ostream &os, const std::string &delim = " "s) const {
for (size_t i = 0; i < data.size(); i++) os << data[i] << (i != data.size() - 1 ? delim : "");
return os;
}
friend std::ostream &operator<<(std::ostream &os, const Invar &invar) { return invar.insertor(os); }
[[nodiscard]] auto str() const { std::ostringstream s; insertor(s); return s.str(); }
[[nodiscard]] auto name() const { std::ostringstream s; insertor(s, "_"s); return s.str(); }
auto & extractor(std::istream &is) {
for (auto &i : data) {
int qn{};
if (is >> qn)
i = qn;
else
throw std::runtime_error("Failed reading quantum numbers.");
}
return is;
}
friend auto &operator>>(std::istream &is, Invar &invar) { return invar.extractor(is); }
bool operator==(const Invar &invar2) const { return data == invar2.data; }
bool operator!=(const Invar &invar2) const { return !operator==(invar2); }
bool operator<(const Invar &invar2) const { return data < invar2.data; }
// Accessor needed, because data is private.
[[nodiscard]] auto getqn(const size_t i) const {
my_assert(i < data.size());
return data[i];
}
// Quantum number addition laws for forming tensor products. For SU(2) and U(1) (additive quantum numbers) this is
// simply addition.
void combine(const Invar &invar2) {
for (size_t i = 0; i < invdim; i++) {
switch (qntype[i]) {
case additive:
data[i] += invar2.getqn(i); // Additive
break;
case multiplicative:
my_assert(data[i] == 1 || data[i] == -1);
data[i] *= invar2.getqn(i); // Multiplicative
break;
case mod3:
my_assert(0 <= data[i] && data[i] <= 2);
data[i] += invar2.getqn(i); // Modulo 3 additive
data[i] = data[i] % 3;
break;
default: my_assert_not_reached();
}
}
}
// In DMNRG runs, we must perform the "inverse of the quantum number addition", i.e. find subspaces that an
// invariant subspaces contributed *to*.
void inverse() {
for (size_t i = 0; i < invdim; i++)
switch (qntype[i]) {
case additive:
// For SU(2) and U(1) related quantum numbers, we just flip the sign.
data[i] = -data[i];
break;
case multiplicative:
my_assert(data[i] == 1 || data[i] == -1);
// do nothing since multiplication and division are equivalent! In principle, data[i] = 1/data[i].
break;
case mod3:
my_assert(0 <= data[i] && data[i] <= 2);
// Flip sign and take modulo 3 value.
data[i] = (3 - data[i]) % 3;
my_assert(0 <= data[i] && data[i] <= 2);
break;
}
}
[[nodiscard]] auto get(const std::string &which) const {
const auto i = names.find(which);
if (i == end(names)) throw std::invalid_argument(fmt::format("{} is an unknown quantum number.", which));
const auto index = i->second;
my_assert(index < invdim);
const auto type = qntype[index];
const auto f = getqn(index);
// Sanity check
switch (type) {
case multiplicative: my_assert(f == 1 || f == -1); break;
case mod3: my_assert(0 <= f && f <= 2); break;
}
return f;
}
void InvertMyParity() {
// By convention (for QSLR, QSZLR, ISOLR, ISOSZLR), parity is the quantum number named "P"
const auto i = names.find("P");
if (i == end(names)) throw std::invalid_argument("Critical error: no P quantum number");
const auto index = i->second;
data[index] = -data[index];
}
[[nodiscard]] auto InvertParity() const {
Invar I(data);
I.InvertMyParity();
return I;
}
};
struct InvarStructure {
std::string name;
int type;
};
inline void initInvar(std::initializer_list<InvarStructure> l) {
Invar::invdim = l.size();
auto i = 0;
for (const auto & [n, t]: l) {
my_assert(t == additive || t == multiplicative || t == mod3);
Invar::names[n] = i++;
Invar::qntype.push_back(t);
std::cout << fmt::format("{} {} {}\n", i, n, typestr(t));
}
}
using InvarVec = std::vector<Invar>; // holds information about ancestor subspaces
using Twoinvar = std::pair<Invar, Invar>; // labels subspace bra and subspace ket for matrix elements
inline std::ostream &operator<<(std::ostream &os, const Twoinvar &p) { return os << "(" << p.first << ") (" << p.second << ")"; }
} // namespace
#endif
| 6,666
|
C++
|
.h
| 164
| 35.695122
| 129
| 0.622418
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,621
|
diag_mpi.hpp
|
rokzitko_nrgljubljana/c++/diag_mpi.hpp
|
#ifndef _diag_mpi_hpp_
#define _diag_mpi_hpp_
#include <iostream>
#include <list>
#include <deque>
#include <algorithm>
#ifdef OMPI_SKIP_MPICXX // workaround to avoid warnings for for redefinition in mpi/environment.hpp
#undef OMPI_SKIP_MPICXX
#endif
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi/collectives.hpp> // broadcast
#include "traits.hpp"
#include "invar.hpp"
#include "step.hpp"
#include "operators.hpp"
#include "symmetry.hpp"
#include "params.hpp"
#include "diag.hpp"
#include "misc.hpp"
#include "core.hpp"
#include "diagengine.hpp"
namespace NRG {
enum TAG : int { TAG_EXIT = 1, TAG_DIAG, TAG_SYNC, TAG_INVAR, TAG_MATRIX, TAG_MATRIX_PART, TAG_MATRIX_SIZE, TAG_VEC };
template <scalar S>
class DiagMPI : public DiagEngine<S>{
private:
boost::mpi::environment &mpienv;
boost::mpi::communicator &mpiw;
public:
DiagMPI(boost::mpi::environment &mpienv, boost::mpi::communicator &mpiw) : mpienv(mpienv), mpiw(mpiw) {}
~DiagMPI() {
for (auto i = 1; i < mpiw.size(); i++) mpiw.send(i, TAG_EXIT, 0); // notify slaves we are done
}
void send_params(const DiagParams &DP) {
mpilog("Sending diag parameters: diag=" << DP.diag << " diagratio=" << DP.diagratio);
for (auto i = 1; i < mpiw.size(); i++) mpiw.send(i, TAG_SYNC, 0);
auto DPcopy = DP;
boost::mpi::broadcast(mpiw, DPcopy, 0);
}
DiagParams receive_params() {
DiagParams DP;
boost::mpi::broadcast(mpiw, DP, 0);
mpilog("Received diag parameters: diag=" << DP.diag << " diagratio=" << DP.diagratio);
return DP;
}
void send_matrix(const int dest, const EigenMatrix<S> &m) {
mpilog("send_matrix() caled, dest=" << dest);
const size_t size1 = NRG::size1(m);
mpiw.send(dest, TAG_MATRIX_SIZE, size1);
const size_t size2 = NRG::size2(m);
mpiw.send(dest, TAG_MATRIX_SIZE, size2);
mpilog("Sending matrix of size " << size1 << " x " << size2 << " to " << dest);
// NOTE: MPI is limited to message size of 2GB (or 4GB). For big problems we thus need to send objects line by line.
// mpiw.send(dest, TAG_MATRIX, (S*)m.data(), size1*size2);
for (size_t i = 0; i < size1; i++)
mpiw.send(dest, TAG_MATRIX_PART, (S*)m.data() + i*size2, size2);
}
auto receive_matrix(const int source) {
mpilog("receive_matrix() called, source=" << source);
size_t size1;
mpiw.recv(source, TAG_MATRIX_SIZE, size1);
size_t size2;
mpiw.recv(source, TAG_MATRIX_SIZE, size2);
mpilog("Receiving matrix of size " << size1 << " x " << size2 << " from " << source);
EigenMatrix<S> m(size1, size2);
// mpiw.recv(source, TAG_MATRIX, (S*)m.data(), size1*size2);
for (size_t i = 0; i < size1; i++)
mpiw.recv(source, TAG_MATRIX_PART, (S*)m.data() + i*size2, size2);
return m;
}
void send_raweigen(const int dest, const RawEigen<S> &eig) {
mpilog("Sending eigen from " << mpiw.rank() << " to " << dest);
mpiw.send(dest, TAG_VEC, eig.val);
send_matrix(dest, eig.vec);
}
auto receive_raweigen(const int source) {
mpilog("Receiving eigen from " << source << " on " << mpiw.rank());
RawEigen<S> eig;
mpiw.recv(source, TAG_VEC, eig.val);
eig.vec = receive_matrix(source);
return eig;
}
// Read results from a slave process.
std::pair<Invar, RawEigen<S>> read_from(const int source) {
mpilog("Reading results from " << source);
const auto eig = receive_raweigen(source);
Invar Irecv;
mpiw.recv(source, TAG_INVAR, Irecv);
mpilog("Received results for subspace " << Irecv << " [nr=" << eig.getnrcomputed() << ", dim=" << eig.getdim() << "]");
return {Irecv, eig};
}
auto myrank() { return mpiw.rank(); }
// Handle a diagonalisation request
void slave_diag(const int master, const DiagParams &DP) {
// 1. receive the matrix and the subspace identification
mpilog("slave_diag() called, master=" << master);
Invar I;
mpiw.recv(master, TAG_INVAR, I);
mpilog("Received I=" << I);
auto m = receive_matrix(master);
// 2. preform the diagonalisation
const auto eig = diagonalise(m, DP, myrank());
// 3. send back the results
send_raweigen(master, eig);
mpiw.send(master, TAG_INVAR, I);
}
DiagInfo<S> diagonalisations(const Step &step, const Opch<S> &opch, const Coef<S> &coef, const DiagInfo<S> &diagprev, const Output<S> &output,
const std::vector<Invar> &tasks, const DiagParams &DP, const Symmetry<S> *Sym, const Params &P) {
DiagInfo<S> diagnew;
send_params(DP); // Synchronise parameters
std::list<Invar> tasks_todo(tasks.begin(), tasks.end());
std::list<Invar> tasks_done;
std::deque<int> nodes_available(mpiw.size()); // Available nodes including the master, which is always at the head of the deque
std::iota(nodes_available.begin(), nodes_available.end(), 0);
nrglog('M', "nrtasks=" << tasks_todo.size() << " nrnodes=" << nodes_available.size());
while (!tasks_todo.empty()) {
my_assert(!nodes_available.empty());
// i is the node to which the next job will be scheduled. (If a single task is left undone, do it on the master
// node to avoid the unnecessary network copying.)
const auto i = tasks_todo.size() != 1 ? get_back(nodes_available) : 0;
// On master, we take short jobs from the end. On slaves, we take long jobs from the beginning.
const Invar I = i == 0 ? get_back(tasks_todo) : get_front(tasks_todo);
auto h = hamiltonian(step, I, opch, coef, diagprev, output, Sym, P); // non-const
nrglog('M', "Scheduler: job " << I << " (dim=" << dim(h) << ")" << " on node " << i);
if (i == 0) {
// On master, diagonalize immediately.
auto e = diagonalise(h, DP, myrank());
diagnew[I] = Eigen<S>(std::move(e), step);
tasks_done.push_back(I);
nodes_available.push_back(0);
} else {
mpiw.send(i, TAG_DIAG, 0);
mpiw.send(i, TAG_INVAR, I);
send_matrix(i, h);
}
// Check for terminated jobs
while (auto status = mpiw.iprobe(boost::mpi::any_source, TAG_VEC)) {
nrglog('M', "Receiveing results from " << status->source());
auto [Irecv, eig] = read_from(status->source());
diagnew[Irecv] = Eigen<S>(std::move(eig), step);
tasks_done.push_back(Irecv);
// The node is now available for new tasks!
nodes_available.push_back(status->source());
}
}
// Keep reading results sent from the slave processes until all tasks have been completed.
while (tasks_done.size() != tasks.size()) {
const auto status = mpiw.probe(boost::mpi::any_source, TAG_VEC);
auto [Irecv, eig] = read_from(status.source());
diagnew[Irecv] = Eigen<S>(std::move(eig), step);
tasks_done.push_back(Irecv);
}
return diagnew;
}
};
} // namespace
#endif
| 7,115
|
C++
|
.h
| 158
| 39.006329
| 145
| 0.61802
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,622
|
debug.hpp
|
rokzitko_nrgljubljana/c++/debug.hpp
|
// debug.h - auxiliary debugging macros
// Copyright (C) 2005-2020 Rok Zitko
#ifndef _debug_hpp_
#define _debug_hpp_
#include <iostream>
#include <cstdlib> // exit
namespace NRG {
// character c defines what to log
#define nrglog(c, ...) if (P.logletter(c)) { std::cout << __VA_ARGS__ << std::endl; }
#define nrglogdp(c, ...) if (DP.logletter(c)) { std::cout << __VA_ARGS__ << std::endl; }
//#define MPI_DEBUG
#ifdef MPI_DEBUG
#define mpilog(...) { std::cout << __VA_ARGS__ << std::endl; }
#else
#define mpilog(...) {}
#endif
#define nrgdump3(STR1, STR2, STR3) #STR1 << "=" << (STR1) << " " << #STR2 << "=" << (STR2) << " " << #STR3 << "=" << (STR3) << " "
#define nrgdump4(STR1, STR2, STR3, STR4) \
#STR1 << "=" << (STR1) << " " << #STR2 << "=" << (STR2) << " " << #STR3 << "=" << (STR3) << " " << #STR4 << "=" << (STR4) << " "
#define nrgdump5(STR1, STR2, STR3, STR4, STR5) \
#STR1 << "=" << (STR1) << " " << #STR2 << "=" << (STR2) << " " << #STR3 << "=" << (STR3) << " " << #STR4 << "=" << (STR4) << " " << #STR5 \
<< "=" << (STR5) << " "
#define nrgdump7(STR1, STR2, STR3, STR4, STR5, STR6, STR7) \
#STR1 << "=" << (STR1) << " " << #STR2 << "=" << (STR2) << " " << #STR3 << "=" << (STR3) << " " << #STR4 << "=" << (STR4) << " " << #STR5 \
<< "=" << (STR5) << " " << #STR6 << "=" << (STR6) << " " << #STR7 << "=" << (STR7) << " "
} // namespace
#endif
| 1,669
|
C++
|
.h
| 27
| 59.555556
| 142
| 0.385276
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,623
|
recalc.hpp
|
rokzitko_nrgljubljana/c++/recalc.hpp
|
#ifndef _recalc_hpp_
#define _recalc_hpp_
#include "debug.hpp"
#include "traits.hpp"
#include "invar.hpp"
#include "eigen.hpp"
#include "subspaces.hpp"
#include "operators.hpp"
#include "symmetry.hpp"
#include "numerics.hpp"
namespace NRG {
// We split the matrices of eigenvectors into blocks according to the partition into "ancestor subspaces". At the price
// of some copying, this increases memory locality of data and thus improves numerical performence of matrix-matrix multiplies
// in the recalculation of matrix elements. Note that the original (matrix) data is discarded after the splitting.
template<scalar S, typename Matrix = Matrix_traits<S>>
inline void split_in_blocks_Eigen(Eigen<S> &e, const SubspaceDimensions &sub) {
const auto combs = sub.combs();
e.U.resize(combs);
const auto nr = e.getnrstored();
my_assert(0 < nr && nr <= e.getdim());
for (const auto block: range0(combs)) {
Matrix U = e.vectors.submatrix_const({0, nr}, sub.part(block));
e.U.set(block, std::move(U));
}
assert(e.U.is_unitary());
e.vectors.shrink();
}
template<scalar S>
inline void split_in_blocks(DiagInfo<S> &diag, const SubspaceStructure &substruct) {
for(auto &[I, eig]: diag)
split_in_blocks_Eigen(eig, substruct.at(I));
}
template<scalar S>
inline void h5save_blocks_Eigen(H5Easy::File &fd, const std::string &name, const Eigen<S> &eig, const SubspaceDimensions &sub)
{
// For certain symmetry types (SPSU2) the same ancestor subspace may contribute more than one
// time, thus we add a suffix with a counter (nr).
const auto range = range0(sub.combs());
for (const auto & [nr, i]: range | ranges::views::enumerate)
h5_dump_matrix(fd, name + "/" + sub.ancestor(i).name() + "|nr=" + std::to_string(nr), eig.U.get(i));
}
template<scalar S>
inline void h5save_blocks(H5Easy::File &fd, const std::string &name, const DiagInfo<S> &diag, const SubspaceStructure &substruct) {
for(const auto &[I, eig]: diag)
h5save_blocks_Eigen(fd, name + I.name(), eig, substruct.at(I));
}
// Recalculates the irreducible matrix elements <I1|| f || Ip>. Called from recalc_irreduc() in nrg-recalc-* files.
template<scalar S> template<typename T>
auto Symmetry<S>::recalc_f(const DiagInfo<S> &diag,
const Invar &I1, // bra
const Invar &Ip, // ket
const T &table) const
{
nrglog('f', "*** recalc_f() ** f: I1=(" << I1 << ") Ip=(" << Ip << ")");
if (!recalc_f_coupled(I1, Ip, this->Invar_f)) return Matrix(0,0); // exception for QST and SPSU2T
const auto & [diagI1, diagIp] = diag.subs(I1, Ip);
const auto & [dim1, dimp] = diag.dims(I1, Ip); // # of states in Ip and in I1, i.e. the dimension of the <||f||> matrix.
nrglog('f', "dim1=" << dim1 << " dimp=" << dimp);
auto f = zero_matrix<S>(dim1, dimp);
// <I1||f||Ip> gets contributions from various |QSr> states. These are given by i1, ip in the Recalc_f type tables.
for (const auto &[i1, ip, factor]: table) {
nrglog('f', "** i1=" << i1 << " ip=" << ip << " factor=" << factor);
const auto U1 = diagI1.U(i1);
const auto Up = diagIp.U(ip);
nrglog('f', "* norm1=" << frobenius_norm(U1) << " normp=" << frobenius_norm(Up));
if (finite_size(U1) && finite_size(Up)) nrglog('f', "* U1(0,0)=" << U1(0,0) << " Up(0,0)=" << Up(0,0));
product<S>(f, factor, U1, Up);
}
if (P.logletter('F')) dump_matrix(f);
return f;
}
// Recalculate the (irreducible) matrix elements of various operators. This is the most important routine in this
// program, so it is heavily instrumentalized for debugging purposes. It is called from recalc_doublet(),
// recalc_singlet(), and other routines. The inner-most for() loops can be found here, so this is the right spot that
// one should try to hand optimize.
template<scalar S> template<typename T>
auto Symmetry<S>::recalc_general(const DiagInfo<S> &diag,
const MatrixElements<S> &cold,
const Invar &I1, // target subspace (bra)
const Invar &Ip, // target subspace (ket)
const T &table,
const Invar &Iop) const // quantum numbers of the operator
{
if (P.logletter('r')) std::cout << "*** recalc_general: " << nrgdump3(I1, Ip, Iop) << std::endl;
const auto & [diagI1, diagIp] = diag.subs(I1, Ip);
const auto & [dim1, dimp] = diag.dims(I1, Ip);
const Twoinvar II = {I1, Ip};
auto cn = zero_matrix<S>(dim1, dimp);
if (dim1 == 0 || dimp == 0) return cn; // return empty matrix
for (const auto &[i1, ip, IN1, INp, factor]: table) {
my_assert(1 <= i1 && i1 <= nr_combs() && 1 <= ip && ip <= nr_combs());
if (P.logletter('r')) std::cout << nrgdump7(i1, ip, IN1, ancestor(I1,i1-1), INp, ancestor(Ip,ip-1), factor) << std::endl;
if (!Invar_allowed(IN1) || !Invar_allowed(INp)) continue;
my_assert(IN1 == ancestor(I1, i1-1));
my_assert(INp == ancestor(Ip, ip-1));
const Twoinvar ININ = {IN1, INp};
if (cold.count(ININ) == 0) continue;
transform<S>(cn, factor, diagI1.U(i1), cold.at(ININ), diagIp.U(ip));
} // over table
if (P.logletter('R')) dump_matrix(cn);
return cn;
}
// This routine is used for recalculation of global operators in nrg-recalc-*.cc
template<scalar S>
void Symmetry<S>::recalc1_global(const DiagInfo<S> &diag, // XXX: pass Eigen instead
const Invar &I,
Matrix &m, // modified, not produced!
const size_t i1,
const size_t ip,
const t_coef value) const
{
const auto &diagI = diag.at(I);
product<S>(m, value, diagI.U(i1), diagI.U(ip));
}
} // namespace
#endif
| 5,830
|
C++
|
.h
| 116
| 44.327586
| 131
| 0.621778
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,624
|
numerics_Eigen.hpp
|
rokzitko_nrgljubljana/c++/numerics_Eigen.hpp
|
//Don't include directly, include numerics.hpp with define USE_EIGEN instead
#ifndef _NUMERICS_EIGEN_HPP_
#define _NUMERICS_EIGEN_HPP_
#include <Eigen/Dense>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include "basicio.hpp"
template <scalar S>
[[nodiscard]] EigenMatrix<S> generate_Eigen(const size_t size1, const size_t size2) {
return EigenMatrix<S>(size1, size2);
}
// Generators
template <scalar S>
[[nodiscard]] EigenMatrix<S> generate_matrix(const size_t size1, const size_t size2) {
return EigenMatrix<S>(size1, size2);
}
template <scalar S>
[[nodiscard]] EigenMatrix<S> zero_matrix(const size_t size1, const size_t size2) {
return EigenMatrix<S>::Zero(size1, size2);
}
template <scalar S>
[[nodiscard]] EigenMatrix<S> id_matrix(const size_t size) {
return EigenMatrix<S>::Identity(size, size);
}
// XXX: return view instead?
template <scalar S> EigenMatrix<S> herm(const EigenMatrix<S> &m) { return m.adjoint(); }
template <scalar S> EigenMatrix<S> trans(const EigenMatrix<S> &m) { return m.transpose(); }
// Access the low-level data storage in the matrix (used in diag.hpp)
template<scalar S> S * data(EigenMatrix<S> &m) {
return m.data();
}
template <scalar T>
void save(boost::archive::binary_oarchive &oa, const EigenMatrix<T> &m) {
oa << size1(m) << size2(m);
for (const auto row : m.rowwise())
oa << row;
}
template <scalar T>
auto load_Eigen(boost::archive::binary_iarchive &ia) {
const auto isize1 = read_one<size_t>(ia);
const auto isize2 = read_one<size_t>(ia);
auto m = EigenMatrix<T>(isize1, isize2);
for (const auto i : range0(isize1))
m.row(i) = read_one<EigenMatrix<T>>(ia);
return m;
}
template <scalar T>
auto load(boost::archive::binary_iarchive &ia) { return load_Eigen<T>(ia); }
// Read 'size' values of type T into an Eigen vector<T>.
template <scalar T> auto read_Eigen_vector(std::istream &F, const size_t size) {
Eigen::VectorX<T> vec(size);
for (auto j = 0; j < size; j++)
vec[j] = read_one<T>(F);
if (F.fail()) throw std::runtime_error("read_vector() error. Input file is corrupted.");
return vec;
}
// Read values of type T into an Eigen vector<T>. 'nr' is either vector dimension or the value of maximum index
template <scalar T> auto read_Eigen_vector(std::istream &F, const bool nr_is_max_index = false) {
const auto nr = read_one<size_t>(F);
const auto len = nr_is_max_index ? nr+1 : nr;
return read_Eigen_vector<T>(F, len);
}
// Read 'size1' x 'size2' Eigen matrix of type T.
template <scalar T> auto read_Eigen_matrix(std::istream &F, const size_t size1, const size_t size2) {
EigenMatrix<T> m(size1, size2);
for (auto j1 = 0; j1 < size1; j1++)
for (auto j2 = 0; j2 < size2; j2++)
m(j1, j2) = assert_isfinite( read_one<T>(F) );
if (F.fail()) std::runtime_error("read_matrix() error. Input file is corrupted.");
return m;
}
template <scalar T> auto read_matrix(std::istream &F, const size_t size1, const size_t size2) {
return read_Eigen_matrix<T>(F, size1, size2);
}
template<scalar S, Eigen_matrix EM, typename t_coef = coef_traits<S>>
void product(EM &M, const t_coef factor, const EM &A, const EM &B) {
if (finite_size(A) && finite_size(B)) {
assert(size1(M) == size1(A) && size2(A) == size2(B) && size1(B) == size2(M));
assert(my_isfinite(factor));
M += factor * A * B.adjoint();
}
}
template<scalar S, Eigen_matrix EM, typename t_coef = coef_traits<S>>
void transform(EM &M, const t_coef factor, const EM &A, const EM &O, const EM &B) {
if (finite_size(A) && finite_size(B)) {
assert(size1(M) == size1(A) && size2(A) == size1(O) && size2(O) == size2(B) && size1(B) == size2(M));
assert(my_isfinite(factor));
M += factor * A * O * B.adjoint();
}
}
template<scalar S, typename U_type, Eigen_matrix EM, typename t_coef = coef_traits<S>> // XXX: U_type
void rotate(EM &M, const t_coef factor, const U_type &U, const EM &O) {
if (finite_size(U)) {
assert(size1(M) == size2(U) && size1(U) == size1(O) && size2(O) == size1(U) && size2(U) == size2(M));
assert(my_isfinite(factor));
M += factor * U.adjoint() * O * U;
}
}
template<scalar S>
Eigen::Block<const EigenMatrix<S>> submatrix_const(const EigenMatrix<S> &M, const std::pair<size_t,size_t> &r1, const std::pair<size_t,size_t> &r2)
{
return M.block(r1.first, r2.first, r1.second - r1.first, r2.second - r2.first);
}
template<scalar S>
Eigen::Block<EigenMatrix<S>> submatrix(EigenMatrix<S> &M, const std::pair<size_t,size_t> &r1, const std::pair<size_t,size_t> &r2)
{
return M.block(r1.first, r2.first, r1.second - r1.first, r2.second - r2.first);
}
template<scalar S>
void resize(EigenMatrix<S> &m, const size_t new_size1, const size_t new_size2) {
assert(new_size1 <= size1(m) && new_size2 <= size2(m));
m.conservativeResize(new_size1, new_size2);
}
template<scalar T, Eigen_matrix U, Eigen_matrix V>
EigenMatrix<T> matrix_prod(const U &A, const V &B) {
assert(size2(A) == size1(B));
return A * B;
}
template<scalar T, Eigen_matrix U, Eigen_matrix V>
EigenMatrix<T> matrix_adj_prod(const U &A, const V &B) {
assert(size1(A) == size1(B));
return A.adjoint() * B;
}
#endif
| 5,175
|
C++
|
.h
| 124
| 39.435484
| 147
| 0.68332
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,625
|
diagengine.hpp
|
rokzitko_nrgljubljana/c++/diagengine.hpp
|
#ifndef _diagengine_hpp_
#define _diagengine_hpp_
#include "traits.hpp"
#include "step.hpp"
#include "operators.hpp"
#include "coef.hpp"
#include "eigen.hpp"
#include "output.hpp"
#include "invar.hpp"
#include "params.hpp"
#include "symmetry.hpp"
namespace NRG {
template <scalar S>
class DiagEngine {
public:
virtual DiagInfo<S> diagonalisations(const Step &step, const Opch<S> &opch, const Coef<S> &coef, const DiagInfo<S> &diagprev, const Output<S> &output,
const std::vector<Invar> &tasks, const DiagParams &DP, const Symmetry<S> *Sym, const Params &P);
virtual ~DiagEngine() = default;
};
}
#endif
| 655
|
C++
|
.h
| 21
| 27.714286
| 153
| 0.701113
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,626
|
output.hpp
|
rokzitko_nrgljubljana/c++/output.hpp
|
#ifndef _output_hpp_
#define _output_hpp_
#include <memory>
#include <ostream>
#include <iomanip>
#include <string>
#include <map>
#include <list>
#include <utility>
#include <vector>
#include <range/v3/all.hpp>
#include <boost/range/adaptor/map.hpp>
#include "traits.hpp"
#include "params.hpp"
#include "io.hpp" // formatted_output
#include "misc.hpp" // range1
#include "step.hpp"
#include "stats.hpp"
#include "symmetry.hpp"
#include "h5.hpp"
namespace NRG {
// Formatted output of the computed expectation values
template<scalar S, typename t_expv = expv_traits<S>>
class ExpvOutput {
private:
std::ofstream F; // output stream
std::map<std::string, t_expv> &m; // reference to the name->value mapping (e.g. from class Stats)
const std::list<std::string> fields; // list of fields to be output (may be a subset of the fields actually present in m)
const Params &P;
void field_numbers() { // Consecutive numbers for the columns
F << '#' << formatted_output(1, P) << ' ';
for (const auto ctr : range1(fields.size())) F << formatted_output(1 + ctr, P) << ' ';
F << std::endl;
}
// Label and field names. Label is the first column (typically the temperature).
void field_names(const std::string &labelname = "T") {
F << '#' << formatted_output(labelname, P) << ' ';
std::transform(fields.cbegin(), fields.cend(), std::ostream_iterator<std::string>(F, " "), [this](const auto op) { return formatted_output(op, P); });
F << std::endl;
}
public:
// Output the current values for the label and for all the fields
void field_values(const double labelvalue, const bool cout_dump = true) {
F << ' ' << formatted_output(labelvalue, P) << ' ';
std::transform(fields.cbegin(), fields.cend(), std::ostream_iterator<std::string>(F, " "), [this](const auto op) { return formatted_output(m[op], P); }); // NOTE: only real part stored
F << std::endl;
if (cout_dump)
for (const auto &op: fields)
color_print(P.pretty_out, fmt::emphasis::bold | fg(fmt::color::red), "<{}>={}\n", op, formatted_output(m[op], P)); // NOTE: real and imaginary part shown
}
ExpvOutput(const std::string &fn, std::map<std::string, t_expv> &m,
std::list<std::string> fields, const Params &P) : m(m), fields(std::move(fields)), P(P) {
F.open(fn);
field_numbers();
field_names();
}
};
// Store eigenvalue & quantum numbers information (RG flow diagrams)
class Annotated {
private:
std::ofstream F;
// scaled = true -> output scaled energies (i.e. do not multiply by the rescale factor)
template<typename T, scalar S>
inline auto scaled_energy(const T e, const Step &step, const Stats<S> &stats,
const bool scaled = true, const bool absolute = false) {
return e * (scaled ? 1.0 : step.scale()) + (absolute ? stats.total_energy : 0.0);
}
const Params &P;
public:
explicit Annotated(const Params &P) : P(P) {}
template<scalar S, typename MF>
void dump(const Step &step, const DiagInfo<S> &diag, const Stats<S> &stats,
MF mult, const std::string &filename = "annotated.dat") {
if (!P.dumpannotated) return;
if (!F.is_open()) { // open output file
F.open(filename);
F << std::setprecision(P.dumpprecision);
}
std::vector<std::pair<double, Invar>> seznam;
for (const auto &[I, eig] : diag)
for (const auto e : eig.values.all_rel_zero())
seznam.emplace_back(e, I);
ranges::sort(seznam);
size_t len = std::min<size_t>(seznam.size(), P.dumpannotated); // non-const
// If states are clustered, we dump the full cluster
while (len < seznam.size()-1 && my_fcmp(seznam[len].first, seznam[len-1].first, P.grouptol) == 0) len++;
const auto scale = [&step, &stats, this](auto x) { return scaled_energy(x, step, stats, P.dumpscaled, P.dumpabs); };
if (P.dumpgroups) {
// Group by degeneracies
for (size_t i = 0; i < len;) { // i increased in the while loop below
const auto [e0, I0] = seznam[i];
F << scale(e0);
std::vector<std::string> QNstrings;
size_t total_degeneracy = 0; // Total number of levels (incl multiplicity)
while (i < len && my_fcmp(seznam[i].first, e0, P.grouptol) == 0) {
const auto [e, I] = seznam[i];
QNstrings.push_back(to_string(I));
total_degeneracy += mult(I);
i++;
}
ranges::sort(QNstrings);
for (const auto &j : QNstrings) F << " (" << j << ")";
F << " [" << total_degeneracy << "]" << std::endl;
}
} else {
seznam.resize(len); // truncate!
for (const auto &[e, I] : seznam)
F << scale(e) << " " << I << std::endl;
}
F << std::endl; // Consecutive iterations are separated by an empty line
}
};
template<scalar S>
auto singlet_operators_for_expv_evaluation(const Operators<S> &operators)
{
std::list<std::string> ops;
for (const auto &name : operators.ops | boost::adaptors::map_keys) ops.push_back(name);
for (const auto &name : operators.opsg | boost::adaptors::map_keys) ops.push_back(name);
return ops;
}
// Handle all output
template<scalar S>
struct Output {
const RUNTYPE runtype;
const Params &P;
Annotated annotated;
std::ofstream Fenergies; // all energies (different file for NRG and for DMNRG)
std::unique_ptr<ExpvOutput<S>> custom;
std::unique_ptr<ExpvOutput<S>> customfdm;
std::unique_ptr<H5Easy::File> h5raw;
Output(const RUNTYPE &runtype, const Operators<S> &operators, Stats<S> &stats, const Params &P,
const std::string filename_energies= "energies.nrg"s,
const std::string filename_custom = "custom",
const std::string filename_customfdm = "customfdm")
: runtype(runtype), P(P), annotated(P)
{
if (P.dumpenergies && runtype == RUNTYPE::NRG) Fenergies.open(filename_energies);
const auto ops = singlet_operators_for_expv_evaluation(operators);
if (runtype == RUNTYPE::NRG)
custom = std::make_unique<ExpvOutput<S>>(filename_custom, stats.expv, ops, P);
else if (runtype == RUNTYPE::DMNRG && P.fdmexpv)
customfdm = std::make_unique<ExpvOutput<S>>(filename_customfdm, stats.fdmexpv, ops, P);
if (P.h5raw) {
const auto filename_h5 = runtype == RUNTYPE::NRG ? "raw.h5" : "raw-dm.h5";
h5raw = std::make_unique<H5Easy::File>(filename_h5, H5Easy::File::Overwrite);
P.h5save(*h5raw);
}
}
// Dump eigenvalues from the diagonalisation to a file.
void dump_energies(const int N, const DiagInfo<S> &diag) {
if (!Fenergies) return;
Fenergies << std::endl << "===== Iteration number: " << N << std::endl;
diag.dump_energies(Fenergies);
}
};
} // namespace
#endif
| 6,816
|
C++
|
.h
| 157
| 38.248408
| 189
| 0.634231
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,627
|
spectral.hpp
|
rokzitko_nrgljubljana/c++/spectral.hpp
|
// spectral.h - Code for handling spectral function data
// Copyright (C) 2005-2020 Rok Zitko
#ifndef _spectral_hpp_
#define _spectral_hpp_
#include <utility>
#include <vector>
#include <cmath>
#include <limits> // quiet_NaN
#include <range/v3/all.hpp>
#include "traits.hpp"
#include "io.hpp"
namespace NRG {
// Container for holding spectral information represented by delta peaks. "Weight" is of type t_weight (complex).
template<scalar S>
using t_delta_peak = std::pair<double, weight_traits<S>>;
template<scalar S, typename t_weight = weight_traits<S>>
class Spikes : public std::vector<t_delta_peak<S>> {
public:
template<typename T>
void save(T&& F, const int prec, const bool imagpart) {
F << std::setprecision(prec);
for (const auto &[e, w] : *this) outputxy(F, e, w, imagpart);
}
[[nodiscard]] auto sum_weights() const { return sum2(*this); }
template<typename F>
[[nodiscard]] auto sum(const bool invert, F && f) const {
return ranges::accumulate(*this, t_weight{}, {}, [&f,invert](const auto &x){ const auto &[e,w] = x; return w*f(invert ? -e : e); });
}
};
#ifndef M_SQRTPI
#define M_SQRTPI 1.7724538509055160273
#endif
// cf. A. Weichselbaum and J. von Delft, cond-mat/0607497
// Modified log-Gaussian broadening kernel. For gamma=alpha/4, the
// kernel is symmetric in both arguments.
inline double BR_L(double e, double ept, double alpha) {
if ((e < 0.0 && ept > 0.0) || (e > 0.0 && ept < 0.0)) return 0.0;
if (ept == 0.0) return 0.0;
const double gamma = alpha/4.0;
return exp(-pow(log(e / ept) / alpha - gamma, 2)) / (alpha * abs(e) * M_SQRTPI);
}
// Normalized to 1, width omega0. The kernel is symmetric in both
// arguments.
inline double BR_G(double e, double ept, double omega0) { return exp(-pow((e - ept) / omega0, 2)) / (omega0 * M_SQRTPI); }
// Note: 'ept' is the energy of the delta peak in the raw spectrum,
// 'e' is the energy of the data point in the broadened spectrum.
inline double BR_NEW(double e, double ept, double alpha, double omega0) {
double part_l = BR_L(e, ept, alpha);
// Most of the time we only need to compute part_l (loggaussian)
if (abs(e) > omega0) return part_l;
// Note: this is DIFFERENT from the broadening kernel proposed by
// by Weichselbaum et al. This BR_h is a function of 'e', not
// of 'ept'! This breaks the normalization at finite temperatures.
// On the other hand, it gives nicer spectra when used in conjunction
// with the self-energy trick.
double BR_h = exp(-pow(log(abs(e) / omega0) / alpha, 2));
my_assert(BR_h >= 0.0 && BR_h <= 1.0);
return part_l * BR_h + BR_G(e, ept, omega0) * (1.0 - BR_h);
}
// Calculate "moment"-th spectral moment.
template<scalar S, typename t_weight = weight_traits<S>>
auto moment(const Spikes<S> &s_neg, const Spikes<S> &s_pos, const int moment) {
auto sumA = ranges::accumulate(s_pos, t_weight{}, {}, [moment](const auto &x){ const auto &[e,w] = x; return w*pow(e,moment); });
auto sumB = ranges::accumulate(s_neg, t_weight{}, {}, [moment](const auto &x){ const auto &[e,w] = x; return w*pow(-e,moment); });
return sumA+sumB;
}
inline constexpr double fermi_fnc(const double omega, const double T) {
return 1 / (1 + exp(-omega / T));
}
inline constexpr double bose_fnc(const double omega, const double T) {
const auto d = 1.0 - exp(-omega / T);
return d != 0.0 ? 1.0/d : std::numeric_limits<double>::quiet_NaN();
}
// Integrated spectral function with a kernel as in FDT for fermions
template<scalar S>
auto fd_fermi(const Spikes<S> &s_neg, const Spikes<S> &s_pos, const double T) {
const auto fnc = [T](const auto x) { return fermi_fnc(x, T); };
return s_neg.sum(true, fnc) + s_pos.sum(false, fnc);
}
// Ditto for bosons
template<scalar S>
auto fd_bose(const Spikes<S> &s_neg, const Spikes<S> &s_pos, const double T) {
const auto fnc = [T](const auto x) { return bose_fnc(x, T); };
return s_neg.sum(true, fnc) + s_pos.sum(false, fnc);
}
} // namespace
#endif // _spectral_hpp_
| 3,999
|
C++
|
.h
| 87
| 43.586207
| 139
| 0.67737
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,628
|
params.hpp
|
rokzitko_nrgljubljana/c++/params.hpp
|
// param.cc - Parameter parsing
// Copyright (C) 2009-2022 Rok Zitko
#ifndef _param_hpp_
#define _param_hpp_
#include <utility>
#include <list>
#include <string>
#include <stdexcept>
#include <cmath>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <fmt/format.h>
#include "misc.hpp" // contains, from_string, is_stdout_redirected, parsing code
#include "workdir.hpp"
#include "h5.hpp"
namespace NRG {
using namespace std::string_literals;
enum class RUNTYPE { NRG, DMNRG }; // First or second sweep? Used in class Step.
inline const auto fn_rho {"rho"s};
inline const auto fn_rhoFDM {"rhofdm"s};
// Base class for parameter containers
// XXX C++20: std::string may be constexpr
class parambase {
protected:
std::string keyword;
std::string desc;
public:
parambase(const std::string &keyword, const std::string &desc) : keyword(keyword), desc(desc) {};
virtual ~parambase() = default;
virtual void set_str(const std::string &new_value) = 0;
virtual void dump(std::ostream &F = std::cout) = 0;
virtual void h5save(H5Easy::File &file, std::string path) = 0;
[[nodiscard]] auto getkeyword() const noexcept { return keyword; }
[[nodiscard]] auto getdesc() const noexcept { return desc; }
};
// Templated specialized classes for various storage types (int, double, string, bool)
template <typename T>
class param : public parambase {
private:
T data;
bool is_default = true;
public:
// Constructor: keyword is a CASE SENSITIVE name of the parameter, desc is at this time used as in-line
// documentation and default_value is a string containing a default value which is immediately parsed.
// allparams is the list of all parameters.
param(const std::string &keyword, const std::string &desc, const std::string &default_value, std::list<parambase*> &allparams) :
parambase(keyword, desc) {
data = from_string<T>(default_value);
for (const auto &i : allparams)
if (i->getkeyword() == keyword) throw std::runtime_error("param class internal error: keyword conflict.");
allparams.push_back(this);
}
void dump(std::ostream &F = std::cout) override {
F << keyword << "=" << data << (!is_default ? " *" : "") << std::endl;
}
void h5save(H5Easy::File &file, std::string path) override {
h5_dump_scalar(file, path + "/" + keyword, data);
}
// This line enables to access parameters using an object as a rvalue
[[nodiscard]] inline operator const T &() const noexcept { return data; }
[[nodiscard]] inline T value() const noexcept { return data; }
void set_str(const std::string &new_value) override { // used in parser
data = from_string<T>(new_value);
is_default = false;
}
param & operator= (const T newdata) noexcept { data = newdata; return *this; }
[[nodiscard]] bool operator== (const T &b) const noexcept { return data == b; }
};
// CONVENTION: parameters that are user configurable are declared as param<T>, other parameters (set at runtime) are
// defined as basic types T.
// Interfacing:
// S = solver, C = constructor, L = low-level, * = hide (deprecated & experimental)
// //! lines define parameters that are only used in the high-level interface
class Params {
private:
std::list<parambase *> all; // Container for all parameters
public:
std::unique_ptr<Workdir> workdir;
param<std::string> symtype{"symtype", "Symmetry type", "", all}; // S
// *************************************************************
// Parameters controlling discretization scheme and Wilson chain
param<double> Lambda{"Lambda", "Logarithmic discretization parameter", "2.0", all}; // S
// Discretization scheme: Y)oshida-Whitaker-Oliveira, C)ampo-Oliveira, Z)itko-Pruschke
param<std::string> discretization{"discretization", "Discretization scheme", "Z", all}; // N
// Twist parameter for the mesh. See Yoshida, Whitaker, Oliveira PRB 41 9403 1990
param<double> z{"z", "Parameter z in the logarithmic discretization", "1.0", all}; // N
//! param<int> Nz {"Nz", "Number of discretization meshes", "1", all}; // S
//! param<double> xmax {"xmax", "Largest x in discretization ODE solver", "20", all}; // S
// Support of the hybridisation function, [-bandrescale:bandrescale]. The automatic rescaling is implemented as
// follows: 1. The spectral function is rescaled on the x-axis by 1/bandrescale and on the y-axis by bandrescale.
// 2. The Wilson chain coefficients are scaled by bandrescale. 3. In the data file, all eigenvalues are reduced by
// the factor of bandrescale. 4. In the NRG code, the current scale is multiplied by bandrescale in function
// SCALE(N).
param<double> bandrescale{"bandrescale", "Band rescaling factor", "1.0", all}; // C
// If polarized=true, the Wilson chain depends on the spin.
param<bool> polarized{"polarized", "Spin-polarized Wilson chain", "false", all}; // N
// If pol2x2=true for symtype=U1, the hybridisation function (and
// thus Wilson chain) depends on two spin indexes, i.e., it is
// described by a full 2x2 matrix in the spin space.
param<bool> pol2x2{"pol2x2", "2x2 spin structure in Wilson chain", "false", all}; // N
// Support for channel-mixing terms in the Wilson chain
// (implemented for QS and QSZ symmetry types)
param<bool> rungs{"rungs", "Channel-mixing terms in Wilson chain", "false", all}; // N
// Length of the Wilson chain. The number of iterations ise determined either by Nmax or, if Tmin>0, by the lowest
// temperature(=energy) scale still considered, Tmin. In other words, if Tmin>0, the parameter Nmax is recomputed
// so that T at the Nmax-th iteration is equal or higher than the minimal temperature Tmin. NOTE: step.ndxN runs
// from 0 to Nmax-1 (including), while the Wilson chain coefficient indexes run from 0 to Nmax (due to the
// inclusion of the zero-th site of the Wilson chain).
size_t Nmax = 0; // 0 means non-initialized.
//! param<double> Tmin {"Tmin", "Lowest scale on the Wilson chain", "1e-4", all}; // S
// If tri=cpp, we do the tridiagonalisation in the C++ part of the
// code. In other cases,. we make use of external tools or Mathematica.
param<std::string> tri{"tri", "Tridiagonalisation approach", "old", all}; // N
param<size_t> preccpp{"preccpp", "Precision for tridiagonalisation", "2000", all}; // N
// ************************
// NRG iteration parameters
param<std::string> diag{"diag", "Eigensolver routine (dsyev|dsyevd|dsyevr|zheev|zheevr|default)", "default", all}; // N
// For partial diagonalisation routines (dsyevr, zheevr), diagratio controls the fraction
// of eigenspectrum that we compute.
param<double> diagratio{"diagratio", "Ratio of eigenstates computed in partial diagonalisation", "1.0", all}; // N
// If an insufficient number of states is computed during an
// iteration with partial diagonalisations, diagratio can be
// increased by a factor of restartfactor and calculation restarted
// if restart=true.
param<bool> restart{"restart", "Restart calculation to achieve truncation goal?", "true", all}; // N
param<double> restartfactor{"restartfactor", "Rescale factor for restart=true", "2.0", all}; // N
// Truncation parameters. If keepenergy>0.0, then the cut-off
// energy truncation scheme will be used. Parameter 'keep' is then
// used to cap the maximum number of states. If 'keepmin' is set to
// a positive value, it will ensure that a chosen minimal number of
// states is always kept.
param<size_t> keep{"keep", "Maximum number of states to keep at each step", "100", all}; // S
param<double> keepenergy{"keepenergy", "Cut-off energy for truncation", "-1.0", all}; // S
param<size_t> keepmin{"keepmin", "Minimum number of states to keep at each step", "0", all}; // S
param<std::string> keepall{"keepall", "Keep all states at certain iterations", "", all};
// Safeguard feature: keep more states in case of a near degeneracy
// near the truncation cutoff. This prevents to truncate in the
// middle of a (near-)degenerate cluster of states, leading to
// unphysical effects. Disabled if set to 0, otherwise keeps states
// that differ at most by P.safeguard.
param<double> safeguard{"safeguard", "Additional states to keep in case of a near degeneracy", "1e-5", all}; // N
param<size_t> safeguardmax{"safeguardmax", "Maximal number of additional states", "200", all}; // N
// Fix artificial splitting of states due to floating point
// round-off. Note that the use of this feature with large value of
// epsilon may be dangerous. (The default conservative value of
// 1e-15 cures differences in the 2-3 least significant bits.)
param<double> fixeps{"fixeps", "Threshold value for eigenvalue splitting corrections", "1e-15", all}; // N
// ******************************************************
// Physical temperature for finite-temperature quantities
param<double> T{"T", "Temperature, k_B T/D,", "0.001", all}; // S
// \bar{\beta}, defines the effective temperature for computing the
// thermodynamic quantities at iteration N. See Krishna-Murthy,
// page 1009. The default value is 1.0, which is somewhat large,
// but it is a safer default compared to 0.46 that requires large
// truncation cutoff energy to obtain converged results.
param<double> betabar{"betabar", "Parameter \bar{\beta} for thermodynamics", "1.0", all}; // N
// *************************************************************
// Parameters controlling the problem and quantities of interest
//! param<std::string> problem {"problem", "Model considered (templated)", "SIAM", all}; // C
// List of operators being considered
param<std::string> ops{"ops", "Operators to be calculated", "", all}; // S
// Dynamical quantities of interest
param<std::string> specs{"specs", "Spectral functions (singlet ops) to compute", "", all}; // S
param<std::string> specd{"specd", "Spectral functions (doublet ops) to compute", "", all}; // S
param<std::string> spect{"spect", "Spectral functions (triplet ops) to compute", "", all}; // S
param<std::string> specq{"specq", "Spectral functions (quadruplet ops) to compute", "", all}; // S
param<std::string> specot{"specot", "Spectral functions (orbital triplet ops) to compute", "", all}; // S
// Calculation of the temperature-dependent conductance G(T) &
// first and second moment of A(w)(-df/dw), which are related to
// the thermopower and the heat conductance.
param<std::string> specgt{"specgt", "Conductance curves to compute", "", all}; // S
param<std::string> speci1t{"speci1t", "I_1 curves to compute", "", all}; // S
param<std::string> speci2t{"speci2t", "I_2 curves to compute", "", all}; // S
param<double> gtp{"gtp", "Parameter p for G(T) calculations", "0.7", all}; // N
// Calculation of the temperature-depenedent susceptibility chi(T)
param<std::string> specchit{"specchit", "Susceptibilities to compute", "", all}; // S
param<double> chitp{"chitp", "Parameter p for chi(T) calculations", "1.0", all}; // N
// If chitp_ratio>0, chitp=chitp_ratio/betabar.
param<double> chitp_ratio{"chitp_ratio", "Determine p from betabar", "-999", all}; // *
// **************
// NRG algorithms
// Calculate finite-temperature spectral functions using Costi,
// Hewson, Zlastic approach.
param<bool> finite{"finite", "Perform Costi-Hewson-Zlatic finite-T calculation", "false", all}; // N
// Perform DMNRG spectral function calculation. W. Hofstetter,
// Phys. Rev. Lett. 85, 1508 (2000).
param<bool> dmnrg{"dmnrg", "Perform DMNRG (density-matrix NRG) calculation", "false", all}; // S
// Perform complete-Fock-space calculation. R. Peters, T. Pruschke,
// F. B. Anders, Phys. Rev. B 74, 245113 (2006)
param<bool> cfs{"cfs", "Perform CFS (complete Fock space) calculation", "false", all}; // S
// Support for calculating greater and lesser correlation functions
param<bool> cfsgt{"cfsgt", "CFS greater correlation function", "false", all}; // N
param<bool> cfsls{"cfsls", "CFS lesser correlation function", "false", all}; // N
// Perform full-density-matrix NRG calculation. Weichselbaum, J. von Delft, PRL 99 076402 (2007).
param<bool> fdm{"fdm", "Perform FDM (full-density-matrix) calculation", "false", all}; // S
// Support for calculating greater and lesser correlation functions
param<bool> fdmgt{"fdmgt", "FDM greater correlation function?", "false", all}; // N
param<bool> fdmls{"fdmls", "FDM lesser correlation function?", "false", all}; // N
// Calculate the expectation value <O>(T) using the FDM algorithm.
param<bool> fdmexpv{"fdmexpv", "Calculate expectation values using FDM", "false", all}; // S
param<size_t> fdmexpvn{"fdmexpvn", "Iteration where we evaluate expv", "0", all}; // N
// Dynamical quantity calculations on the Mastubara axis
param<bool> finitemats{"finitemats", "T>0 calculation on Matsubara axis", "false", all}; // N
param<bool> dmnrgmats{"dmnrgmats", "DMNRG calculation on Matsubara axis", "false", all}; // S
param<bool> fdmmats{"fdmmats", "FDM calculation on Matsubara axis", "false", all}; // S
param<size_t> mats{"mats", "Number of Matsubara points to collect", "100", all}; // S
// If dm is set to true, density matrices are computed.
// Automatically enabled when needed (DMNRG, CFS, FDM).
param<bool> dm{"dm", "Compute density matrixes?", "false", all}; // N
// **************
// Frequency mesh
param<double> broaden_max{"broaden_max", "Broadening mesh maximum frequency", "10", all}; // N
param<double> broaden_min{"broaden_min", "Broadening mesh minimum frequency", "-99.", all}; // N
param<double> broaden_min_ratio{"broaden_min_ratio", "Auto-tune broaden_min parameter", "3.0", all}; // N
param<double> broaden_ratio{"broaden_ratio", "Common ration of the geometric sequence", "1.05", all}; // N
//! param<double> mesh_max {"mesh_max", "Mesh maximum frequency", "10", all}; // C
//! param<double> mesh_min {"mesh_min", "Mesh minimum frequency", "1e-4", all}; // C
//! param<double> mesh_ratio {"mesh_ratio", "Common ratio of the geometric sequence", "1.05", all}; // C
// Broadening parameters. cf. cond-mat/0607497
param<double> alpha{"alpha", "Width of logarithmic gaussian", "0.3", all}; // S
param<double> omega0{"omega0", "Smallest energy scale in the problem", "-1.0", all}; // N
param<double> omega0_ratio{"omega0_ratio", "omega0 = omega0_ratio x T", "1.0", all}; // N
//! param<double> gamma {"gamma", "Parameter for Gaussian convolution step", "0.2", all}; // S
// ******************************************************
// Parameters for fine-grained control of NRG calculation
// Number of concurrent threads for matrix diagonalisation
param<int> diagth{"diagth", "Diagonalisation threads", "1", all}; // N
// Interleaved diagonalization
param<bool> substeps{"substeps", "Interleaved diagonalization", "false", all}; // N
// For "strategy=all", we recompute for the next iteration the
// matrix elements corresponding to all eigenpairs computed in the
// diagonalization step. For "strategy=kept", we only recompute
// those matrix elements that are actually required in the next
// iteration, i.e. those that correspond to the eigenpairs that we
// keep after truncation. Note 1: using "strategy=kept" also
// affects the calculation of thermodynamic and dynamic quantities
// (in non-CFS algorithms), since the sum over all combinations of
// states is correspondingly truncated. However, since due to the
// gain in efficiency with "strategy=kept" we can increase the
// number of states taken into account, this can be easily
// compensated since the contributions are weighted with
// exponentially decreasing Boltzmann factors. Note 2: for CFS/FDM
// calculations, where all eigenpairs need to be recalculated, the
// strategy is automatically switched to "all"!
param<std::string> strategy{"strategy", "Recalculation strategy", "kept", all}; // N
// It is possible to include more than the zero-th site in the
// initial Wilson chain. This is controlled by parameter Ninit,
// which is equal to the last f operator index still retained.
// Ninit < Nmax.
param<size_t> Ninit{"Ninit", "Initial Wilson chain ops", "0", all}; // N
// Output real and imaginary parts of calculated correlators (specs).
param<bool> reim{"reim", "Output imaginary parts of correlators?", "false", all}; // N
// Number of eigenstates to save in "annotated.dat" per iteration.
// Use dumpabs=true together with dumpscaled=false to trace total
// energies of excitations.
param<size_t> dumpannotated{"dumpannotated", "Number of eigenvalues to dump", "0", all}; // N
param<bool> dumpabs{"dumpabs", "Dump in terms of absolute energies", "false", all}; // N
param<bool> dumpscaled{"dumpscaled", "Dump using omega_N energy units", "true", all}; // N
param<size_t> dumpprecision{"dumpprecision", "Dump with # digits of precision", "8", all}; // N
param<bool> dumpgroups{"dumpgroups", "Dump by grouping degenerate states", "true", all}; // N
param<double> grouptol{"grouptol", "Energy tolerance for considering two states as degenerate", "1e-6", all}; // N
// Dump diagonal matrix elements of singlet operators. This is
// particularly useful in the presence of the gap, where the matrix
// elements are different in the long-chain limit. "dumpdiagonal"
// matrix elements are saved for each singlet operator. The output
// goes to the standard output.
param<size_t> dumpdiagonal{"dumpdiagonal", "Dump diagonal matrix elements", "0", all}; // N
// ********************
// Binning & broadening
param<bool> savebins{"savebins", "Save binned (unbroadened) data", "false", all}; // N
param<bool> broaden{"broaden", "Enable broadening of spectra", "true", all}; // N
// Overrides for the binning interval limits
param<double> emin{"emin", "Lower binning limit", "-1.0", all}; // N
param<double> emax{"emax", "Upper binning limit", "-1.0", all}; // N
// Number of bins per energy decade for accumulating spectral data
param<size_t> bins{"bins", "bins/decade for spectral data", "1000", all}; // N
// If P.accumulation != 0, the accumulation point of the
// logarithmic mesh will be shifted away from omega=0. This may be
// used in superconducting cases to get good spectral resolution
// near the gap edges (cf. T. Hecht et al, JPCM).
param<double> accumulation{"accumulation", "Shift of the accumulation points for binning", "0.0", all}; // N
// If P.linstep != 0 (and P.accumulation != 0), a linear mesh
// will be used in the interval [-accumulation:accumulation]. This
// may be used to properly resolve the sub-gap peaks (Shiba bound
// states or resonances).
param<double> linstep{"linstep", "Bin width for linear mesh", "0", all}; // N
// *************
// Peak trimming
// DISCARD_TRIM is relative value wrt "interval width" between
// consecutive "bins". A "bin" is trimmed away if its weight is
// less than (energy_bin(this)-energy_bin(next))*DISCARD_TRIM. This
// is consistent with the fact that spectral density is spectral
// weight per interval.
param<double> discard_trim{"discard_trim", "Peak clipping at the end of the run", "1e-16", all}; // N
// DISCARD_IMMEDIATELY is relative value wrt peak energy: we clip
// if peak's weight is lower than energy*DISCARD_IMMEDIATELY.
param<double> discard_immediately{"discard_immediately", "Peak clipping on the fly", "1e-16", all}; // N
// ********
// Patching
// Parameter that controls the N/N+n patching schemes in non-FDM algorithms
param<double> goodE{"goodE", "Energy window parameter for patching", "2.0", all}; // N
// Do N/N+1 patching, rather than N/N+2 which is the default
param<bool> NN1{"NN1", "Do N/N+1 patching?", "false", all}; // N
// In N/N+2 patching we can use the information from even
// iterations (NN2even=true, which is the default) or from odd
// iterations (NN2even=false).
param<bool> NN2even{"NN2even", "Use even iterations in N/N+2 patching", "true", all}; // N
// NN2avg=true is equivalent to averaging results from a
// NN2even=true and a NN2even=false calculations.
param<bool> NN2avg{"NN2avg", "Average over even and odd N/N+2 spectra", "false", all}; // N
// If NNtanh > 0, tanh window function is used instead of linear
// (i.e. a smooth heap instead of a triangle).
param<double> NNtanh{"NNtanh", "a in tanh[a(x-0.5)] window function", "0.0", all}; // N
// **************************
// Formatting of output files
param<int> width_td{"width_td", "Widht of columns in 'td'", "16", all}; // N
param<int> width_custom{"width_custom", "Width of columns in 'custom'", "16", all}; // N
param<int> prec_td{"prec_td", "Precision of columns in 'td'", "10", all}; // N
param<int> prec_custom{"prec_custom", "Precision of columns in 'custom'", "10", all}; // N
param<int> prec_xy{"prec_xy", "Precision of spectral function output", "10", all}; // N
// Checkpoint-restart functionality. Attempt to restart calculation
// by reading the "unitary*" files from a previous calculation.
// Automatically determines the number of files.
param<bool> resume{"resume", "Attempt restart?", "false", all}; // N
std::optional<size_t> laststored; // has value if stored data is found
/* Fine-grained control over data logging with the following tokens:
i - iteration (subspaces list)
s - dump ancestor subspaces during Hamiltonian matrix building
m - dump Hamiltonian matrix of each subspace [very verbose!]
H - details about storing unitary matrices to files
f - follow recalc_f() [low-level]
F - matrix elements in recalc_f() [very verbose!]
0 - functions calls in recalculations, etc. [high-level]
r - follow recalc_general() [low-level]
R - matrix elements in recalc_general() [very verbose!]
g - follow calc_generic() [low-level]
c - details about spectral function calculation [high-level]
A - eigensolver diagnostics (routine used, matrix size)
t - timing for eigensolver routines
e - dump eigenvalues in function diagonalize_h()
d - eigenvalue computation [low-level]
T - spectral peak trimming statistics
* - merging details
w - calculation of weights w_n
X - show energy clusters in find_clusters()
$ - Hamiltonian matrix sorting diagnostics
M - MPI parallelization details
! - debug internal variables
D - DMNRG calculation details
@ - follow the program flow
Z - report the values of different partition functions
Useful combinations:
fr - debug recalculation of irreducible matrix elements <||f||>
ies - debug matrix construction and diagonalization
*/
param<std::string> logstr{"log", "list of tokens to define what to log", "", all}; // N
param<bool> logall{"logall", "Log everything", "false", all}; // N
// Returns true if option 'c' is selected for logging
auto logletter(const char c) const { return logall ? true : contains(logstr, c); }
// ********************************************
// Parameters where overrides are rarely needed
param<bool> done{"done", "Create DONE file?", "true", all}; // N
param<bool> calc0{"calc0", "Perform calculations at 0-th iteration?", "true", all}; // N
// If only dmnrg is enabled, setting lastall=true will force "keeping" all states in the last step and the density
// matrix will be initialized with all the states. Note that by default this feature is disabled, which is
// especially appropriate for T->0 calculations.
param<bool> lastall{"lastall", "Keep all states in the last iteratio for DMNRG", "false", all}; // N
// If lastalloverride=true, then "lastall" is not set to true automatically for full-Fock-space (CFS and FDM)
// approaches.
param<bool> lastalloverride{"lastalloverride", "Override automatic lastall setting", "false", all}; // N
// ******************************************************************
// Parameters mostly relevant for low-level debugging and RG analysis
// Store information about subspaces (total, calculated and kept states).
param<bool> dumpsubspaces{"dumpsubspaces", "Save detailed subspace info", "false", all}; // N
// Enable dumps of the matrix elements of <f> channel by channel,
// subspace pair by subspace pair.
param<bool> dump_f{"dump_f", "Dump <f> matrix elements", "false", all}; // N
param<bool> dumpenergies{"dumpenergies", "Dump (all) energies to file?", "false", all}; // N
param<bool> dumpabsenergies{"dumpabsenergies", "Dump (all) absolute energies to file?", "false", all}; // N - new
// If set to false, the unitary transformation matrix and density
// matrix files are kept after the calculation.
param<bool> removefiles{"removefiles", "Remove temporary data files?", "true", all}; // N
param<bool> checksumrules{"checksumrules", "Check operator sumrules", "false", all}; // N
param<bool> absolute{"absolute", "Do NRG without any rescaling", "false", all};
// Parallelization strategy: MPI, OpenMP or serial
param<std::string> diag_mode{"diag_mode", "Parallelization strategy", "MPI", all};
param<bool> h5raw{"h5raw", "Store raw data in an HDF5 file", "false", all};
param<bool> h5all{"h5all", "Store raw data at all steps", "false", all};
param<bool> h5last{"h5last", "Store raw data at last step", "true", all};
param<bool> h5ham{"h5ham", "Store Hamiltonian matrices", "false", all};
param<bool> h5ops{"h5ops", "Store operator matrices", "false", all};
param<bool> h5vectors{"h5vectors", "Store eigenvectors", "false", all};
param<bool> h5U{"h5U", "Store eigenvectors U", "false", all};
param<bool> h5struct{"h5struct", "Store relations between subspaces", "false", all};
param<std::string> project{"project", "Project the states before taking measurements", "", all};
// **********************************
// Backwards compatibility parameters
param<bool> data_has_rescaled_energies{"data_has_rescaled_energies", "Rescaled eigenvalues?", "true", all};
// **************************************************
// Internal parameters, not under direct user control
bool pretty_out; // If true, produce color output using the {fmt} library.
bool embedded; // If true, the code is being called as a library from some application, not stand-alone.
size_t channels = 0; // Number of channels
size_t coeffactor = 0; // coefchannels = coeffactor * channels (typically coeffactor=1)
size_t coefchannels = 0; // Number of coefficient sets (typically coefchannels=channels)
size_t perchannel = 0; // f-matrices per channel (typically 1)
size_t combs = 0; // dimension of new shell Hilbert space, 4 for single-channel, 16 for two-channel, etc.
size_t Nlen = 0; // Nlen=Nmax for regular calculations. Nlen=1 for ZBW. Length of wn, wnfactor, ZnD and dm vectors.
[[nodiscard]] bool ZBW() const noexcept { return Nmax == Ninit; } // Zero-bandwidth calculation
// Spin expressed in terms of the spin multiplicity, 2S+1. For SL & SL 3 symmetry types, P.spin is 1. Default value
// of 2 is valid for all other symmetry types.
size_t spin = 2;
// Sets 'channels', then sets 'combs' and related parameters accordingly, depending on the spin of the conduction
// band electrons. Called from read_data() in read-input.hpp
void set_channels_and_combs(const int channels_) {
my_assert(channels_ >= 1);
channels = channels_;
// Number of tables of coefficients. It is doubled in the case of spin-polarized conduction bands. The first half
// corresponds to spin-up, the second half to spin-down. It is quadrupled in the case of full 2x2 matrix structure
// in the spin space.
if (pol2x2)
coeffactor = 4;
else if (polarized)
coeffactor = 2;
else
coeffactor = 1;
coefchannels = coeffactor * channels;
if (symtype == "U1" || symtype == "SU2" || symtype == "DBLSU2") {
perchannel = 2; // We distinguish spin-up and spin-down operators.
} else if (symtype == "NONE" || symtype == "P" || symtype == "PP") {
perchannel = 4; // We distinguish CR/AN and spin UP/DO.
} else {
perchannel = 1;
}
my_assert(perchannel >= 1);
spin = symtype == "SL" || symtype == "SL3" ? 1 : 2;
const auto statespersite = intpow(2, spin);
combs = !substeps ? intpow(statespersite, channels) : statespersite;
if (logletter('!'))
fmt::print("coefchannels={} perchannel={} combs={}", coefchannels, perchannel, combs);
}
bool cfs_flags() const noexcept { return cfs || cfsgt || cfsls; }
bool fdm_flags() const noexcept { return fdm || fdmgt || fdmls || fdmmats || fdmexpv; }
bool dmnrg_flags() const noexcept { return dmnrg || dmnrgmats; }
bool cfs_or_fdm_flags() const noexcept { return cfs_flags() || fdm_flags(); }
bool dm_flags() const noexcept { return cfs_flags() || fdm_flags() || dmnrg_flags(); }
bool keep_all_states_in_last_step() const noexcept { return lastall || (cfs_or_fdm_flags() && !lastalloverride); }
bool need_rho() const noexcept { return cfs_flags() || dmnrg_flags(); }
bool need_rhoFDM() const noexcept { return fdm_flags(); }
bool do_recalc_kept(const RUNTYPE &runtype) const noexcept { // kept: Recalculate using vectors kept after truncation
return strategy == "kept" && !(cfs_or_fdm_flags() && runtype == RUNTYPE::DMNRG) && !ZBW();
}
bool do_recalc_all(const RUNTYPE &runtype) const noexcept { // all: Recalculate using all vectors
return !do_recalc_kept(runtype) && !ZBW();
}
bool do_recalc_none() const noexcept { return ZBW(); }
// What is the last iteration completed in the previous NRG runs?
void init_laststored() {
if (resume) {
laststored = std::nullopt;
for (size_t N = Ninit; N < Nmax; N++) {
const std::string fn = workdir->unitaryfn(N);
std::ifstream F(fn);
if (F.good())
laststored = N;
}
if (laststored.has_value())
std::cout << "Last unitary file found: " << laststored.value() << std::endl;
else
std::cout << "No unitary files found." << std::endl;
}
}
void validate() {
my_assert(keep > 1);
if (keepenergy > 0.0) my_assert(keepmin <= keep);
if (dm_flags()) dm = true;
my_assert(Lambda > 1.0);
if (diag == "dsyevr"s || diag =="zheevr"s) {
my_assert(0.0 < diagratio && diagratio <= 1.0);
if (cfs_flags() && diagratio != 1.0) throw std::invalid_argument("CFS/FDM is not compatible with partial diagonalisation.");
}
my_assert(!(dumpabs && dumpscaled)); // dumpabs=true and dumpscaled=true is a meaningless combination
// Take the first character (for backward compatibility)
discretization = std::string(discretization, 0, 1);
if (chitp_ratio > 0.0) chitp = chitp_ratio / betabar;
}
void dump(std::ostream &F = std::cout) {
all.sort([](auto a, auto b) { return a->getkeyword() < b->getkeyword(); });
F << std::setprecision(std::numeric_limits<double>::max_digits10); // ensure no precision is lost
for (const auto &i : all) i->dump(F);
}
void h5save(H5Easy::File &file) const {
for (const auto &i : all) i->h5save(file, "params");
h5_dump_scalar(file, "params/Nmax", Nmax);
h5_dump_scalar(file, "params/channels", channels);
h5_dump_scalar(file, "params/coeffactor", coeffactor);
h5_dump_scalar(file, "params/coefchannels", coefchannels);
h5_dump_scalar(file, "params/perchannel", perchannel);
h5_dump_scalar(file, "params/combs", combs);
h5_dump_scalar(file, "params/Nlen", Nmax);
h5_dump_scalar(file, "params/spin", spin);
}
explicit Params(const std::string &filename, const std::string &block,
std::unique_ptr<Workdir> workdir_,
const bool embedded,
const bool quiet = false )
: workdir(std::move(workdir_)), embedded(embedded)
{
pretty_out = !is_stdout_redirected();
if (filename != "") {
auto parsed_params = parser(filename, block);
for (const auto &i : all) {
const std::string keyword = i->getkeyword();
if (parsed_params.count(keyword) == 1) {
i->set_str(parsed_params[keyword]);
parsed_params.erase(keyword);
}
}
if (parsed_params.size()) {
std::cout << "Unused settings: " << std::endl;
for (const auto &[key, value] : parsed_params)
std::cout << " " << key << "=" << value << std::endl;
std::cout << std::endl;
}
}
validate();
init_laststored();
if (!quiet) dump();
}
explicit Params() : Params("", "", std::make_unique<Workdir>(), true, true) {} // defaulted version (for testing purposes)
Params(const Params &) = delete;
Params(Params &&) = delete;
Params &operator=(const Params &) = delete;
Params &operator=(Params &&) = delete;
// The factor that multiplies the eigenvalues of the length-N Wilson chain Hamiltonian in order to obtain the
// energies on the original scale. Also named the "reduced bandwidth".
// TO DO: use polymorphism instead of if statements.
auto SCALE(const int N) const noexcept {
double scale = 0.0;
if (discretization == "Y"s)
// Yoshida,Whitaker,Oliveira PRB 41 9403 Eq. (39)
scale = 0.5 * (1. + 1. / Lambda); // NOLINT
if (std::string(discretization) == "C"s || std::string(discretization) == "Z"s)
// Campo, Oliveira PRB 72 104432, Eq. (46) [+ Lanczos]
scale = (1.0 - 1. / Lambda) / std::log(Lambda); // NOLINT
if (!substeps)
scale *= pow(Lambda, -(N - 1) / 2. + 1 - z); // NOLINT
else
scale *= pow(Lambda, -N / (2. * double(channels)) + 3 / 2. - z); // NOLINT
scale = scale * bandrescale; // RESCALE // XXX: is this the appropriate place for rescaling? compatible with P.absolute==true?
return scale;
}
// Energy scale at the last NRG iteration. Used in binning and broadening code.
double last_step_scale() const noexcept { return SCALE(Nmax); }
double nrg_step_scale_factor() const noexcept { // rescale factor in the RG transformation (matrix construction)
return absolute ? 1 : (!substeps ? sqrt(Lambda) : pow(Lambda, 0.5/double(channels))); // NOLINT
}
// Here we set the lowest frequency at which we will evaluate the spectral density. If the value is not predefined
// in the parameters file, use the smallest scale from the calculation multiplied by P.broaden_min_ratio.
double get_broaden_min() const noexcept { return broaden_min <= 0.0 ? broaden_min_ratio * last_step_scale() : broaden_min; }
// Energy scale factor that is exponentiated. N/N+1 patching is recommended for larger values of Lambda, so as to
// reduce the upper limit of the patching window to omega_N*goodE*Lambda, i.e., by a factor of Lambda compared to
// the N/N+2 patching where the upper limit is omega_N*goodE*Lambda^2.
double getEfactor() const noexcept {
return (channels == 1 && !NN1) ? Lambda : std::sqrt(Lambda);
}
// Energy window for the patching procedure [FT and DMNRG algorithms]. In ZBW calculations the window is extended to [0:infty]
// to get all spectral contributions.
double getE0() const noexcept { return goodE; }
double getEmin() const noexcept { return !ZBW() ? getE0() : 0.0; }
double getEx() const noexcept { return getE0() * getEfactor(); } // The "peak" energy of the "window function" in the patching procedure.
double getEmax() const noexcept { return !ZBW() ? getE0() * pow(getEfactor(),2) : std::numeric_limits<double>::max(); }
auto Nall() const noexcept { return boost::irange(size_t(Ninit), size_t(Nlen)); }
};
class DiagParams {
public:
std::string diag{};
double diagratio{};
bool logall{};
std::string logstr{};
DiagParams() {}
explicit DiagParams(const Params &P, const double diagratio_ = -1) :
diag(P.diag), diagratio(diagratio_ > 0 ? diagratio_ : P.diagratio),
logall(P.logall), logstr(P.logstr) {}
bool logletter(char c) const { return logall ? true : logstr.find(c) != std::string::npos; }
private:
friend class boost::serialization::access;
template <class Archive> void serialize(Archive &ar, [[maybe_unused]] const unsigned int version) {
ar &diag;
ar &diagratio;
ar &logall;
ar &logstr;
}
};
} // namespace
#endif
| 36,730
|
C++
|
.h
| 596
| 57.755034
| 143
| 0.674164
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,629
|
nrg-general.hpp
|
rokzitko_nrgljubljana/c++/nrg-general.hpp
|
/*
"NRG Ljubljana" - Numerical renormalization group for multiple
impurities and an arbitrary number of channels
Copyright (C) 2005-2024 Rok Zitko
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact information:
Rok Zitko
F1 - Theoretical physics
"Jozef Stefan" Institute
Jamova 39
SI-1000 Ljubljana
Slovenia
rok.zitko@ijs.si
*/
#ifndef _nrg_general_hpp_
#define _nrg_general_hpp_
#include <utility>
#include <functional>
#include <iterator>
#include <algorithm>
#include <complex>
#include <numeric>
#include <limits>
#include <memory>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include <map>
#include <list>
#include <deque>
#include <set>
#include <stdexcept>
// C headers
#include <cmath>
#include <cfloat>
#include <climits>
#include <cstring>
#include <unistd.h>
#include <boost/range/irange.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/optional.hpp>
// Serialization support (used for storing to files and for MPI)
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
// MPI support
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <fmt/format.h>
#include <fmt/color.h>
#include <fmt/ranges.h>
#include <range/v3/all.hpp>
#include "nrg-lib.hpp" // exposed interfaces for wrapping into a library
#include "portabil.hpp"
#include "debug.hpp"
#include "basicio.hpp"
#include "misc.hpp"
#include "openmp.hpp"
#include "mp.hpp"
#include "traits.hpp"
#include "workdir.hpp"
#include "params.hpp"
#include "io.hpp"
#include "time_mem.hpp"
#include "outfield.hpp"
#include "core.hpp"
#include "mk_sym.hpp"
#include "numerics.hpp"
namespace NRG {
using namespace std::string_literals;
using namespace fmt::literals;
template <scalar S> class NRG_calculation {
private:
Params P;
std::shared_ptr<DiagEngine<S>> eng;
InputData<S> input;
std::shared_ptr<Symmetry<S>> Sym;
Stats<S> stats;
Store<S> store, store_all;
MemTime mt; // memory and timing statistics
public:
auto run_nrg(const RUNTYPE runtype, Operators<S> operators, const Coef<S> &coef, DiagInfo<S> diag0) {
auto oprecalc = Oprecalc<S>(runtype, operators, Sym, mt, P);
auto output = Output<S>(runtype, operators, stats, P);
if (P.h5raw && P.h5all) {
diag0.h5save(*output.h5raw, std::to_string(P.Ninit) + "/eigen/");
operators.h5save(*output.h5raw, std::to_string(P.Ninit));
}
Step step{P, runtype};
// If calc0=true, a calculation of TD quantities is performed before starting the NRG iteration.
if (step.nrg() && P.calc0 && !P.ZBW())
docalc0(step, operators, diag0, stats, output, oprecalc, Sym.get(), mt, P);
auto diag = P.ZBW() ? nrg_ZBW(step, operators, stats, diag0, output, store, store_all, oprecalc, Sym.get(), mt, P)
: nrg_loop(step, operators, coef, stats, diag0, output, store, store_all, oprecalc, Sym.get(), eng.get(), mt, P);
color_print(P.pretty_out, fmt::emphasis::bold | fg(fmt::color::red), FMT_STRING("\nTotal energy: {:.18}\n"), stats.total_energy);
stats.GS_energy = stats.total_energy;
if (step.nrg()) {
store.shift_abs_energies(stats.GS_energy);
if (P.dumpabsenergies) store.dump_all_absolute_energies();
if (P.dumpsubspaces) store.dump_subspaces();
if (P.h5raw) stats.h5save_nrg(*output.h5raw); // saved in raw.h5
if (P.h5raw && P.h5all)
store.h5save(*output.h5raw, "store");
}
if (step.dmnrg()) {
if (P.h5raw) stats.h5save_dmnrg(*output.h5raw); // saved in raw-dm.h5
}
fmt::print("\n** Iteration completed.\n\n");
return diag;
}
void calc_rho(const DiagInfo<S> &diag) {
Step step{P, RUNTYPE::NRG};
step.set_last();
auto rho = init_rho(step, diag, Sym.get(), P);
rho.save(step.lastndx(), P, fn_rho);
if (!P.ZBW()) calc_densitymatrix(rho, store_all, Sym.get(), mt, P);
}
void calc_rhoFDM() {
Step step{P, RUNTYPE::NRG};
step.set_last();
calc_ZnD(store, stats, Sym.get(), P);
if (P.logletter('w'))
report_ZnD(stats, P);
fdm_thermodynamics(store, stats, Sym.get(), P.T);
auto rhoFDM = init_rho_FDM(step.lastndx(), store, stats, Sym->multfnc(), P.T);
rhoFDM.save(step.lastndx(), P, fn_rhoFDM);
if (!P.ZBW()) calc_fulldensitymatrix(step, rhoFDM, store, store_all, stats, Sym.get(), mt, P);
}
NRG_calculation(std::unique_ptr<Workdir> workdir, std::shared_ptr<DiagEngine<S>> _eng, const bool embedded) :
P("param", "param", std::move(workdir), embedded), eng(_eng), input(P, "data"), Sym(input.Sym),
stats(P, Sym->get_td_fields(), input.GS_energy), store(P.Ninit, P.Nlen), store_all(P.Ninit, P.Nlen)
{
if (P.diag_mode == "OpenMP") // override
eng = std::make_shared<DiagOpenMP<S>>();
if (P.diag_mode == "serial")
eng = std::make_shared<DiagSerial<S>>();
auto diag = run_nrg(RUNTYPE::NRG, input.operators, input.coef, input.diag);
if (P.dm) {
if (P.need_rho()) calc_rho(diag); // XXX: diag required here?
if (P.need_rhoFDM()) calc_rhoFDM();
run_nrg(RUNTYPE::DMNRG, input.operators, input.coef, input.diag);
}
}
NRG_calculation(const NRG_calculation &) = delete;
NRG_calculation(NRG_calculation &&) = delete;
NRG_calculation & operator=(const NRG_calculation &) = delete;
NRG_calculation & operator=(const NRG_calculation &&) = delete;
~NRG_calculation() {
if (!P.embedded) mt.report(); // only when running as a stand-alone application
if (P.done) { std::ofstream D("DONE"); } // Indicate completion by creating a flag file
}
};
} // namespace
#endif
| 6,301
|
C++
|
.h
| 163
| 35.257669
| 137
| 0.694508
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,630
|
read-input.hpp
|
rokzitko_nrgljubljana/c++/read-input.hpp
|
#ifndef _read_input_hpp_
#define _read_input_hpp_
#include <memory>
#include <string>
#include <iostream>
#include <stdexcept>
#include <tuple>
#include <utility>
#include "traits.hpp"
#include "constants.hpp"
#include "symmetry.hpp"
#include "params.hpp"
#include "eigen.hpp"
#include "operators.hpp"
#include "coef.hpp"
#include "mk_sym.hpp"
#include <fmt/format.h>
namespace NRG {
// Parse the header of the data file, check the version, determine the symmetry type.
inline auto parse_datafile_header(std::istream &fdata, const int expected_version = 9)
{
std::string sym_string = "";
int dataversion = -1;
while (fdata.peek() == '#') {
fdata.ignore(); // ignore '#'
if (fdata.peek() == '!') {
fdata.ignore(); // ignore '!'
fdata >> dataversion;
} else {
std::string line;
std::getline(fdata, line);
auto pos = line.find("symtype", 1);
if (pos != std::string::npos) {
// Symmetry type declaration
auto p = line.find_last_of(" \t");
if (p != std::string::npos && p < line.size() - 1)
sym_string = line.substr(p + 1); // global variable
}
}
if (fdata.peek() == '\n') fdata.ignore();
}
my_assert(dataversion == expected_version);
return sym_string;
}
// Determine Nmax & Nlen, taking into account P.substeps. Must be called after the
// tridiagonalization routines if not using the tables in the data file.
template<scalar S>
void determine_Nmax_Nlen(const Coef<S> &coef, const size_t Nmax0, Params &P) { // Params is non-const !
const auto length_coef_table = coef.xi.max(0); // all channels have the same nr. of coefficients
my_assert(length_coef_table == Nmax0); // check consistency
P.Nmax = !P.substeps ? Nmax0 : P.channels * Nmax0;
P.Nlen = !P.ZBW() ? P.Nmax : P.Nmax+1; // an additional element in the tables for ZBW
if (P.ZBW()) std::cout << "\nZBW=true -> zero-bandwidth calculation\n";
std::cout << "\nlength_coef_table=" << length_coef_table << " Nmax0=" << Nmax0 << " Nmax=" << P.Nmax << "\n\n";
my_assert(P.Nlen < MAX_NDX);
if (P.ZBW()) my_assert(P.substeps == false);
}
inline auto get_next_block(std::istream &fdata) {
while (!fdata.eof() && std::isspace(fdata.peek())) fdata.get(); // skip white space
char ch = char(fdata.get());
std::string opname;
std::getline(fdata, opname);
return std::make_pair(ch, opname);
}
template<scalar S>
class InputData {
private:
std::string sym_string;
size_t channels;
size_t Nmax;
size_t nsubs;
public:
std::shared_ptr<Symmetry<S>> Sym;
DiagInfo<S> diag;
Operators<S> operators;
Coef<S> coef;
double GS_energy = 0.0;
InputData(Params &P, const std::string &filename = "data") : coef(P) {
std::ifstream fdata(filename);
if (!fdata) throw std::runtime_error("Can't load initial data.");
sym_string = parse_datafile_header(fdata);
channels = read_one<size_t>(fdata); // Number of channels in the bath
Nmax = read_one<size_t>(fdata); // Length of the Wilson chain
nsubs = read_one<size_t>(fdata); // Number of invariant subspaces
my_assert(sym_string == P.symtype.value()); // Check consistency between 'param' and 'data' file
Sym = set_symmetry<S>(P, sym_string, channels);
diag = DiagInfo<S>(fdata, nsubs, P); // 0-th step of the NRG iteration
diag.states_report(Sym->multfnc());
operators.opch = Opch<S>(fdata, diag, P);
while (true) {
const auto [ch, opname] = get_next_block(fdata);
if (fdata.eof()) break;
if (ch != '#') std::cout << "Reading <||" << opname << "||> (" << ch << ")" << std::endl;
switch (ch) {
case '#':
break; // ignore embedded comment lines
case 'e': GS_energy = read_one<double>(fdata); break;
case 's': operators.ops[opname] = MatrixElements<S>(fdata, diag); break;
case 'p': operators.opsp[opname] = MatrixElements<S>(fdata, diag); break;
case 'g': operators.opsg[opname] = MatrixElements<S>(fdata, diag); break;
case 'd': operators.opd[opname] = MatrixElements<S>(fdata, diag); break;
case 't': operators.opt[opname] = MatrixElements<S>(fdata, diag); break;
case 'o': operators.opot[opname] = MatrixElements<S>(fdata, diag); break;
case 'q': operators.opq[opname] = MatrixElements<S>(fdata, diag); break;
case 'z':
coef.xi.read(fdata, P.coefchannels);
coef.zeta.read(fdata, P.coefchannels);
break;
case 'Z':
coef.delta.read(fdata, P.coefchannels);
coef.kappa.read(fdata, P.coefchannels);
break;
case 'X':
coef.xiR.read(fdata, P.coefchannels);
coef.zetaR.read(fdata, P.coefchannels);
break;
case 'T':
coef.ep.read(fdata, P.coefchannels);
coef.em.read(fdata, P.coefchannels);
coef.u0p.read(fdata, P.coefchannels);
coef.u0m.read(fdata, P.coefchannels);
break;
#ifdef CHAIN_COEF
case 'W':
coef.eps.read(fdata);
coef.t.read(fdata);
break;
#endif
default: throw std::invalid_argument(fmt::format("Unknown block {} in data file.", ch));
}
}
if (std::string(P.tri) == "cpp") Tridiag<S>(coef, Nmax, P); // before calling determine_Nmax_Nlen()
determine_Nmax_Nlen(coef, Nmax, P);
};
};
} // namespace
#endif
| 5,352
|
C++
|
.h
| 137
| 34.021898
| 113
| 0.629587
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,631
|
truncation.hpp
|
rokzitko_nrgljubljana/c++/truncation.hpp
|
#ifndef _truncation_hpp_
#define _truncation_hpp_
#include <algorithm> // clamp
#include "step.hpp"
#include "eigen.hpp"
#include "params.hpp"
#include "symmetry.hpp"
#include "debug.hpp" // nrgdump
#include <fmt/format.h>
namespace NRG {
// Returns true if all states should be retained in the current step of the NRG iteration.
inline auto keepall(const Step &step, const Params &P) {
if (P.keepall == ""s) return false;
if (P.keepall == "even"s && step.N() % 2 == 0) return true;
if (P.keepall == "odd"s && step.N() % 2 == 1) return true;
const auto list = split(P.keepall, ',');
if (std::find(list.begin(), list.end(), to_string(step.N())) != list.end()) return true;
return false;
}
// Determine the number of states to be retained. Returns Emax - the highest energy to still be retained.
template <scalar S> auto highest_retained_energy(const Step &step, const DiagInfo<S> &diag, const Params &P) {
const auto energies = diag.sorted_energies_corr(); // We use roundoff-error corrected eigenvalues here!
const auto totalnumber = energies.size();
my_assert(totalnumber != 0);
my_assert(energies.front() == 0.0); // check for the subtraction of Egs
if (keepall(step, P))
return energies.back();
// We add 1 for historical reasons. We thus keep states with E<=Emax, and one additional state which has E>Emax.
auto nrkeep = P.keepenergy <= 0.0 ?
P.keep :
std::clamp<size_t>(1 + ranges::count_if(energies, [keepenergy = P.keepenergy * step.unscale()](double e) { return e <= keepenergy; }), P.keepmin, P.keep);
// Check for near degeneracy and ensure that the truncation occurs in a "gap" between clusters of eigenvalues.
if (P.safeguard > 0.0) {
size_t cnt_extra = 0;
while (nrkeep < totalnumber && (energies[nrkeep] - energies[nrkeep - 1]) <= P.safeguard && cnt_extra < P.safeguardmax) {
nrkeep++;
cnt_extra++;
}
if (cnt_extra) std::cout << "Safeguard: keep additional " << cnt_extra << " states" << std::endl;
}
nrkeep = std::clamp<size_t>(nrkeep, 1, totalnumber);
return energies[nrkeep - 1];
}
struct truncate_stats {
size_t nrall, nrallmult, nrkept, nrkeptmult;
template <scalar S, typename MF>
truncate_stats(const DiagInfo<S> &diag, MF mult) {
nrall = ranges::accumulate(diag, 0, {}, [](const auto &d) { const auto &[I, eig] = d; return eig.getdim(); });
nrallmult = ranges::accumulate(diag, 0, {}, [mult](const auto &d) { const auto &[I, eig] = d; return mult(I) * eig.getdim(); });
nrkept = ranges::accumulate(diag, 0, {}, [](const auto &d) { const auto &[I, eig] = d; return eig.getnrkept(); });
nrkeptmult = ranges::accumulate(diag, 0, {}, [mult](const auto &d) { const auto &[I, eig] = d; return mult(I) * eig.getnrkept(); });
}
void report() { std::cout << nrgdump4(nrkept, nrkeptmult, nrall, nrallmult) << std::endl; }
};
struct NotEnough : public std::exception {};
// Compute the number of states to keep in each subspace. Returns true if an insufficient number of states has been
// obtained in the diagonalization and we need to compute more states.
template <scalar S, typename MF>
void truncate_prepare(const Step &step, DiagInfo<S> &diag, MF mult, const Params &P) {
const auto Emax = highest_retained_energy(step, diag, P);
for (auto &[I, eig] : diag)
diag[I].truncate_prepare(step.last() && P.keep_all_states_in_last_step()
? eig.getnrcomputed()
: ranges::count_if(eig.values.all_corr(), [Emax](const double e) { return e <= Emax; }));
std::cout << "Emax=" << Emax / step.unscale() << " ";
truncate_stats ts(diag, mult);
ts.report();
if (ranges::any_of(diag, [Emax](const auto &d) {
const auto &[I, eig] = d;
return eig.getnrkept() == eig.getnrcomputed() && eig.values.highest_corr() != Emax && eig.getnrcomputed() < eig.getdim();
}))
throw NotEnough();
const double ratio = double(ts.nrkept) / ts.nrall;
fmt::print(FMT_STRING("Kept: {} out of {}, ratio={:.3}\n"), ts.nrkept, ts.nrall, ratio);
}
} // namespace
#endif
| 4,089
|
C++
|
.h
| 77
| 49.12987
| 159
| 0.654414
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,632
|
algo_FDM.hpp
|
rokzitko_nrgljubljana/c++/algo_FDM.hpp
|
#ifndef _algo_FDM_hpp_
#define _algo_FDM_hpp_
#include <complex>
#include "traits.hpp"
#include "algo.hpp"
#include "spectrum.hpp"
namespace NRG {
using namespace std::complex_literals;
// Recall: II=(Ij,Ii) <i|A|j> <j|B|i>. B is d^dag. We conjugate A.
template<scalar S, typename Matrix = Matrix_traits<S>, typename t_coef = coef_traits<S>, typename t_eigen = eigen_traits<S>>
class Algo_FDMls : virtual public Algo<S> {
private:
inline static const std::string algoname = "FDMls";
SpectrumRealFreq<S> spec;
const int sign; // 1 for bosons, -1 for fermions
const bool save;
protected:
using CB = ChainBinning<S>;
std::unique_ptr<CB> cb;
public:
using Algo<S>::P;
Algo_FDMls(const std::string &name, const std::string &prefix, const gf_type gt, const Params &P, const bool save = true)
: Algo<S>(P), spec(name, algoname, spec_fn(name, prefix, algoname, save), P), sign(gf_sign(gt)), save(save) {}
void begin(const Step &) override { cb = std::make_unique<CB>(P); }
void calc(const Step &step, const Eigen<S> &diagIi, const Eigen<S> &diagIj, const Matrix &op1, const Matrix &op2,
t_coef factor, [[maybe_unused]] const Invar &Ii, [[maybe_unused]] const Invar &Ij, const DensMatElements<S> &rhoFDM,
const Stats<S> &stats) override
{
const auto wnf = stats.wnfactor[step.ndx()];
const auto rho_op2 = prod_fit(rhoFDM.at(Ij), op2);
const auto energies = [&diagIi, &diagIj](const auto i, const auto j) {
return std::make_pair(diagIi.values.abs_G(i), diagIj.values.abs_G(j));
};
const auto term1 = [&energies, &op1, &op2, T = P.T.value(), wnf, this](const auto i, const auto j) {
const auto [Ei, Ej] = energies(i, j);
return std::make_pair(Ej-Ei, conj_me(op1(j, i)) * op2(j, i) * (-sign) * exp(-Ej/T) * wnf);
};
const auto term2 = [&energies, &op1, &rho_op2, this](const auto i, const auto j) {
const auto [Ei, Ej] = energies(i, j);
return std::make_pair(Ej-Ei, conj_me(op1(j, i)) * rho_op2(j, i) * (-sign));
};
const auto term3 = [&energies, &op1, &op2, T = P.T.value(), wnf, this](const auto i, const auto j) {
const auto [Ei, Ej] = energies(i, j);
return std::make_pair(Ej-Ei, conj_me(op1(j, i)) * op2(j, i) * (-sign) * exp(-Ej/T) * wnf);
};
for (const auto i : diagIi.Drange()) // XXX: change order for sequential memory access!
for (const auto j : diagIj.Drange())
cb->add(term1(i,j), factor);
for (const auto i : diagIi.Drange())
for (const auto j : diagIj.Krange())
cb->add(term2(i,j), factor);
for (const auto i : diagIi.Krange())
for (const auto j : diagIj.Drange())
cb->add(term3(i,j), factor);
}
void end([[maybe_unused]] const Step &step) override {
spec.mergeCFS(*cb.get());
cb.reset();
}
~Algo_FDMls() { if (save) spec.save(); }
std::string rho_type() override { return "rhoFDM"; }
};
template<scalar S, typename Matrix = Matrix_traits<S>, typename t_coef = coef_traits<S>, typename t_eigen = eigen_traits<S>>
class Algo_FDMgt : virtual public Algo<S> {
private:
inline static const std::string algoname = "FDMgt";
SpectrumRealFreq<S> spec;
const int sign; // 1 for bosons, -1 for fermions
const bool save;
protected:
using CB = ChainBinning<S>;
std::unique_ptr<CB> cb;
public:
using Algo<S>::P;
Algo_FDMgt(const std::string &name, const std::string &prefix, const gf_type gt, const Params &P, const bool save = true)
: Algo<S>(P), spec(name, algoname, spec_fn(name, prefix, algoname, save), P), sign(gf_sign(gt)), save(save) {}
void begin(const Step &) override { cb = std::make_unique<CB>(P); }
void calc(const Step &step, const Eigen<S> &diagIi, const Eigen<S> &diagIj, const Matrix &op1, const Matrix &op2,
t_coef factor, [[maybe_unused]] const Invar &Ii, [[maybe_unused]] const Invar &Ij, const DensMatElements<S> &rhoFDM,
const Stats<S> &stats) override
{
const auto wnf = stats.wnfactor[step.ndx()];
const auto op2_rho = prod_fit(op2, rhoFDM.at(Ii));
const auto energies = [&diagIi, &diagIj](const auto i, const auto j) {
return std::make_pair(diagIi.values.abs_G(i), diagIj.values.abs_G(j));
};
const auto term1 = [&energies, &op1, &op2, T = P.T.value(), wnf](const auto i, const auto j) {
const auto [Ei, Ej] = energies(i, j);
return std::make_pair(Ej-Ei, conj_me(op1(j, i)) * op2(j, i) * exp(-Ei/T) * wnf);
};
const auto term2 = [&energies, &op1, &op2, T = P.T.value(), wnf](const auto i, const auto j) {
const auto [Ei, Ej] = energies(i, j);
return std::make_pair(Ej-Ei, conj_me(op1(j, i)) * op2(j, i) * exp(-Ei/T) * wnf);
};
const auto term3 = [&energies, &op1, &op2_rho](const auto i, const auto j) {
const auto [Ei, Ej] = energies(i, j);
return std::make_pair(Ej-Ei, conj_me(op1(j, i)) * op2_rho(j, i));
};
for (const auto i : diagIi.Drange())
for (const auto j : diagIj.Drange())
cb->add(term1(i,j), factor);
for (const auto i : diagIi.Drange())
for (const auto j : diagIj.Krange())
cb->add(term2(i,j), factor);
for (const auto i : diagIi.Krange())
for (const auto j : diagIj.Drange())
cb->add(term3(i,j), factor);
}
void end([[maybe_unused]] const Step &step) override {
spec.mergeCFS(*cb.get());
cb.reset();
}
~Algo_FDMgt() { if (save) spec.save(); }
std::string rho_type() override { return "rhoFDM"; }
};
template<scalar S, typename Matrix = Matrix_traits<S>, typename t_coef = coef_traits<S>, typename t_eigen = eigen_traits<S>>
class Algo_FDM : public Algo_FDMls<S>, public Algo_FDMgt<S> {
private:
inline static const std::string algoname2 = "FDM";
SpectrumRealFreq<S> spec_tot;
public:
using Algo<S>::P;
Algo_FDM(const std::string &name, const std::string &prefix, const gf_type gt, const Params &P) :
Algo<S>(P), Algo_FDMls<S>(name, prefix, gt, P, false), Algo_FDMgt<S>(name, prefix, gt, P, false), spec_tot(name, algoname2, spec_fn(name, prefix, algoname2), P) {}
void begin(const Step &step) override {
Algo_FDMgt<S>::begin(step);
Algo_FDMls<S>::begin(step);
}
void calc(const Step &step, const Eigen<S> &diagIp, const Eigen<S> &diagI1, const Matrix &op1, const Matrix &op2,
t_coef factor, const Invar &Ip, const Invar &I1, const DensMatElements<S> &rho,
const Stats<S> &stats) override
{
Algo_FDMgt<S>::calc(step, diagIp, diagI1, op1, op2, factor, Ip, I1, rho, stats);
Algo_FDMls<S>::calc(step, diagIp, diagI1, op1, op2, factor, Ip, I1, rho, stats);
}
void end([[maybe_unused]] const Step &step) override {
spec_tot.mergeCFS(*Algo_FDMgt<S>::cb.get());
spec_tot.mergeCFS(*Algo_FDMls<S>::cb.get());
Algo_FDMgt<S>::cb.reset();
Algo_FDMls<S>::cb.reset();
}
~Algo_FDM() { spec_tot.save(); }
std::string rho_type() override { return "rhoFDM"; }
};
template<scalar S, typename Matrix = Matrix_traits<S>, typename t_coef = coef_traits<S>, typename t_eigen = eigen_traits<S>, typename t_weight = weight_traits<S>>
class Algo_FDMmats : public Algo<S> {
private:
inline static const std::string algoname = "FDMmats";
GFMatsubara<S> gf;
const int sign;
const gf_type gt;
using CM = ChainMatsubara<S>;
std::unique_ptr<CM> cm;
public:
using Algo<S>::P;
Algo_FDMmats(const std::string &name, const std::string &prefix, const gf_type gt, const Params &P) :
Algo<S>(P), gf(name, algoname, spec_fn(name, prefix, algoname), gt, P), sign(gf_sign(gt)), gt(gt) {}
void begin(const Step &) override { cm = std::make_unique<CM>(P, gt); }
void calc(const Step &step, const Eigen<S> &diagIi, const Eigen<S> &diagIj, const Matrix &op1, const Matrix &op2,
t_coef factor, const Invar &Ii, const Invar &Ij, const DensMatElements<S> &rhoFDM,
const Stats<S> &stats) override
{
const size_t cutoff = P.mats;
const auto wnf = stats.wnfactor[step.ndx()];
const auto rho_op2 = prod_fit(rhoFDM.at(Ij), op2);
const auto op2_rho = prod_fit(op2, rhoFDM.at(Ii));
const auto energies = [&diagIi, &diagIj](const auto i, const auto j) {
return std::make_pair(diagIi.values.abs_G(i), diagIj.values.abs_G(j));
};
const auto term1 = [&energies, &op1, &op2, T = P.T.value(), wnf, this](const auto i, const auto j, const auto n) -> t_weight {
const auto [Ei, Ej] = energies(i, j);
const auto energy = Ej - Ei;
const auto weightA = conj_me(op1(j, i)) * op2(j, i) * wnf * exp(-Ei/T); // a[ij] b[ji] exp(-beta e[i])
const auto weightB = conj_me(op1(j, i)) * op2(j, i) * (-sign) * wnf * exp(-Ej/T); // a[ij] b[ji] sign exp(-beta e[j])
if (gt == gf_type::fermionic || n>0 || abs(energy) > WEIGHT_TOL)
return (weightA + weightB) / (ww(n, gt, T)*1i - energy);
else // bosonic w=0 && Ei=Ej case
return -weightA/T;
};
const auto term2 = [&energies, &op1, &op2, &rho_op2, T = P.T.value(), wnf, this](const auto i, const auto j, const auto n) {
const auto [Ei, Ej] = energies(i, j);
const auto energy = Ej - Ei;
const auto weightA = conj_me(op1(j, i)) * op2(j, i) * wnf * exp(-Ei/T);
const auto weightB = conj_me(op1(j, i)) * rho_op2(j, i) * (-sign);
return (weightA + weightB) / (ww(n, gt, T)*1i - energy);
};
const auto term3 = [&energies, &op1, &op2, &op2_rho, T = P.T.value(), wnf, this](const auto i, const auto j, const auto n) {
const auto [Ei, Ej] = energies(i, j);
const auto energy = Ej - Ei;
const auto weightA = conj_me(op1(j, i)) * op2_rho(j, i);
const auto weightB = (-sign) * conj_me(op1(j, i)) * op2(j, i) * wnf * exp(-Ej/T);
return (weightA + weightB) / (ww(n, gt, T)*1i - energy);
};
for (const auto i : diagIi.Drange())
for (const auto j : diagIj.Drange())
#pragma omp parallel for schedule(static)
for (size_t n = 0; n < cutoff; n++)
cm->add(n, term1(i,j,n) * factor);
for (const auto i : diagIi.Drange())
for (const auto j : diagIj.Krange())
#pragma omp parallel for schedule(static)
for (size_t n = 0; n < cutoff; n++)
cm->add(n, term2(i,j,n) * factor);
for (const auto i : diagIi.Krange())
for (const auto j : diagIj.Drange())
#pragma omp parallel for schedule(static)
for (size_t n = 0; n < cutoff; n++)
cm->add(n, term3(i,j,n) * factor);
}
void end([[maybe_unused]] const Step &step) override {
gf.merge(*cm.get());
cm.reset();
}
~Algo_FDMmats() { gf.save(); }
std::string rho_type() override { return "rhoFDM"; }
};
} // namespace
#endif
| 10,801
|
C++
|
.h
| 218
| 43.715596
| 168
| 0.610801
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,633
|
spectrum.hpp
|
rokzitko_nrgljubljana/c++/spectrum.hpp
|
#ifndef _spectrum_hpp_
#define _spectrum_hpp_
#include <algorithm>
#include "traits.hpp"
#include "params.hpp"
#include "bins.hpp"
#include "matsubara.hpp"
#include "io.hpp" // {fmt}, color_print
#include <fmt/format.h>
namespace NRG {
template<scalar S, typename t_weight = weight_traits<S>>
class ChainBinning {
private:
const Params &P;
Bins<S> spos, sneg;
public:
explicit ChainBinning(const Params &P) : P(P), spos(P), sneg(P) {}
void add(const double energy, const t_weight weight) {
if (energy >= 0.0)
spos.add(energy, weight);
else
sneg.add(-energy, weight);
}
void add(const std::pair<double, t_weight> &p, const t_weight factor) {
const auto & [energy, weight] = p;
this->add(energy, factor * weight);
}
auto total_weight() const { return spos.total_weight() + sneg.total_weight(); }
template<scalar U> friend class SpectrumRealFreq;
};
template<scalar S, typename t_weight = weight_traits<S>>
class ChainMatsubara {
private:
const Params &P;
Matsubara<S> m;
public:
explicit ChainMatsubara(const Params &P, const gf_type gt) : P(P), m(P.mats, gt, P.T){};
void add(const size_t n, const t_weight w) { m.add(n, w); }
template<scalar U> friend class GFMatsubara;
};
template<scalar S, typename t_weight = weight_traits<S>>
class ChainTempDependence {
private:
const Params &P;
Temp<S> v;
public:
explicit ChainTempDependence(const Params &P) : P(P), v(P) {}
void add(const double T, const t_weight value) { v.add_value(T, value); }
template<scalar U> friend class TempDependence;
};
// Real-frequency spectral function
template<scalar S>
class SpectrumRealFreq {
private:
const std::string name, algoname, filename; // e.g. "A_d-A_d", "FT", "spec_A_d-A_d_dens_FT.dat"
const Params &P;
Bins<S> fspos, fsneg; // Full spectral information, separately for positive and negative frequencies
void mergeNN2half(Bins<S> &fullspec, const Bins<S> &cs, const Step &step);
void weight_report(const double imag_tolerance = 1e-10);
void trim() {
fspos.trim();
fsneg.trim();
}
void savebins();
void continuous();
public:
SpectrumRealFreq(const std::string &name, const std::string &algoname, const std::string &filename, const Params &P) :
name(name), algoname(algoname), filename(filename), P(P), fspos(P), fsneg(P) {}
void mergeCFS(const ChainBinning<S> &cs) {
fspos.merge(cs.spos); // Collect delta peaks
fsneg.merge(cs.sneg);
}
void mergeNN2(const ChainBinning<S> &cs, const Step &step) {
if (!step.N_for_merging()) return;
mergeNN2half(fspos, cs.spos, step); // Spectrum merging using the N/N+n patching.
mergeNN2half(fsneg, cs.sneg, step);
}
void save() {
color_print(P.pretty_out, fmt::emphasis::bold, "Spectrum: {} {} -> ", name, algoname); // savebins() & continuous() append the filenames
trim();
if (P.savebins) savebins();
if (P.broaden) continuous();
weight_report();
}
};
inline double windowfunction(const double E, const double Emin, const double Ex, const double Emax, const Step &step, const Params &P) {
if (E <= Ex && step.last()) return 1.0; // Exception 1
if (E >= Ex && step.first()) return 1.0; // Exception 2
if (P.ZBW()) return 1.0; // Exception 3
if (E <= Emin || E >= Emax) return 0.0; // Optimization
// Window functions: f(0)=0, f(1)=1.
const auto fnc_linear = [](const auto x) { return x ; };
const auto fnc_tanh_0 = [](const double x, const double NNtanh) { return tanh(NNtanh * (x - 0.5)); };
const auto fnc_tanh = [fnc_tanh_0](const double x, const double NNtanh) {
const auto f0 = fnc_tanh_0(0, NNtanh);
const auto fx = fnc_tanh_0(x, NNtanh);
const auto f1 = fnc_tanh_0(1, NNtanh);
return (fx - f0) / (f1 - f0);
};
const auto fnc = [&P, fnc_linear, fnc_tanh](const auto x) { return P.NNtanh > 0 ? fnc_tanh(x, P.NNtanh) : fnc_linear(x); };
if (Emin < E && E <= Ex) return fnc((E - Emin) / (Ex - Emin));
if (Ex < E && E < Emax) return 1.0 - fnc((E - Ex) / (Emax - Ex));
my_assert_not_reached();
}
// Here we perform the actual merging of data using the N/N+2 scheme. Note that we use a windowfunction (see above)
// to accomplish the smooth combining of data.
// See R. Bulla, T. A. Costi, D. Vollhardt, Phys. Rev. B 64, 045103 (2001)
template<scalar S>
void SpectrumRealFreq<S>::mergeNN2half(Bins<S> &fullspec, const Bins<S> &cs, const Step &step) {
const auto Emin = step.scale() * P.getEmin(); // p
const auto Ex = step.scale() * P.getEx(); // p Lambda
const auto Emax = step.scale() * P.getEmax(); // p Lambda^2
const auto len = fullspec.bins.size();
my_assert(len == cs.bins.size()); // We require equivalent bin sets!!
for (const auto i: range0(len)) {
const auto [energy, weight] = cs.bins[i];
if (Emin < energy && energy < Emax && weight != 0.0) {
const auto factor = P.NN2avg ? 0.5 : 1.0;
fullspec.bins[i].second += factor * weight * windowfunction(energy, Emin, Ex, Emax, step, P);
}
}
}
template<scalar S>
void SpectrumRealFreq<S>::weight_report(const double imag_tolerance) {
const auto fmt = [imag_tolerance](const auto x) -> std::string { return abs(x.imag()) < imag_tolerance ? to_string(x.real()) : to_string(x); };
const auto twneg = fsneg.total_weight();
const auto twpos = fspos.total_weight();
std::cout << std::endl << "pos=" << fmt(twpos) << " neg=" << fmt(twneg) << " sum= " << fmt(twpos + twneg) << std::endl;
for (int m = 1; m <= 4; m++) {
const auto mom = moment(fsneg.bins, fspos.bins, m); // Spectral moments from delta-peaks
std::cout << fmt::format("mu{}={} ", m, fmt(mom));
}
std::cout << std::endl;
const auto f = fd_fermi(fsneg.bins, fspos.bins, P.T);
const auto b = fd_bose (fsneg.bins, fspos.bins, P.T);
std::cout << "f=" << fmt(f) << " b=" << fmt(b) << std::endl;
}
// Save binary raw (binned) spectral function. If using complex numbers and P.reim==true, we save triplets
// (energy,real part,imag part).
template<scalar S>
void SpectrumRealFreq<S>::savebins() {
const auto fn = filename + ".bin";
std::cout << " " << fn;
std::ofstream Fbins = safe_open(fn, true); // true=binary!
for (const auto &[e, w] : fspos.bins) {
const auto [wr, wi] = reim(w);
my_assert(e > 0.0);
Fbins.write((char *)&e, sizeof(double));
Fbins.write((char *)&wr, sizeof(double));
if (P.reim)
Fbins.write((char *)&wi, sizeof(double));
}
for (const auto &[abse, w] : fsneg.bins) {
const auto [wr, wi] = reim(w);
const auto e = -abse;
my_assert(e < 0.0); // attention!
Fbins.write((char *)&e, sizeof(double));
Fbins.write((char *)&wr, sizeof(double));
if (P.reim)
Fbins.write((char *)&wi, sizeof(double));
}
}
// Energy mesh for spectral functions
inline std::vector<double> make_mesh(const Params &P) {
const double broaden_min = P.get_broaden_min();
std::vector<double> vecE; // Energies on the mesh
for (double E = P.broaden_max; E > broaden_min; E /= P.broaden_ratio) vecE.push_back(E);
return vecE;
}
template<scalar S>
void SpectrumRealFreq<S>::continuous() {
using t_weight = weight_traits<S>;
const double alpha = P.alpha;
const double omega0 = P.omega0 < 0.0 ? P.omega0_ratio * P.T : P.omega0;
Spikes<S> densitypos, densityneg;
const auto vecE = make_mesh(P); // Energies on the mesh
for (const auto E : vecE) {
t_weight valpos{}, valneg{};
for (const auto &[e, w] : fspos.bins) {
my_assert(e > 0.0);
valpos += w * BR_NEW(E, e, alpha, omega0);
valneg += w * BR_NEW(-E, e, alpha, omega0);
}
for (const auto &[e, w] : fsneg.bins) {
my_assert(e > 0.0); // attention!
valneg += w * BR_NEW(-E, -e, alpha, omega0);
valpos += w * BR_NEW(E, -e, alpha, omega0);
}
densitypos.emplace_back(E, valpos);
densityneg.emplace_back(-E, valneg);
}
ranges::sort(densityneg, sortfirst());
ranges::sort(densitypos, sortfirst());
const auto fn = filename + ".dat";
std::cout << " " << fn;
std::ofstream Fdensity = safe_open(fn);
densityneg.save(Fdensity, P.prec_xy, P.reim);
densitypos.save(Fdensity, P.prec_xy, P.reim);
}
template<scalar S>
class GFMatsubara {
private:
const std::string name, algoname, filename;
const Params &P;
Matsubara<S> results;
public:
GFMatsubara(const std::string &name, const std::string &algoname, const std::string &filename, gf_type gt, const Params &P) :
name(name), algoname(algoname), filename(filename), P(P), results(P.mats, gt, P.T) {}
void merge(const ChainMatsubara<S> &cm) {
results.merge(cm.m);
}
void save() {
color_print(P.pretty_out, fmt::emphasis::bold, "GF Matsubara: {} {} -> {}\n", name, algoname, filename);
results.save(safe_open(filename + ".dat"), P.prec_xy);
}
};
template<scalar S>
class TempDependence {
private:
const std::string name, algoname, filename;
const Params &P;
Spikes<S> results;
public:
TempDependence(const std::string &name, const std::string &algoname, const std::string &filename, const Params &P) :
name(name), algoname(algoname), filename(filename), P(P) {}
void merge(const ChainTempDependence<S> &ctd) {
std::copy(ctd.v.cbegin(), ctd.v.cend(), std::back_inserter(results));
}
void save() {
color_print(P.pretty_out, fmt::emphasis::bold, "Temperature dependence: {} {} -> {}\n", name, algoname, filename);
ranges::sort(results, sortfirst());
results.save(safe_open(filename + ".dat"), P.prec_xy, P.reim);
}
};
} // namespace
#endif
| 9,567
|
C++
|
.h
| 236
| 36.970339
| 145
| 0.647735
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,535,634
|
algo_FT.hpp
|
rokzitko_nrgljubljana/c++/algo_FT.hpp
|
#ifndef _algo_FT_hpp_
#define _algo_FT_hpp_
#include <complex>
#include "traits.hpp"
#include "algo.hpp"
#include "spectrum.hpp"
// The first matrix element is conjugated! This is <rp|OP1^dag|r1> <r1|OP2|rp> (wp - s*w1)/(z+Ep-E1)
namespace NRG {
using namespace std::complex_literals;
template<scalar S, typename Matrix = Matrix_traits<S>, typename t_coef = coef_traits<S>, typename t_eigen = eigen_traits<S>>
class Algo_FT : public Algo<S> {
private:
inline static const std::string algoname = "FT";
SpectrumRealFreq<S> spec;
const int sign; // 1 for bosons, -1 for fermions
using CB = ChainBinning<S>;
std::unique_ptr<CB> cb;
public:
using Algo<S>::P;
Algo_FT(const std::string &name, const std::string &prefix, const gf_type >, const Params &P) :
Algo<S>(P), spec(name, algoname, spec_fn(name, prefix, algoname), P), sign(gf_sign(gt)) {}
void begin(const Step &) override { cb = std::make_unique<CB>(P); }
void calc([[maybe_unused]] const Step &step, const Eigen<S> &diagIp, const Eigen<S> &diagI1, const Matrix &op1, const Matrix &op2,
const t_coef factor, const Invar &, const Invar &, const DensMatElements<S> &, const Stats<S> &stats) override
{
const auto stat_factor = [beta = 1.0/P.T, Z = stats.Zft, this](const auto E1, const auto Ep) {
return ((-sign) * exp(-beta*E1) + exp(-beta*Ep))/Z;
};
const auto term = [&diagI1, &diagIp, &op1, &op2, &stat_factor](const auto r1, const auto rp) {
const auto E1 = diagI1.values.abs_zero(r1);
const auto Ep = diagIp.values.abs_zero(rp);
return std::make_pair(E1 - Ep, conj_me(op1(r1, rp)) * op2(r1, rp) * stat_factor(E1,Ep));
};
for (const auto r1: diagI1.kept())
for (const auto rp: diagIp.kept())
cb->add(term(r1, rp), factor);
}
void end(const Step &step) override {
spec.mergeNN2(*cb.get(), step);
cb.reset();
}
~Algo_FT() { spec.save(); }
};
template<scalar S, typename Matrix = Matrix_traits<S>, typename t_coef = coef_traits<S>, typename t_eigen = eigen_traits<S>, typename t_weight = weight_traits<S>>
class Algo_FTmats : public Algo<S> {
private:
inline static const std::string algoname = "FTmats";
GFMatsubara<S> gf;
const int sign;
const gf_type gt;
using CM = ChainMatsubara<S>;
std::unique_ptr<CM> cm;
public:
using Algo<S>::P;
Algo_FTmats(const std::string &name, const std::string &prefix, const gf_type gt, const Params &P) :
Algo<S>(P), gf(name, algoname, spec_fn(name, prefix, algoname), gt, P), sign(gf_sign(gt)), gt(gt) {}
void begin(const Step &) override { cm = std::make_unique<CM>(P, gt); }
void calc([[maybe_unused]] const Step &step, const Eigen<S> &diagIp, const Eigen<S> &diagI1, const Matrix &op1, const Matrix &op2,
t_coef factor, const Invar &, const Invar &, const DensMatElements<S> &, const Stats<S> &stats) override
{
const auto stat_factor = [beta = 1.0/P.T, Z = stats.Zft, T = P.T.value(), this](const auto E1, const auto Ep, const auto n) -> t_weight {
const auto energy = E1-Ep;
if (gt == gf_type::fermionic || n>0 || abs(energy) > WEIGHT_TOL) // [[likely]]
return ((-sign) * exp(-beta*E1) + exp(-beta*Ep)) / (Z * (ww(n, gt, T)*1i - energy));
else // bosonic w=0 && E1=Ep case
return -exp(-beta*E1) / (Z * T);
};
const auto term = [&diagI1, &diagIp, &op1, &op2, &stat_factor](const auto r1, const auto rp, const auto n) {
const auto E1 = diagI1.values.abs_zero(r1);
const auto Ep = diagIp.values.abs_zero(rp);
return conj_me(op1(r1, rp)) * op2(r1, rp) * stat_factor(E1,Ep,n);
};
const size_t cutoff = P.mats;
for (const auto r1: diagI1.kept()) {
for (const auto rp: diagIp.kept()) {
#pragma omp parallel for schedule(static)
for (size_t n = 0; n < cutoff; n++)
cm->add(n, factor * term(r1, rp, n));
}
}
}
void end([[maybe_unused]] const Step &step) override {
gf.merge(*cm.get());
cm.reset();
}
~Algo_FTmats() { gf.save(); }
};
// Calculation of the temperature-dependent linear conductrance G(T) using the linear response theory &
// impurity-level spectral density. See Yoshida, Seridonio, Oliveira, arxiv:0906.4289, Eq. (8).
template<scalar S, int n, typename Matrix = Matrix_traits<S>, typename t_coef = coef_traits<S>, typename t_eigen = eigen_traits<S>>
class Algo_GT : public Algo<S> {
private:
inline static const std::string algoname = n == 0 ? "GT" : (n == 1 ? "I1T" : "I2T");
TempDependence<S> td;
using CT = ChainTempDependence<S>;
std::unique_ptr<CT> ct;
public:
using Algo<S>::P;
Algo_GT(const std::string &name, const std::string &prefix, const gf_type gt, const Params &P) :
Algo<S>(P), td(name, algoname, spec_fn(name, prefix, algoname), P) {
my_assert(gt == gf_type::fermionic);
static_assert(n ==0 || n == 1 || n == 2);
}
void begin(const Step &) override { ct = std::make_unique<CT>(P); }
void calc(const Step &step, const Eigen<S> &diagIp, const Eigen<S> &diagI1, const Matrix &op1, const Matrix &op2,
t_coef factor, const Invar &, const Invar &, const DensMatElements<S> &, const Stats<S> &stats) override
{
const double temperature = P.gtp * step.scale(); // in absolute units! stats.Zgt is evaluated for this temperature.
const auto stat_factor = [beta = 1.0/temperature, Z = stats.Zgt](const auto E1, const auto Ep) {
return beta / (exp(+beta*E1) + exp(+beta*Ep)) * pow(E1 - Ep, n)/Z; // n is template parameter
};
const auto term = [&diagI1, &diagIp, &op1, &op2, &stat_factor](const auto r1, const auto rp) {
const auto E1 = diagI1.values.abs_zero(r1);
const auto Ep = diagIp.values.abs_zero(rp);
return conj_me(op1(r1, rp)) * op2(r1, rp) * stat_factor(E1,Ep);
};
weight_traits<S> value{};
for (const auto r1: diagI1.kept())
for (const auto rp: diagIp.kept())
value += term(r1, rp);
ct->add(temperature, factor * value);
}
void end([[maybe_unused]] const Step &) override {
td.merge(*ct.get());
}
~Algo_GT() { td.save(); }
};
// Calculation of the temperature-dependent susceptibility chi_AB(T) using the linear response theory and the matrix
// elements of global operators. Binning needs to be turned off. Note that Zchit needs to be calculated with the same
// 'temperature' parameter that we use for the exponential functions in the following equation. The output is
// chi/beta = k_B T chi, as we prefer.
template<scalar S, typename Matrix = Matrix_traits<S>, typename t_coef = coef_traits<S>, typename t_eigen = eigen_traits<S>>
class Algo_CHIT : public Algo<S> {
private:
inline static const std::string algoname = "CHIT";
TempDependence<S> td;
using CT = ChainTempDependence<S>;
std::unique_ptr<CT> ct;
public:
using Algo<S>::P;
Algo_CHIT(const std::string &name, const std::string &prefix, const gf_type gt, const Params &P) :
Algo<S>(P), td(name, algoname, spec_fn(name, prefix, algoname), P) {
my_assert(gt == gf_type::bosonic);
}
void begin(const Step &) override { ct = std::make_unique<CT>(P); }
void calc(const Step &step, const Eigen<S> &diagIp, const Eigen<S> &diagI1, const Matrix &op1, const Matrix &op2,
t_coef factor, const Invar &, const Invar &, const DensMatElements<S> &, const Stats<S> &stats) override
{
const double temperature = P.chitp * step.scale(); // in absolute units! stats.Zchit is evaluated for this temperature.
const auto stat_factor = [temperature, Z = stats.Zchit](const auto E1, const auto Ep) {
return chit_weight(E1, Ep, 1.0/temperature)/Z;
};
const auto term = [&diagI1, &diagIp, &op1, &op2, &stat_factor](const auto r1, const auto rp) {
const auto E1 = diagI1.values.abs_zero(r1);
const auto Ep = diagIp.values.abs_zero(rp);
return conj_me(op1(r1, rp)) * op2(r1, rp) * stat_factor(E1,Ep);
};
weight_traits<S> value{};
for (const auto r1: diagI1.kept())
for (const auto rp: diagIp.kept())
value += term(r1, rp);
ct->add(temperature, factor * value);
}
void end([[maybe_unused]] const Step &) override {
td.merge(*ct.get());
}
~Algo_CHIT() { td.save(); }
};
} // namespace
#endif
| 8,322
|
C++
|
.h
| 170
| 43.958824
| 162
| 0.640015
|
rokzitko/nrgljubljana
| 31
| 8
| 4
|
GPL-3.0
|
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.