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,736
nrg-recalc-ISOLR.hpp
rokzitko_nrgljubljana/c++/symmetry/nrg-recalc-ISOLR.hpp
namespace NRG { // *** WARNING!!! Modify nrg-recalc-ISOLR.cc.m4, not nrg-recalc-ISOLR.cc !!! // Quantum number dependent recalculation routines // Rok Zitko, rok.zitko@ijs.si, Feb 2006, June 2006, Nov 2007 // This file pertains to (I,S,P) subspaces namespace NRG { // m4 macros for nrg-recalc-*.cc files // Rok Zitko, rok.zitko@ijs.si, 2007-2020 } // (ISOLR): 8 calls of recalc_f() are necessary: different parities are also possible! template<typename SC> Opch<SC> SymmetryISOLR<SC>::recalc_irreduc(const Step &step, const DiagInfo<SC> &diag) const { Opch<SC> opch(P); for(const auto &[Ip, eig]: diag) { Invar I1; // NOTE: ii,ss only couples to ii+-1,ss+-1 in general, even for // several channels. int iip = Ip.get("II"); int ssp = Ip.get("SS"); // IMPORTANT NEW ELEMENT: the parity is important here!! int pp = Ip.get("P"); // nn is index n of f_n, the last site in the chain prior to adding // the new site (f_{n+1}). int NN = step.getnn(); // Both parities yield non-zero <I+-1/2, S+-1/2, P| a^\mu_\nu // |I,S,P'>. Coefficients *DO* depend on P,P', or more accurately, // on whether or not P and P' are the same. // // Observation: due to reflection symmetry, the coefficient for 'a' and // 'b' (2 channels) are either all the same or differ in sign. // ****** CASE I: SAME PARITY ****** I1 = Invar(iip + 1, ssp + 1, pp); { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spinup-isoupa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spinup-isoupa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spinup-isoupb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spinup-isoupb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(iip + 1, ssp - 1, pp); { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spindown-isoupa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spindown-isoupa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spindown-isoupb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spindown-isoupb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(iip - 1, ssp + 1, pp); { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spinup-isodowna.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spinup-isodowna.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spinup-isodownb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spinup-isodownb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(iip - 1, ssp - 1, pp); { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spindown-isodowna.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spindown-isodowna.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spindown-isodownb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spindown-isodownb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; // ****** CASE II: DIFFERENT PARITY ****** I1 = Invar(iip + 1, ssp + 1, -pp); { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spinup-isoupdiffa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spinup-isoupdiffa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spinup-isoupdiffb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spinup-isoupdiffb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(iip + 1, ssp - 1, -pp); { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spindown-isoupdiffa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spindown-isoupdiffa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spindown-isoupdiffb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spindown-isoupdiffb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(iip - 1, ssp + 1, -pp); { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spinup-isodowndiffa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spinup-isodowndiffa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spinup-isodowndiffb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spinup-isodowndiffb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(iip - 1, ssp - 1, -pp); { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spindown-isodowndiffa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spindown-isodowndiffa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "isolr/isolr-2ch-spindown-isodowndiffb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "isolr/isolr-2ch-spindown-isodowndiffb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; } return opch; } // Recalculate matrix elements of a doublet tensor operator [EVEN PARITY] template<typename SC> MatrixElements<SC> SymmetryISOLR<SC>::recalc_doublet(const DiagInfo<SC> &diag, const MatrixElements<SC> &cold) const { MatrixElements<SC> cnew; for(const auto &[I1, eig]: diag) { int ii1 = I1.get("II"); int ss1 = I1.get("SS"); int p1 = I1.get("P"); Invar Ip; Ip = Invar(ii1 - 1, ss1 + 1, p1); { nrglog('f', "RECALC(fn=" << "isolr/isolr-2ch-doubletmp.dat" << ", Iop=" << Invar(2, 2, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "isolr/isolr-2ch-doubletmp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(2, 2, +1)); } } }; Ip = Invar(ii1 - 1, ss1 - 1, p1); { nrglog('f', "RECALC(fn=" << "isolr/isolr-2ch-doubletmm.dat" << ", Iop=" << Invar(2, 2, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "isolr/isolr-2ch-doubletmm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(2, 2, +1)); } } }; Ip = Invar(ii1 + 1, ss1 + 1, p1); { nrglog('f', "RECALC(fn=" << "isolr/isolr-2ch-doubletpp.dat" << ", Iop=" << Invar(2, 2, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "isolr/isolr-2ch-doubletpp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(2, 2, +1)); } } }; Ip = Invar(ii1 + 1, ss1 - 1, p1); { nrglog('f', "RECALC(fn=" << "isolr/isolr-2ch-doubletpm.dat" << ", Iop=" << Invar(2, 2, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "isolr/isolr-2ch-doubletpm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(2, 2, +1)); } } }; } return cnew; } // Recalculate matrix elements of a triplet tensor operator [EVEN PARITY] template<typename SC> MatrixElements<SC> SymmetryISOLR<SC>::recalc_triplet(const DiagInfo<SC> &diag, const MatrixElements<SC> &cold) const { MatrixElements<SC> cnew; for(const auto &[I1, eig]: diag) { int ii1 = I1.get("II"); int ss1 = I1.get("SS"); int p1 = I1.get("P"); Invar Ip; Ip = Invar(ii1, ss1, p1); { nrglog('f', "RECALC(fn=" << "isolr/isolr-2ch-triplets.dat" << ", Iop=" << Invar(1, 3, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "isolr/isolr-2ch-triplets.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 3, +1)); } } }; Ip = Invar(ii1, ss1 + 2, p1); { nrglog('f', "RECALC(fn=" << "isolr/isolr-2ch-tripletp.dat" << ", Iop=" << Invar(1, 3, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "isolr/isolr-2ch-tripletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 3, +1)); } } }; Ip = Invar(ii1, ss1 - 2, p1); { nrglog('f', "RECALC(fn=" << "isolr/isolr-2ch-tripletm.dat" << ", Iop=" << Invar(1, 3, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "isolr/isolr-2ch-tripletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 3, +1)); } } }; } return cnew; } }
13,819
C++
.h
351
35.205128
118
0.592444
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,737
nrg-recalc-SPSU2LR.hpp
rokzitko_nrgljubljana/c++/symmetry/nrg-recalc-SPSU2LR.hpp
namespace NRG { // *** WARNING!!! Modify nrg-recalc-SPSU2LR.cc.m4, not nrg-recalc-SPSU2LR.cc !!! // Quantum number dependant recalculation routines // Rok Zitko, rok.zitko@ijs.si, Sep 2015 // This file pertains to (S,P) subspaces namespace NRG { // m4 macros for nrg-recalc-*.cc files // Rok Zitko, rok.zitko@ijs.si, 2007-2020 } template<typename SC> MatrixElements<SC> SymmetrySPSU2LR<SC>::recalc_doublet(const DiagInfo<SC> &diag, const MatrixElements<SC> &cold) const { MatrixElements<SC> cnew; for(const auto &[I1, eig]: diag) { int ss1 = I1.get("SS"); int p1 = I1.get("P"); Invar Ip; Ip = Invar(ss1 + 1, p1); { nrglog('f', "RECALC(fn=" << "spsu2lr/spsu2lr-2ch-doubletp.dat" << ", Iop=" << Invar(-1, 1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "spsu2lr/spsu2lr-2ch-doubletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(-1, 1)); } } }; Ip = Invar(ss1 - 1, p1); { nrglog('f', "RECALC(fn=" << "spsu2lr/spsu2lr-2ch-doubletm.dat" << ", Iop=" << Invar(+1, 1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "spsu2lr/spsu2lr-2ch-doubletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(+1, 1)); } } }; } return cnew; } template<typename SC> Opch<SC> SymmetrySPSU2LR<SC>::recalc_irreduc(const Step &step, const DiagInfo<SC> &diag) const { Opch<SC> opch(P); for(const auto &[Ip, eig]: diag) { int ssp = Ip.get("SS"); int pp = Ip.get("P"); Invar I1; // CASE I: SAME PARITY I1 = Invar(ssp + 1, pp); { nrglog('f', "RECALC_F(fn=" << "spsu2lr/spsu2lr-2ch-spinupa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "spsu2lr/spsu2lr-2ch-spinupa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "spsu2lr/spsu2lr-2ch-spinupb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "spsu2lr/spsu2lr-2ch-spinupb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(ssp - 1, pp); { nrglog('f', "RECALC_F(fn=" << "spsu2lr/spsu2lr-2ch-spindowna.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "spsu2lr/spsu2lr-2ch-spindowna.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "spsu2lr/spsu2lr-2ch-spindownb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "spsu2lr/spsu2lr-2ch-spindownb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; // CASE II: OPPOSITE PARITY I1 = Invar(ssp + 1, -pp); { nrglog('f', "RECALC_F(fn=" << "spsu2lr/spsu2lr-2ch-spinupdiffa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "spsu2lr/spsu2lr-2ch-spinupdiffa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "spsu2lr/spsu2lr-2ch-spinupdiffb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "spsu2lr/spsu2lr-2ch-spinupdiffb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(ssp - 1, -pp); { nrglog('f', "RECALC_F(fn=" << "spsu2lr/spsu2lr-2ch-spindowndiffa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "spsu2lr/spsu2lr-2ch-spindowndiffa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "spsu2lr/spsu2lr-2ch-spindowndiffb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "spsu2lr/spsu2lr-2ch-spindowndiffb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; } return opch; } template<typename SC> MatrixElements<SC> SymmetrySPSU2LR<SC>::recalc_triplet(const DiagInfo<SC> &diag, const MatrixElements<SC> &cold) const { MatrixElements<SC> cnew; for(const auto &[I1, eig]: diag) { int ss1 = I1.get("SS"); int p1 = I1.get("P"); Invar Ip; Ip = Invar(ss1, p1); { nrglog('f', "RECALC(fn=" << "spsu2lr/spsu2lr-2ch-triplets.dat" << ", Iop=" << Invar(0, 1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "spsu2lr/spsu2lr-2ch-triplets.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 1)); } } }; Ip = Invar(ss1 + 2, p1); { nrglog('f', "RECALC(fn=" << "spsu2lr/spsu2lr-2ch-tripletp.dat" << ", Iop=" << Invar(-2, 1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "spsu2lr/spsu2lr-2ch-tripletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(-2, 1)); } } }; Ip = Invar(ss1 - 2, p1); { nrglog('f', "RECALC(fn=" << "spsu2lr/spsu2lr-2ch-tripletm.dat" << ", Iop=" << Invar(+2, 1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "spsu2lr/spsu2lr-2ch-tripletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(+2, 1)); } } }; } return cnew; } }
7,678
C++
.h
207
33.024155
120
0.598197
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,738
sym-QS-impl.hpp
rokzitko_nrgljubljana/c++/symmetry/sym-QS-impl.hpp
namespace NRG { template<typename SC> class SymmetryQS : public Symmetry<SC> { private: using Symmetry<SC>::P; using Symmetry<SC>::In; using Symmetry<SC>::QN; public: using Matrix = typename traits<SC>::Matrix; using t_matel = typename traits<SC>::t_matel; SymmetryQS(const Params &P) : Symmetry<SC>(P, std::vector{"<Sz^2>", "<Q>", "<Q^2>"}, Invar(0,1), Invar(1,2)) { initInvar({ {"Q", additive}, // charge {"SS", additive} // spin }); } // Multiplicity of the (Q,SS) subspace is 2S+1 = SS. size_t mult(const Invar &I) const override { return I.get("SS"); } bool triangle_inequality(const Invar &I1, const Invar &I2, const Invar &I3) const override { return u1_equality(I1.get("Q"), I2.get("Q"), I3.get("Q")) && su2_triangle_inequality(I1.get("SS"), I2.get("SS"), I3.get("SS")); } bool Invar_allowed(const Invar &I) const override { return I.get("SS") > 0; } void load() override { if (!P.substeps) { switch (P.channels) { case 1: #include "qs/qs-1ch-In2.dat" #include "qs/qs-1ch-QN.dat" break; case 2: #include "qs/qs-2ch-In2.dat" #include "qs/qs-2ch-QN.dat" break; case 3: #include "qs/qs-3ch-In2.dat" #include "qs/qs-3ch-QN.dat" break; case 4: #include "qs/qs-4ch-In2.dat" #include "qs/qs-4ch-QN.dat" break; default: my_assert_not_reached(); } } else { #include "qs/qs-1ch-In2.dat" #include "qs/qs-1ch-QN.dat" } } double dynamicsusceptibility_factor(const Invar &Ip, const Invar &I1) const override { check_diff(Ip, I1, "Q", 0); const auto ssp = Ip.get("SS"); const auto ss1 = I1.get("SS"); my_assert((abs(ss1 - ssp) == 2 || ss1 == ssp)); return switch3(ss1, ssp + 2, 1. + (ssp - 1) / 3., ssp, ssp / 3., ssp - 2, (-2. + ssp) / 3.); } double specdens_factor(const Invar &Ip, const Invar &I1) const override { check_diff(Ip, I1, "Q", 1); const auto ssp = Ip.get("SS"); const auto ss1 = I1.get("SS"); my_assert(abs(ss1 - ssp) == 1); return (ss1 == ssp + 1 ? S(ssp) + 1.0 : S(ssp)); } void calculate_TD(const Step &step, const DiagInfo<SC> &diag, Stats<SC> &stats, const double factor) const override { auto trSZ = 0.0, trQ = 0.0, trQ2 = 0.0; // Tr[S_z^2], Tr[Q], Tr[Q^2] for (const auto &[I, eig]: diag) { const auto ss = I.get("SS"); const auto q = I.get("Q"); const auto sumZ = this->calculate_Z(I, eig, factor); trQ += sumZ * q; trQ2 += sumZ * q * q; trSZ += sumZ * (ss * ss - 1) / 12.; } stats.td.set("<Sz^2>", trSZ / stats.Z); stats.td.set("<Q>", trQ / stats.Z); stats.td.set("<Q^2>", trQ2 / stats.Z); } bool project_subspace(const Invar &I, const std::string &p) const override { if (p == ""s || p == "trivial"s) { return true; } else if (p == "evenQ"s) { return is_even(I.get("Q")); } else if (p == "oddQ"s) { return is_odd(I.get("Q")); } else throw std::runtime_error(fmt::format("Unknown projection type {} for symmetry QS.", p)); } DECL; HAS_DOUBLET; HAS_TRIPLET; HAS_GLOBAL; HAS_SUBSTEPS; void show_coefficients(const Step &, const Coef<SC> &) const override; }; // *** Helper macros for make_matrix() members in matrix.cc #undef OFFDIAG #define OFFDIAG(i, j, ch, factor0) offdiag_function(step, i, j, ch, 0, t_matel(factor0) * coef.xi(step.N(), ch), h, qq, In, opch) /* i - subspace index ch - channel (0 or 1) number - number of electrons added in channel 'ch' in subspace 'i' */ #undef DIAG #define DIAG(i, ch, number) this->diag_function(step, i, number, coef.zeta(step.N() + 1, ch), h, qq) #undef OFFDIAG_MIX #define OFFDIAG_MIX(i, j, ch, factor) offdiag_function(step, i, j, ch, 0, t_matel(factor) * coef.xiR(step.N(), ch), h, qq, In, opch) #undef RUNGHOP #define RUNGHOP(i, j, factor) this->diag_offdiag_function(step, i, j, t_matel(factor) * coef.zetaR(step.N() + 1, 0), h, qq) template<typename SC> void SymmetryQS<SC>::make_matrix(Matrix &h, const Step &step, const SubspaceDimensions &qq, const Invar &I, const InvarVec &In, const Opch<SC> &opch, const Coef<SC> &coef) const { auto ss = I.get("SS"); if (!P.substeps) { switch (P.channels) { case 1: #include "qs/qs-1ch-offdiag.dat" #include "qs/qs-1ch-diag.dat" break; case 2: #include "qs/qs-2ch-diag.dat" #include "qs/qs-2ch-offdiag.dat" if (P.rungs) { #include "qs/qs-2ch-offdiag-mix.dat" #include "qs/qs-2ch-runghop.dat" } break; case 3: #include "qs/qs-3ch-diag.dat" #include "qs/qs-3ch-offdiag.dat" break; case 4: #include "qs/qs-4ch-diag.dat" #include "qs/qs-4ch-offdiag.dat" break; default: my_assert_not_reached(); } } else { my_assert(P.coeffactor == 1); const auto [N, M] = step.NM(); #undef OFFDIAG #define OFFDIAG(i, j, ch, factor0) offdiag_function(step, i, j, M, 0, t_matel(factor0) * coef.xi(N, M), h, qq, In, opch) #undef DIAG #define DIAG(i, ch, number) this->diag_function(step, i, number, coef.zeta(N + 1, M), h, qq) #include "qs/qs-1ch-offdiag.dat" #include "qs/qs-1ch-diag.dat" if (P.rungs) my_assert_not_reached(); } } template<typename SC> void SymmetryQS<SC>::show_coefficients(const Step &step, const Coef<SC> &coef) const { Symmetry<SC>::show_coefficients(step, coef); if (P.rungs) for (auto i = 0; i < P.channels; i++) std::cout << "[" << i + 1 << "]" << " xi_rung(" << step.N() << ")=" << coef.xiR(step.N(), i) << " zeta_rung(" << step.N() + 1 << ")=" << coef.zetaR(step.N() + 1, i) << std::endl; } } #include "nrg-recalc-QS.hpp"
5,735
C++
.h
155
32.174194
132
0.595392
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,739
nrg-recalc-DBLISOSZ.hpp
rokzitko_nrgljubljana/c++/symmetry/nrg-recalc-DBLISOSZ.hpp
namespace NRG { // *** WARNING!!! Modify nrg-recalc-DBLISOSZ.cc.m4, not nrg-recalc-DBLISOSZ.cc !!! // Quantum number dependant recalculation routines // Rok Zitko, rok.zitko@ijs.si, Mar 2010 // This file pertains to (I1,I2,Sz) subspaces namespace NRG { // m4 macros for nrg-recalc-*.cc files // Rok Zitko, rok.zitko@ijs.si, 2007-2020 } template<typename SC> MatrixElements<SC> SymmetryDBLISOSZ<SC>::recalc_doublet(const DiagInfo<SC> &diag, const MatrixElements<SC> &cold) const { MatrixElements<SC> cnew; for(const auto &[I1, eig]: diag) { int ii11 = I1.get("II1"); int ii21 = I1.get("II2"); int ssz1 = I1.get("SSZ"); Invar Ip; Ip = Invar(ii11 - 1, ii21, ssz1 - 1); { nrglog('f', "RECALC(fn=" << "dblisosz/dblisosz-2ch-doubletm0m.dat" << ", Iop=" << Invar(2, 1, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-doubletm0m.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(2, 1, +1)); } } }; Ip = Invar(ii11 - 1, ii21, ssz1 + 1); { nrglog('f', "RECALC(fn=" << "dblisosz/dblisosz-2ch-doubletm0p.dat" << ", Iop=" << Invar(2, 1, -1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-doubletm0p.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(2, 1, -1)); } } }; Ip = Invar(ii11 + 1, ii21, ssz1 - 1); { nrglog('f', "RECALC(fn=" << "dblisosz/dblisosz-2ch-doubletp0m.dat" << ", Iop=" << Invar(2, 1, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-doubletp0m.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(2, 1, +1)); } } }; Ip = Invar(ii11 + 1, ii21, ssz1 + 1); { nrglog('f', "RECALC(fn=" << "dblisosz/dblisosz-2ch-doubletp0p.dat" << ", Iop=" << Invar(2, 1, -1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-doubletp0p.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(2, 1, -1)); } } }; Ip = Invar(ii11, ii21 - 1, ssz1 - 1); { nrglog('f', "RECALC(fn=" << "dblisosz/dblisosz-2ch-doublet0mm.dat" << ", Iop=" << Invar(1, 2, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-doublet0mm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2, +1)); } } }; Ip = Invar(ii11, ii21 - 1, ssz1 + 1); { nrglog('f', "RECALC(fn=" << "dblisosz/dblisosz-2ch-doublet0mp.dat" << ", Iop=" << Invar(1, 2, -1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-doublet0mp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2, -1)); } } }; Ip = Invar(ii11, ii21 + 1, ssz1 - 1); { nrglog('f', "RECALC(fn=" << "dblisosz/dblisosz-2ch-doublet0pm.dat" << ", Iop=" << Invar(1, 2, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-doublet0pm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2, +1)); } } }; Ip = Invar(ii11, ii21 + 1, ssz1 + 1); { nrglog('f', "RECALC(fn=" << "dblisosz/dblisosz-2ch-doublet0pp.dat" << ", Iop=" << Invar(1, 2, -1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-doublet0pp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2, -1)); } } }; } return cnew; } template<typename SC> Opch<SC> SymmetryDBLISOSZ<SC>::recalc_irreduc(const Step &step, const DiagInfo<SC> &diag) const { Opch<SC> opch(P); for(const auto &[Ip, eig]: diag) { Invar I1; int ii1p = Ip.get("II1"); int ii2p = Ip.get("II2"); int sszp = Ip.get("SSZ"); // NN is index n of f_n, the last site in the chain prior to adding // the new site (f_{n+1}). int NN = step.getnn(); I1 = Invar(ii1p + 1, ii2p, sszp + 1); { nrglog('f', "RECALC_F(fn=" << "dblisosz/dblisosz-2ch-type1-isoup-a.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-type1-isoup-a.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(ii1p + 1, ii2p, sszp - 1); { nrglog('f', "RECALC_F(fn=" << "dblisosz/dblisosz-2ch-type2-isoup-a.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-type2-isoup-a.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(ii1p, ii2p + 1, sszp + 1); { nrglog('f', "RECALC_F(fn=" << "dblisosz/dblisosz-2ch-type1-isoup-b.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-type1-isoup-b.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(ii1p, ii2p + 1, sszp - 1); { nrglog('f', "RECALC_F(fn=" << "dblisosz/dblisosz-2ch-type2-isoup-b.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-type2-isoup-b.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(ii1p - 1, ii2p, sszp + 1); { nrglog('f', "RECALC_F(fn=" << "dblisosz/dblisosz-2ch-type1-isodown-a.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-type1-isodown-a.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(ii1p - 1, ii2p, sszp - 1); { nrglog('f', "RECALC_F(fn=" << "dblisosz/dblisosz-2ch-type2-isodown-a.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-type2-isodown-a.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(ii1p, ii2p - 1, sszp + 1); { nrglog('f', "RECALC_F(fn=" << "dblisosz/dblisosz-2ch-type1-isodown-b.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-type1-isodown-b.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(ii1p, ii2p - 1, sszp - 1); { nrglog('f', "RECALC_F(fn=" << "dblisosz/dblisosz-2ch-type2-isodown-b.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "dblisosz/dblisosz-2ch-type2-isodown-b.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; } return opch; } #undef SPINZ #define SPINZ(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) template<typename SC> void SymmetryDBLISOSZ<SC>::recalc_global(const Step &step, const DiagInfo<SC> &diag, const std::string name, MatrixElements<SC> &cnew) const { if (name == "SZtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II{I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 2: #include "dblisosz/dblisosz-2ch-spinz.dat" break; default: my_assert_not_reached(); } } return; } my_assert_not_reached(); } }
10,123
C++
.h
262
34.412214
142
0.59623
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,740
sym-SPU1-impl.hpp
rokzitko_nrgljubljana/c++/symmetry/sym-SPU1-impl.hpp
namespace NRG { template<typename SC> class SymmetrySPU1 : public SymField<SC> { private: using Symmetry<SC>::P; using Symmetry<SC>::In; using Symmetry<SC>::QN; public: using Matrix = typename traits<SC>::Matrix; using t_matel = typename traits<SC>::t_matel; SymmetrySPU1(const Params &P) : SymField<SC>(P, std::vector{"<Sz^2>", "<Sz>"}, Invar(0)) { initInvar({ {"SSZ", additive} // spin projection }); } bool check_SPIN(const Invar &I1, const Invar &Ip, const int &SPIN) const override { // The spin projection of the operator is defined by the difference in Sz of both the invariant subspaces. int ssz1 = I1.get("SSZ"); int sszp = Ip.get("SSZ"); int sszop = ssz1 - sszp; return sszop == SPIN; } bool triangle_inequality(const Invar &I1, const Invar &I2, const Invar &I3) const override { return u1_equality(I1.get("SSZ"), I2.get("SSZ"), I3.get("SSZ")); } void load() override { if (!P.substeps) { switch (P.channels) { case 1: #include "spu1/spu1-1ch-In2.dat" #include "spu1/spu1-1ch-QN.dat" break; case 2: #include "spu1/spu1-2ch-In2.dat" #include "spu1/spu1-2ch-QN.dat" break; default: my_assert_not_reached(); } // switch } else { #include "spu1/spu1-1ch-In2.dat" #include "spu1/spu1-1ch-QN.dat" } } void make_matrix_polarized(Matrix &h, const Step &step, const SubspaceDimensions &qq, const Invar &I, const InvarVec &In, const Opch<SC> &opch, const Coef<SC> &coef) const; void make_matrix_nonpolarized(Matrix &h, const Step &step, const SubspaceDimensions &qq, const Invar &I, const InvarVec &In, const Opch<SC> &opch, const Coef<SC> &coef) const; void calculate_TD(const Step &step, const DiagInfo<SC> &diag, Stats<SC> &stats, const double factor) const override { bucket trSZ, trSZ2; // Tr[S_z], Tr[S_z^2] for (const auto &[I, eig]: diag) { const int ssz = I.get("SSZ"); const double sumZ = this->calculate_Z(I, eig, factor); trSZ += sumZ * SZ(ssz); trSZ2 += sumZ * pow(SZ(ssz),2); } stats.td.set("<Sz^2>", trSZ2 / stats.Z); stats.td.set("<Sz>", trSZ / stats.Z); } DECL; HAS_DOUBLET; HAS_TRIPLET; HAS_GLOBAL; HAS_SUBSTEPS; }; #undef ISOSPINX #define ISOSPINX(i, j, ch, factor) this->diag_offdiag_function(step, i, j, t_matel(factor) * 2.0 * coef.delta(step.N() + 1, ch), h, qq) #undef ANOMALOUS #define ANOMALOUS(i, j, ch, factor) offdiag_function(step, i, j, ch, 0, t_matel(factor) * coef.kappa(step.N(), ch), h, qq, In, opch) #undef OFFDIAG #define OFFDIAG(i, j, ch, factor0) offdiag_function(step, i, j, ch, 0, t_matel(factor0) * coef.xi(step.N(), ch), h, qq, In, opch) #undef DIAG #define DIAG(i, ch, number) this->diag_function(step, i, number, coef.zeta(step.N() + 1, ch), h, qq) template<typename SC> void SymmetrySPU1<SC>::make_matrix_nonpolarized(Matrix &h, const Step &step, const SubspaceDimensions &qq, const Invar &I, const InvarVec &In, const Opch<SC> &opch, const Coef<SC> &coef) const { if (!P.substeps) { switch (P.channels) { case 1: #include "spu1/spu1-1ch-offdiag.dat" #include "spu1/spu1-1ch-anomalous.dat" #include "spu1/spu1-1ch-diag.dat" #include "spu1/spu1-1ch-isospinx.dat" break; case 2: #include "spu1/spu1-2ch-diag.dat" #include "spu1/spu1-2ch-offdiag.dat" #include "spu1/spu1-2ch-anomalous.dat" #include "spu1/spu1-2ch-isospinx.dat" break; default: my_assert_not_reached(); } } else { my_assert(P.coeffactor == 1); const auto [Ntrue, M] = step.NM(); #undef ISOSPINX #define ISOSPINX(i, j, ch, factor) this->diag_offdiag_function(step, i, j, t_matel(factor) * 2.0 * coef.delta(Ntrue + 1, M), h, qq) #undef ANOMALOUS #define ANOMALOUS(i, j, ch, factor) offdiag_function(step, i, j, M, 0, t_matel(factor) * coef.kappa(Ntrue, M), h, qq, In, opch) #undef OFFDIAG #define OFFDIAG(i, j, ch, factor0) offdiag_function(step, i, j, M, 0, t_matel(factor0) * coef.xi(Ntrue, M), h, qq, In, opch) #undef DIAG #define DIAG(i, ch, number) this->diag_function(step, i, number, coef.zeta(Ntrue + 1, M), h, qq) #include "spu1/spu1-1ch-offdiag.dat" #include "spu1/spu1-1ch-anomalous.dat" #include "spu1/spu1-1ch-diag.dat" #include "spu1/spu1-1ch-isospinx.dat" } } #undef ISOSPINX #define ISOSPINX(i, j, ch, factor) this->diag_offdiag_function(step, i, j, t_matel(factor) * 2.0 * coef.delta(step.N() + 1, ch), h, qq) #undef ANOMALOUS #define ANOMALOUS(i, j, ch, factor) offdiag_function(step, i, j, ch, 0, t_matel(factor) * coef.kappa(step.N(), ch), h, qq, In, opch) #undef OFFDIAG_UP #undef OFFDIAG_DOWN #undef DIAG_UP #undef DIAG_DOWN #define OFFDIAG_UP(i, j, ch, factor0) offdiag_function(step, i, j, ch, 0, t_matel(factor0) * coef.xiUP(step.N(), ch), h, qq, In, opch) #define OFFDIAG_DOWN(i, j, ch, factor0) offdiag_function(step, i, j, ch, 0, t_matel(factor0) * coef.xiDOWN(step.N(), ch), h, qq, In, opch) #define DIAG_UP(i, j, ch, number) this->diag_function_half(step, i, number, coef.zetaUP(step.N() + 1, ch), h, qq) #define DIAG_DOWN(i, j, ch, number) this->diag_function_half(step, i, number, coef.zetaDOWN(step.N() + 1, ch), h, qq) template<typename SC> void SymmetrySPU1<SC>::make_matrix_polarized(Matrix &h, const Step &step, const SubspaceDimensions &qq, const Invar &I, const InvarVec &In, const Opch<SC> &opch, const Coef<SC> &coef) const { my_assert(!P.substeps); switch (P.channels) { case 1: #include "spu1/spu1-1ch-offdiag-UP.dat" #include "spu1/spu1-1ch-offdiag-DOWN.dat" #include "spu1/spu1-1ch-anomalous.dat" #include "spu1/spu1-1ch-diag-UP.dat" #include "spu1/spu1-1ch-diag-DOWN.dat" #include "spu1/spu1-1ch-isospinx.dat" break; case 2: #include "spu1/spu1-2ch-diag-UP.dat" #include "spu1/spu1-2ch-diag-DOWN.dat" #include "spu1/spu1-2ch-offdiag-UP.dat" #include "spu1/spu1-2ch-offdiag-DOWN.dat" #include "spu1/spu1-2ch-anomalous.dat" #include "spu1/spu1-2ch-isospinx.dat" break; default: my_assert_not_reached(); } } template<typename SC> void SymmetrySPU1<SC>::make_matrix(Matrix &h, const Step &step, const SubspaceDimensions &qq, const Invar &I, const InvarVec &In, const Opch<SC> &opch, const Coef<SC> &coef) const { if (P.polarized) { make_matrix_polarized(h, step, qq, I, In, opch, coef); } else { make_matrix_nonpolarized(h, step, qq, I, In, opch, coef); } } } #include "nrg-recalc-SPU1.hpp"
6,367
C++
.h
148
39.851351
194
0.678947
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,741
nrg-recalc-SL3.hpp
rokzitko_nrgljubljana/c++/symmetry/nrg-recalc-SL3.hpp
namespace NRG { // *** WARNING!!! Modify nrg-recalc-SL3.cc.m4, not nrg-recalc-SL3.cc !!! // Quantum number dependant recalculation routines // Rok Zitko, rok.zitko@ijs.si, June 2006, Nov 2007, Oct 2010 // This file pertains to the spinless-fermions code. namespace NRG { // m4 macros for nrg-recalc-*.cc files // Rok Zitko, rok.zitko@ijs.si, 2007-2020 } template<typename SC> MatrixElements<SC> SymmetrySL3<SC>::recalc_doublet(const DiagInfo<SC> &diag, const MatrixElements<SC> &cold) const { MatrixElements<SC> cnew; for(const auto &[I1, eig]: diag) { int q11 = I1.get("Q1"); int q21 = I1.get("Q2"); int q31 = I1.get("Q3"); Invar Ip = Invar(q11 - 1, q21, q31); // This is a channel 1 operator { nrglog('f', "RECALC(fn=" << "sl3/sl3-3ch-doublet.dat" << ", Iop=" << Invar(1, 0, 0) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "sl3/sl3-3ch-doublet.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 0, 0)); } } }; } return cnew; } template<typename SC> Opch<SC> SymmetrySL3<SC>::recalc_irreduc(const Step &step, const DiagInfo<SC> &diag) const { Opch<SC> opch(P); for(const auto &[Ip, eig]: diag) { int q1p = Ip.get("Q1"); int q2p = Ip.get("Q2"); int q3p = Ip.get("Q3"); Invar I1; I1 = Invar(q1p + 1, q2p, q3p); { nrglog('f', "RECALC_F(fn=" << "sl3/sl3-3ch-a.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "sl3/sl3-3ch-a.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(q1p, q2p + 1, q3p); { nrglog('f', "RECALC_F(fn=" << "sl3/sl3-3ch-b.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "sl3/sl3-3ch-b.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(q1p, q2p, q3p + 1); { nrglog('f', "RECALC_F(fn=" << "sl3/sl3-3ch-c.dat" << ", ch=" << 2 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "sl3/sl3-3ch-c.dat" }; opch[2][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; } return opch; } #undef QTOT #define QTOT(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef N1 #define N1(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef N2 #define N2(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef N3 #define N3(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) template<typename SC> void SymmetrySL3<SC>::recalc_global(const Step &step, const DiagInfo<SC> &diag, const std::string name, MatrixElements<SC> &cnew) const { if (name == "Qtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; #include "sl3/sl3-3ch-qtot.dat" } return; } if (name == "N1") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; #include "sl3/sl3-3ch-N1.dat" } return; } if (name == "N2") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; #include "sl3/sl3-3ch-N2.dat" } return; } if (name == "N3") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; #include "sl3/sl3-3ch-N3.dat" } return; } my_assert_not_reached(); } }
4,253
C++
.h
127
29.622047
137
0.596135
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,742
nrg-recalc-QS.hpp
rokzitko_nrgljubljana/c++/symmetry/nrg-recalc-QS.hpp
namespace NRG { // *** WARNING!!! Modify nrg-recalc-QS.cc.m4, not nrg-recalc-QS.cc !!! // Quantum number dependant recalculation routines // Rok Zitko, rok.zitko@ijs.si, Feb 2006 // This file pertains to (Q,S) subspaces namespace NRG { // m4 macros for nrg-recalc-*.cc files // Rok Zitko, rok.zitko@ijs.si, 2007-2020 } template<typename SC> MatrixElements<SC> SymmetryQS<SC>::recalc_doublet(const DiagInfo<SC> &diag, const MatrixElements<SC> &cold) const { MatrixElements<SC> cnew; if (!P.substeps) { for(const auto &[I1, eig]: diag) { int q1 = I1.get("Q"); int ss1 = I1.get("SS"); Invar Ip; Ip = Invar(q1 - 1, ss1 + 1); switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "qs/qs-1ch-doubletp.dat" << ", Iop=" << Invar(1, 2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-1ch-doubletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2)); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "qs/qs-2ch-doubletp.dat" << ", Iop=" << Invar(1, 2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-2ch-doubletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2)); } } } } break; case 3: { { nrglog('f', "RECALC(fn=" << "qs/qs-3ch-doubletp.dat" << ", Iop=" << Invar(1, 2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-3ch-doubletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2)); } } } } break; case 4: { { nrglog('f', "RECALC(fn=" << "qs/qs-4ch-doubletp.dat" << ", Iop=" << Invar(1, 2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-4ch-doubletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2)); } } } } break; default: my_assert_not_reached(); }; Ip = Invar(q1-1, ss1-1); switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "qs/qs-1ch-doubletm.dat" << ", Iop=" << Invar(1, 2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-1ch-doubletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2)); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "qs/qs-2ch-doubletm.dat" << ", Iop=" << Invar(1, 2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-2ch-doubletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2)); } } } } break; case 3: { { nrglog('f', "RECALC(fn=" << "qs/qs-3ch-doubletm.dat" << ", Iop=" << Invar(1, 2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-3ch-doubletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2)); } } } } break; case 4: { { nrglog('f', "RECALC(fn=" << "qs/qs-4ch-doubletm.dat" << ", Iop=" << Invar(1, 2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-4ch-doubletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2)); } } } } break; default: my_assert_not_reached(); }; } } else { for(const auto &[I1, eig]: diag) { int q1 = I1.get("Q"); int ss1 = I1.get("SS"); Invar Ip; Ip = Invar(q1 - 1, ss1 + 1); { nrglog('f', "RECALC(fn=" << "qs/qs-1ch-doubletp.dat" << ", Iop=" << Invar(1, 2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-1ch-doubletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2)); } } }; Ip = Invar(q1 - 1, ss1 - 1); { nrglog('f', "RECALC(fn=" << "qs/qs-1ch-doubletm.dat" << ", Iop=" << Invar(1, 2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-1ch-doubletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, 2)); } } }; } } return cnew; } // (QS): Two calls of recalc_f() are necessary (for S+1/2 and S-1/2) // for each channel. // See Krishna-Murthy p. 1034, equation (B10). // <I1 | f^dag | Ip>, hence q1=qp+1 // Driver routine for recalc_f() template<typename SC> Opch<SC> SymmetryQS<SC>::recalc_irreduc(const Step &step, const DiagInfo<SC> &diag) const { Opch<SC> opch(P); for(const auto &[Ip, eig]: diag) { int qp = Ip.get("Q"); int ssp = Ip.get("SS"); Invar I1; // NOTE: q,ss only couples to q+1,ss+-1 in general, even for // several channels. I1 = Invar(qp + 1, ssp + 1); switch (P.channels) { case 1: { { nrglog('f', "RECALC_F(fn=" << "qs/qs-1ch-spinupa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-1ch-spinupa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; case 2: { { nrglog('f', "RECALC_F(fn=" << "qs/qs-2ch-spinupa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-2ch-spinupa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qs/qs-2ch-spinupb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-2ch-spinupb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; case 3: { { nrglog('f', "RECALC_F(fn=" << "qs/qs-3ch-spinupa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-3ch-spinupa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qs/qs-3ch-spinupb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-3ch-spinupb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qs/qs-3ch-spinupc.dat" << ", ch=" << 2 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-3ch-spinupc.dat" }; opch[2][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; case 4: { { nrglog('f', "RECALC_F(fn=" << "qs/qs-4ch-spinupa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-4ch-spinupa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qs/qs-4ch-spinupb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-4ch-spinupb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qs/qs-4ch-spinupc.dat" << ", ch=" << 2 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-4ch-spinupc.dat" }; opch[2][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qs/qs-4ch-spinupd.dat" << ", ch=" << 3 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-4ch-spinupd.dat" }; opch[3][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; default: my_assert_not_reached(); }; I1 = Invar(qp+1, ssp-1); switch (P.channels) { case 1: { { nrglog('f', "RECALC_F(fn=" << "qs/qs-1ch-spindowna.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-1ch-spindowna.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; case 2: { { nrglog('f', "RECALC_F(fn=" << "qs/qs-2ch-spindowna.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-2ch-spindowna.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qs/qs-2ch-spindownb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-2ch-spindownb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; case 3: { { nrglog('f', "RECALC_F(fn=" << "qs/qs-3ch-spindowna.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-3ch-spindowna.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qs/qs-3ch-spindownb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-3ch-spindownb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qs/qs-3ch-spindownc.dat" << ", ch=" << 2 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-3ch-spindownc.dat" }; opch[2][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; case 4: { { nrglog('f', "RECALC_F(fn=" << "qs/qs-4ch-spindowna.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-4ch-spindowna.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qs/qs-4ch-spindownb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-4ch-spindownb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qs/qs-4ch-spindownc.dat" << ", ch=" << 2 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-4ch-spindownc.dat" }; opch[2][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qs/qs-4ch-spindownd.dat" << ", ch=" << 3 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-4ch-spindownd.dat" }; opch[3][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; default: my_assert_not_reached(); }; } return opch; } // Driver routine for recalc_f() for substeps=true, i.e., chain by chain diagonalisations template<typename SC> OpchChannel<SC> SymmetryQS<SC>::recalc_irreduc_substeps(const Step &step, const DiagInfo<SC> &diag, const int M) const { Opch<SC> opch(P); for(const auto &[Ip, eig]: diag) { int qp = Ip.get("Q"); int ssp = Ip.get("SS"); Invar I1; I1 = Invar(qp + 1, ssp + 1); { nrglog('f', "RECALC_F(fn=" << "qs/qs-1ch-spinupa.dat" << ", ch=" << M << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-1ch-spinupa.dat" }; opch[M][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(qp + 1, ssp - 1); { nrglog('f', "RECALC_F(fn=" << "qs/qs-1ch-spindowna.dat" << ", ch=" << M << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qs/qs-1ch-spindowna.dat" }; opch[M][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; } return opch[M]; } // Recalculate matrix elements of a triplet tenzor operator template<typename SC> MatrixElements<SC> SymmetryQS<SC>::recalc_triplet(const DiagInfo<SC> &diag, const MatrixElements<SC> &cold) const { MatrixElements<SC> cnew; if (!P.substeps) { for(const auto &[I1, eig]: diag) { int q1 = I1.get("Q"); int ss1 = I1.get("SS"); Invar Ip; Ip = Invar(q1, ss1); switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "qs/qs-1ch-triplets.dat" << ", Iop=" << Invar(0, 3) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-1ch-triplets.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 3)); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "qs/qs-2ch-triplets.dat" << ", Iop=" << Invar(0, 3) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-2ch-triplets.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 3)); } } } } break; case 3: { { nrglog('f', "RECALC(fn=" << "qs/qs-3ch-triplets.dat" << ", Iop=" << Invar(0, 3) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-3ch-triplets.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 3)); } } } } break; case 4: { { nrglog('f', "RECALC(fn=" << "qs/qs-4ch-triplets.dat" << ", Iop=" << Invar(0, 3) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-4ch-triplets.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 3)); } } } } break; default: my_assert_not_reached(); }; Ip = Invar(q1, ss1+2); switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "qs/qs-1ch-tripletp.dat" << ", Iop=" << Invar(0, 3) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-1ch-tripletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 3)); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "qs/qs-2ch-tripletp.dat" << ", Iop=" << Invar(0, 3) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-2ch-tripletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 3)); } } } } break; case 3: { { nrglog('f', "RECALC(fn=" << "qs/qs-3ch-tripletp.dat" << ", Iop=" << Invar(0, 3) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-3ch-tripletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 3)); } } } } break; case 4: { { nrglog('f', "RECALC(fn=" << "qs/qs-4ch-tripletp.dat" << ", Iop=" << Invar(0, 3) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-4ch-tripletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 3)); } } } } break; default: my_assert_not_reached(); }; Ip = Invar(q1, ss1-2); switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "qs/qs-1ch-tripletm.dat" << ", Iop=" << Invar(0, 3) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-1ch-tripletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 3)); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "qs/qs-2ch-tripletm.dat" << ", Iop=" << Invar(0, 3) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-2ch-tripletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 3)); } } } } break; case 3: { { nrglog('f', "RECALC(fn=" << "qs/qs-3ch-tripletm.dat" << ", Iop=" << Invar(0, 3) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-3ch-tripletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 3)); } } } } break; case 4: { { nrglog('f', "RECALC(fn=" << "qs/qs-4ch-tripletm.dat" << ", Iop=" << Invar(0, 3) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qs/qs-4ch-tripletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 3)); } } } } break; default: my_assert_not_reached(); }; } } else my_assert_not_reached(); return cnew; } #undef QDIFF #define QDIFF(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef Q1 #define Q1(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef Q2 #define Q2(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef QTOT #define QTOT(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) template<typename SC> void SymmetryQS<SC>::recalc_global(const Step &step, const DiagInfo<SC> &diag, std::string name, MatrixElements<SC> &cnew) const { // AAA: m4 macros!! RECALC_GLOBAL("Qdiff", ...) if (name == "Qdiff") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 2: #include "qs/qs-2ch-qdiff.dat" break; default: my_assert_not_reached(); } } return; } if (name == "Q1") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 2: #include "qs/qs-2ch-q1.dat" break; default: my_assert_not_reached(); } } return; } if (name == "Q2") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 2: #include "qs/qs-2ch-q2.dat" break; default: my_assert_not_reached(); } } return; } if (name == "Qtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 2: #include "qs/qs-2ch-qtot.dat" break; default: my_assert_not_reached(); } } return; } my_assert_not_reached(); } #undef Q2 }
24,959
C++
.h
696
31.550287
120
0.572508
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,743
sym-QSC3-impl.hpp
rokzitko_nrgljubljana/c++/symmetry/sym-QSC3-impl.hpp
namespace NRG { template<typename SC> class SymmetryQSC3 : public SymC3<SC> { private: using Symmetry<SC>::P; using Symmetry<SC>::In; using Symmetry<SC>::QN; public: using Matrix = typename traits<SC>::Matrix; using t_matel = typename traits<SC>::t_matel; SymmetryQSC3(const Params &P) : SymC3<SC>(P, std::vector{"<Sz^2>", "<Q>", "<Q^2>"}, Invar(0,1,0)) { initInvar({ {"Q", additive}, // charge {"SS", additive}, // spin {"P", mod3} // C_3 rep }); } // Multiplicity of the I=(Q,SS,P) subspace = 2S+1 = SS. size_t mult(const Invar &I) const override { return I.get("SS"); // spin multiplicity } bool Invar_allowed(const Invar &I) const override { return I.get("SS") > 0; } bool triangle_inequality(const Invar &I1, const Invar &I2, const Invar &I3) const override { return u1_equality(I1.get("Q"), I2.get("Q"), I3.get("Q")) && su2_triangle_inequality(I1.get("SS"), I2.get("SS"), I3.get("SS")) && c3_equality(I1.get("P"), I2.get("P"), I3.get("P")); } void load() override { my_assert(P.channels == 3); #include "qsc3/qsc3-In2.dat" #include "qsc3/qsc3-QN.dat" } double dynamicsusceptibility_factor(const Invar &Ip, const Invar &I1) const override { check_diff(Ip, I1, "Q", 0); check_diff(Ip, I1, "P", 0); const int ssp = Ip.get("SS"); const int ss1 = I1.get("SS"); my_assert((abs(ss1 - ssp) == 2 || ss1 == ssp)); return switch3(ss1, ssp + 2, 1. + (ssp - 1) / 3., ssp, ssp / 3., ssp - 2, (-2. + ssp) / 3.); } double specdens_factor(const Invar &Ip, const Invar &I1) const override { check_diff(Ip, I1, "Q", 1); check_diff(Ip, I1, "P", 0); // only P=0 implemented const int ssp = Ip.get("SS"); const int ss1 = I1.get("SS"); return (ss1 == ssp + 1 ? S(ssp) + 1.0 : S(ssp)); } void calculate_TD(const Step &step, const DiagInfo<SC> &diag, Stats<SC> &stats, const double factor) const override { bucket trSZ2, trQ, trQ2; // Tr[S_z^2], Tr[Q], Tr[Q^2] for (const auto &[I, eig]: diag) { const int ss = I.get("SS"); const int q = I.get("Q"); const double sumZ = this->calculate_Z(I, eig, factor); trQ += sumZ * q; trQ2 += sumZ * q * q; trSZ2 += sumZ * (ss * ss - 1) / 12.; } stats.td.set("<Sz^2>", trSZ2 / stats.Z); stats.td.set("<Q>", trQ / stats.Z); stats.td.set("<Q^2>", trQ2 / stats.Z); } DECL; }; #undef OFFDIAG #define OFFDIAG(i, j, ch, factor0) offdiag_function(step, i, j, ch, 0, t_matel(factor0) * coef.xi(step.N(), ch), h, qq, In, opch) #undef DIAG #define DIAG(i, number) this->diag_function(step, i, number, coef.zeta(step.N() + 1, 0), h, qq) template<typename SC> void SymmetryQSC3<SC>::make_matrix(Matrix &h, const Step &step, const SubspaceDimensions &qq, const Invar &I, const InvarVec &In, const Opch<SC> &opch, const Coef<SC> &coef) const { my_assert(P.channels == 3); int ss = I.get("SS"); #undef Complex #define Complex(x, y) cmpl(x, y) #define sqrt(x) csqrt(x) #include "qsc3/qsc3-diag.dat" #include "qsc3/qsc3-offdiag.dat" #undef sqrt } } #include "nrg-recalc-QSC3.hpp"
3,127
C++
.h
79
35.683544
181
0.607979
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,744
nrg-recalc-SU2.hpp
rokzitko_nrgljubljana/c++/symmetry/nrg-recalc-SU2.hpp
namespace NRG { // *** WARNING!!! Modify nrg-recalc-SU2.cc.m4, not nrg-recalc-SU2.cc !!! // Quantum number dependant recalculation routines // Rok Zitko, rok.zitko@ijs.si, Feb 2006, Sep 2009 // This file pertains to (I) subspaces namespace NRG { // m4 macros for nrg-recalc-*.cc files // Rok Zitko, rok.zitko@ijs.si, 2007-2020 } template<typename SC> MatrixElements<SC> SymmetrySU2<SC>::recalc_doublet(const DiagInfo<SC> &diag, const MatrixElements<SC> &cold) const { MatrixElements<SC> cnew; for(const auto &[I1, eig]: diag) { int ii1 = I1.get("II"); Invar Ip; Ip = Invar(ii1 - 1); switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "su2/su2-1ch-doubletm.dat" << ", Iop=" << Invar(2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "su2/su2-1ch-doubletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(2)); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "su2/su2-2ch-doubletm.dat" << ", Iop=" << Invar(2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "su2/su2-2ch-doubletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(2)); } } } } break; default: my_assert_not_reached(); }; Ip = Invar(ii1+1); switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "su2/su2-1ch-doubletp.dat" << ", Iop=" << Invar(2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "su2/su2-1ch-doubletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(2)); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "su2/su2-2ch-doubletp.dat" << ", Iop=" << Invar(2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "su2/su2-2ch-doubletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(2)); } } } } break; default: my_assert_not_reached(); }; } return cnew; } template<typename SC> Opch<SC> SymmetrySU2<SC>::recalc_irreduc(const Step &step, const DiagInfo<SC> &diag) const { Opch<SC> opch(P); for(const auto &[Ip, eig]: diag) { Invar I1; int iip = Ip.get("II"); // NN is index n of f_n, the last site in the chain prior to adding // the new site (f_{n+1}). int NN = step.getnn(); // RECALC_F_TAB_... (filename, channel_number, matrix_number, array_length) // type 1: [f^dag_UP, f_DO] // type 2: [f^dag_DO, f_UP] I1 = Invar(iip + 1); switch (P.channels) { case 1: { { nrglog('f', "RECALC_F(fn=" << "su2/su2-1ch-type1-isoup-a.dat" << ", ch=" << 0 << ", n=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "su2/su2-1ch-type1-isoup-a.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "su2/su2-1ch-type2-isoup-a.dat" << ", ch=" << 0 << ", n=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "su2/su2-1ch-type2-isoup-a.dat" }; opch[0][1][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; case 2: { { nrglog('f', "RECALC_F(fn=" << "su2/su2-2ch-type1-isoup-a.dat" << ", ch=" << 0 << ", n=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "su2/su2-2ch-type1-isoup-a.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "su2/su2-2ch-type1-isoup-b.dat" << ", ch=" << 1 << ", n=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "su2/su2-2ch-type1-isoup-b.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "su2/su2-2ch-type2-isoup-a.dat" << ", ch=" << 0 << ", n=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "su2/su2-2ch-type2-isoup-a.dat" }; opch[0][1][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "su2/su2-2ch-type2-isoup-b.dat" << ", ch=" << 1 << ", n=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "su2/su2-2ch-type2-isoup-b.dat" }; opch[1][1][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; default: my_assert_not_reached(); }; I1 = Invar(iip-1); switch (P.channels) { case 1: { { nrglog('f', "RECALC_F(fn=" << "su2/su2-1ch-type1-isodown-a.dat" << ", ch=" << 0 << ", n=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "su2/su2-1ch-type1-isodown-a.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "su2/su2-1ch-type2-isodown-a.dat" << ", ch=" << 0 << ", n=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "su2/su2-1ch-type2-isodown-a.dat" }; opch[0][1][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; case 2: { { nrglog('f', "RECALC_F(fn=" << "su2/su2-2ch-type1-isodown-a.dat" << ", ch=" << 0 << ", n=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "su2/su2-2ch-type1-isodown-a.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "su2/su2-2ch-type1-isodown-b.dat" << ", ch=" << 1 << ", n=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "su2/su2-2ch-type1-isodown-b.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "su2/su2-2ch-type2-isodown-a.dat" << ", ch=" << 0 << ", n=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "su2/su2-2ch-type2-isodown-a.dat" }; opch[0][1][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "su2/su2-2ch-type2-isodown-b.dat" << ", ch=" << 1 << ", n=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "su2/su2-2ch-type2-isodown-b.dat" }; opch[1][1][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; default: my_assert_not_reached(); }; } return opch; } #undef SPINX #define SPINX(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef SPINY #define SPINY(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef SPINZ #define SPINZ(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) template<typename SC> void SymmetrySU2<SC>::recalc_global(const Step &step, const DiagInfo<SC> &diag, const std::string name, MatrixElements<SC> &cnew) const { if (name == "SZtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "su2/su2-1ch-spinz.dat" break; case 2: #include "su2/su2-2ch-spinz.dat" break; default: my_assert_not_reached(); } } return; } if constexpr (std::is_same_v<SC, std::complex<double>>) { #undef Complex #define Complex(x, y) cmpl(x, y) if (name == "SYtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "su2/su2-1ch-spiny.dat" break; case 2: #include "su2/su2-2ch-spiny.dat" break; default: my_assert_not_reached(); } } return; } } if (name == "SXtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "su2/su2-1ch-spinx.dat" break; case 2: #include "su2/su2-2ch-spinx.dat" break; default: my_assert_not_reached(); } } return; } my_assert_not_reached(); } }
10,972
C++
.h
304
31.634868
137
0.57464
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,745
sym-SPSU2T-impl.hpp
rokzitko_nrgljubljana/c++/symmetry/sym-SPSU2T-impl.hpp
namespace NRG { template<typename SC> class SymmetrySPSU2T : public Symmetry<SC> { private: using Symmetry<SC>::P; using Symmetry<SC>::In; using Symmetry<SC>::QN; public: using Matrix = typename traits<SC>::Matrix; using t_matel = typename traits<SC>::t_matel; SymmetrySPSU2T(const Params &P) : Symmetry<SC>(P, std::vector{"<Sz^2>", "<Tz^2>"}, Invar(1,0), Invar(2,1)) { initInvar({ {"SS", additive}, // spin {"T", additive} // angular momentum }); } // Multiplicity of the (SS,T) subspace is (2S+1 = SS) times (2T+1). size_t mult(const Invar &I) const override { return I.get("SS") * (2 * I.get("T") + 1); } bool triangle_inequality(const Invar &I1, const Invar &I2, const Invar &I3) const override { return su2_triangle_inequality(I1.get("SS"), I2.get("SS"), I3.get("SS")) && su2_triangle_inequality(2 * I1.get("T") + 1, 2 * I2.get("T") + 1, 2 * I3.get("T") + 1); } bool Invar_allowed(const Invar &I) const override { const bool spin_ok = I.get("SS") > 0; const bool angmom_ok = I.get("T") >= 0; return spin_ok && angmom_ok; } void load() override { my_assert(!P.substeps); my_assert(P.channels == 3); #include "spsu2t/spsu2t-In2.dat" #include "spsu2t/spsu2t-QN.dat" } // load // Same as for SYMTYPE=QS, because spin operators are angular momentum singlets. double dynamicsusceptibility_factor(const Invar &Ip, const Invar &I1) const override { check_diff(Ip, I1, "T", 0); const int ssp = Ip.get("SS"); const int ss1 = I1.get("SS"); my_assert((abs(ss1 - ssp) == 2 || ss1 == ssp)); return switch3(ss1, ssp + 2, 1. + (ssp - 1) / 3., ssp, ssp / 3., ssp - 2, (-2. + ssp) / 3.); } // Creation operator is a spin-doublet, angular-momentum-triplet ! double specdens_factor(const Invar &Ip, const Invar &I1) const override { const int ssp = Ip.get("SS"); const int ss1 = I1.get("SS"); my_assert(abs(ss1 - ssp) == 1); double spinfactor = (ss1 == ssp + 1 ? S(ssp) + 1.0 : S(ssp)); const int tp = Ip.get("T"); const int t1 = I1.get("T"); const int ttp = 2 * tp + 1; const int tt1 = 2 * t1 + 1; my_assert(abs(ttp - tt1) == 2 || ttp == tt1); double angmomfactor = switch3(tt1, ttp + 2, 1. + (ttp - 1) / 3., ttp, ttp / 3., ttp - 2, (-2. + ttp) / 3.); return spinfactor * angmomfactor; } void calculate_TD(const Step &step, const DiagInfo<SC> &diag, Stats<SC> &stats, const double factor) const override { bucket trSZ2, trTZ2; // Tr[S_z^2], Tr[T_z^2] for (const auto &[I, eig]: diag) { const int ss = I.get("SS"); const int t = I.get("T"); const double sumZ = this->calculate_Z(I, eig, factor); trSZ2 += sumZ * (ss * ss - 1) / 12.; // [(2S+1)(2S+1)-1]/12=S(S+1)/3 trTZ2 += sumZ * t * (t + 1) / 3.; } stats.td.set("<Sz^2>", trSZ2 / stats.Z); stats.td.set("<Tz^2>", trTZ2 / stats.Z); } DECL; HAS_DOUBLET; HAS_TRIPLET; bool recalc_f_coupled(const Invar &I1, const Invar &I2, const Invar &If) const override { return triangle_inequality(I1, I2, If); } }; bool spsu2t_exception(const unsigned int i, const unsigned int j, const Invar &I) { // In these cases the subspace exists, but taking the T=2 or T=1 limit shows that the coefficient is actually zero, // so there is no contribution. (Directly computed factor is nan.) This exception handling is added io order to // avoid false positives in error detection assertions. // see spsu2t_exceptions.nb int T = I.get("T"); if (i == 46 && j == 21 && T == 1) return true; if (i == 55 && j == 27 && T == 1) return true; if (i == 5 && j == 38 && T == 2) return true; return false; } #define offdiag_spsu2t(i, j, ch, fnr, factor0, h, qq, In, I, opch) \ { \ const bool contributes = qq.offdiag_contributes(i, j); \ if (contributes) { \ t_matel factor; \ if (spsu2t_exception(i, j, I)) { \ factor = 0; \ } else { \ factor = factor0; \ } \ this->offdiag_function_impl(step, i, j, ch, fnr, factor, h, qq, In, opch); \ } \ }; // We take the coefficients of the first channel (indexed as 0), because all three set are exactly the same due to // orbital symmetry. #undef OFFDIAG #define OFFDIAG(i, j, factor0) offdiag_spsu2t(i, j, 0, 0, t_matel(factor0) * coef.xi(step.N(), 0), h, qq, In, I, opch) #undef DIAG #define DIAG(i, number) this->diag_function(step, i, number, coef.zeta(step.N() + 1, 0), h, qq) #undef ISOSPINX #define ISOSPINX(i, j, factor) this->diag_offdiag_function(step, i, j, t_matel(factor) * 2.0 * coef.delta(step.N() + 1, 0), h, qq) #undef ANOMALOUS #define ANOMALOUS(i, j, factor) offdiag_function(step, i, j, 0, 0, t_matel(factor) * coef.kappa(step.N(), 0), h, qq, In, opch) template<typename SC> void SymmetrySPSU2T<SC>::make_matrix(Matrix &h, const Step &step, const SubspaceDimensions &qq, const Invar &I, const InvarVec &In, const Opch<SC> &opch, const Coef<SC> &coef) const { int ss = I.get("SS"); int t = I.get("T"); double T = t; // crucially important to use floating point! my_assert(!P.substeps); my_assert(P.channels == 3); #include "spsu2t/spsu2t-offdiag.dat" #include "spsu2t/spsu2t-diag.dat" if (!num_equal(coef.delta(step.N() + 1, 0), 0.0)) { #include "spsu2t/spsu2t-isospinx.dat" } if (!num_equal(coef.kappa(step.N(), 0), 0.0)) { #include "spsu2t/spsu2t-anomalous.dat" } } } #include "nrg-recalc-SPSU2T.hpp"
6,873
C++
.h
126
50.626984
183
0.489963
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,746
sym-SPSU2C3-impl.hpp
rokzitko_nrgljubljana/c++/symmetry/sym-SPSU2C3-impl.hpp
namespace NRG { template<typename SC> class SymmetrySPSU2C3 : public SymC3<SC> { private: using Symmetry<SC>::P; using Symmetry<SC>::In; using Symmetry<SC>::QN; public: using Matrix = typename traits<SC>::Matrix; using t_matel = typename traits<SC>::t_matel; SymmetrySPSU2C3(const Params &P) : SymC3<SC>(P, std::vector{"<Sz^2>"}, Invar(1,0)) { initInvar({ {"SS", additive}, // spin {"P", mod3} // C_3 rep }); } size_t mult(const Invar &I) const override { return I.get("SS"); } bool Invar_allowed(const Invar &I) const override { return I.get("SS") > 0; } bool triangle_inequality(const Invar &I1, const Invar &I2, const Invar &I3) const override { return su2_triangle_inequality(I1.get("SS"), I2.get("SS"), I3.get("SS")) && c3_equality(I1.get("P"), I2.get("P"), I3.get("P")); } void load() override { my_assert(P.channels == 3); #include "spsu2c3/spsu2c3-In2.dat" #include "spsu2c3/spsu2c3-QN.dat" } double dynamicsusceptibility_factor(const Invar &Ip, const Invar &I1) const override { const int ssp = Ip.get("SS"); const int ss1 = I1.get("SS"); my_assert((abs(ss1 - ssp) == 2 || ss1 == ssp)); return switch3(ss1, ssp + 2, 1. + (ssp - 1) / 3., ssp, ssp / 3., ssp - 2, (-2. + ssp) / 3.); } double specdens_factor(const Invar &Ip, const Invar &I1) const override { const int ssp = Ip.get("SS"); const int ss1 = I1.get("SS"); return (ss1 == ssp + 1 ? S(ssp) + 1.0 : S(ssp)); } void calculate_TD(const Step &step, const DiagInfo<SC> &diag, Stats<SC> &stats, const double factor) const override { bucket trSZ2; // Tr[S_z^2] for (const auto &[I, eig]: diag) { const int ss = I.get("SS"); const double sumZ = this->calculate_Z(I, eig, factor); trSZ2 += sumZ * (ss * ss - 1) / 12.; } stats.td.set("<Sz^2>", trSZ2 / stats.Z); } DECL; }; #undef ISOSPINX #define ISOSPINX(i, j, factor) this->diag_offdiag_function(step, i, j, t_matel(factor) * 2.0 * coef.delta(step.N() + 1, 0), h, qq) #undef OFFDIAG #define OFFDIAG(i, j, ch, factor0) offdiag_function(step, i, j, ch, 0, t_matel(factor0) * coef.xi(step.N(), ch), h, qq, In, opch) #undef DIAG #define DIAG(i, number) this->diag_function(step, i, number, coef.zeta(step.N() + 1, 0), h, qq) template<typename SC> void SymmetrySPSU2C3<SC>::make_matrix(Matrix &h, const Step &step, const SubspaceDimensions &qq, const Invar &I, const InvarVec &In, const Opch<SC> &opch, const Coef<SC> &coef) const { my_assert(P.channels == 3); int ss = I.get("SS"); #undef Complex #define Complex(x, y) cmpl(x, y) #define sqrt(x) csqrt(x) #include "spsu2c3/spsu2c3-diag.dat" #include "spsu2c3/spsu2c3-offdiag.dat" #include "spsu2c3/spsu2c3-isospinx.dat" #undef sqrt } } #include "nrg-recalc-SPSU2C3.hpp"
2,799
C++
.h
68
37.735294
184
0.643094
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,747
sym-QJ.hpp
rokzitko_nrgljubljana/c++/symmetry/sym-QJ.hpp
namespace NRG { template <typename S> std::unique_ptr<Symmetry<S>> mk_QJ(const Params &P); }
95
C++
.h
4
22.25
52
0.741573
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,748
sym-SPU1.hpp
rokzitko_nrgljubljana/c++/symmetry/sym-SPU1.hpp
namespace NRG { template <typename S> std::unique_ptr<Symmetry<S>> mk_SPU1(const Params &P); }
97
C++
.h
4
22.75
54
0.747253
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,749
nrg-recalc-QSZ.hpp
rokzitko_nrgljubljana/c++/symmetry/nrg-recalc-QSZ.hpp
namespace NRG { // *** WARNING!!! Modify nrg-recalc-QSZ.cc.m4, not nrg-recalc-QSZ.cc !!! // Quantum number dependant recalculation routines // Rok Zitko, rok.zitko@ijs.si, 2006-2020 // This file pertains to (Q,SZ) subspaces namespace NRG { // m4 macros for nrg-recalc-*.cc files // Rok Zitko, rok.zitko@ijs.si, 2007-2020 } // NOTE: p is ket (right side), 1 is bra (left side). OP is sandwiched in between. Thus Q[p] + Q[op] = Q[1]. template<typename SC> MatrixElements<SC> SymmetryQSZ<SC>::recalc_doublet(const DiagInfo<SC> &diag, const MatrixElements<SC> &cold) const { MatrixElements<SC> cnew; if (!P.substeps) { for(const auto &[I1, eig]: diag) { int q1 = I1.get("Q"); int ssz1 = I1.get("SSZ"); Invar Ip; // In the case of (Q,S_z) basis, spin up and spin down are not // equivalent. The distinction appears in this recalculation code, but // also during the evaluation of the spectral densities, where two // spin-diagonal spectral densities (and also spin-flip spectral // density) can be defined. Ip = Invar(q1 - 1, ssz1 + 1); switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "qsz/qsz-1ch-doubletp.dat" << ", Iop=" << Invar(1, -1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-1ch-doubletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, -1)); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "qsz/qsz-2ch-doubletp.dat" << ", Iop=" << Invar(1, -1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-2ch-doubletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, -1)); } } } } break; case 3: { { nrglog('f', "RECALC(fn=" << "qsz/qsz-3ch-doubletp.dat" << ", Iop=" << Invar(1, -1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-3ch-doubletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, -1)); } } } } break; default: my_assert_not_reached(); }; Ip = Invar(q1-1, ssz1-1); switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "qsz/qsz-1ch-doubletm.dat" << ", Iop=" << Invar(1, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-1ch-doubletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, +1)); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "qsz/qsz-2ch-doubletm.dat" << ", Iop=" << Invar(1, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-2ch-doubletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, +1)); } } } } break; case 3: { { nrglog('f', "RECALC(fn=" << "qsz/qsz-3ch-doubletm.dat" << ", Iop=" << Invar(1, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-3ch-doubletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, +1)); } } } } break; default: my_assert_not_reached(); }; } // loop } else { // substeps for(const auto &[I1, eig]: diag) { int q1 = I1.get("Q"); int ssz1 = I1.get("SSZ"); Invar Ip; Ip = Invar(q1 - 1, ssz1 + 1); { nrglog('f', "RECALC(fn=" << "qsz/qsz-1ch-doubletp.dat" << ", Iop=" << Invar(1, -1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-1ch-doubletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, -1)); } } }; Ip = Invar(q1 - 1, ssz1 - 1); { nrglog('f', "RECALC(fn=" << "qsz/qsz-1ch-doubletm.dat" << ", Iop=" << Invar(1, +1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-1ch-doubletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(1, +1)); } } }; } // loop } return cnew; } template<typename SC> Opch<SC> SymmetryQSZ<SC>::recalc_irreduc(const Step &step, const DiagInfo<SC> &diag) const { Opch<SC> opch(P); for(const auto &[Ip, eig]: diag) { int qp = Ip.get("Q"); int sszp = Ip.get("SSZ"); Invar I1; // NOTE: q,ssz only couples to q+1,ssz+-1 in general, even for // several channels. I1 = Invar(qp + 1, sszp + 1); switch (P.channels) { case 1: { { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-1ch-spinupa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-1ch-spinupa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; case 2: { { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-2ch-spinupa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-2ch-spinupa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-2ch-spinupb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-2ch-spinupb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; case 3: { { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-3ch-spinupa.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-3ch-spinupa.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-3ch-spinupb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-3ch-spinupb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-3ch-spinupc.dat" << ", ch=" << 2 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-3ch-spinupc.dat" }; opch[2][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; default: my_assert_not_reached(); }; I1 = Invar(qp+1, sszp-1); switch (P.channels) { case 1: { { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-1ch-spindowna.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-1ch-spindowna.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; case 2: { { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-2ch-spindowna.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-2ch-spindowna.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-2ch-spindownb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-2ch-spindownb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; case 3: { { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-3ch-spindowna.dat" << ", ch=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-3ch-spindowna.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-3ch-spindownb.dat" << ", ch=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-3ch-spindownb.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-3ch-spindownc.dat" << ", ch=" << 2 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-3ch-spindownc.dat" }; opch[2][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; default: my_assert_not_reached(); }; } // loop return opch; } template<typename SC> OpchChannel<SC> SymmetryQSZ<SC>::recalc_irreduc_substeps(const Step &step, const DiagInfo<SC> &diag, const int M) const { Opch<SC> opch(P); for(const auto &[Ip, eig]: diag) { int qp = Ip.get("Q"); int sszp = Ip.get("SSZ"); Invar I1; I1 = Invar(qp + 1, sszp + 1); { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-1ch-spinupa.dat" << ", ch=" << M << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-1ch-spinupa.dat" }; opch[M][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; I1 = Invar(qp + 1, sszp - 1); { nrglog('f', "RECALC_F(fn=" << "qsz/qsz-1ch-spindowna.dat" << ", ch=" << M << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "qsz/qsz-1ch-spindowna.dat" }; opch[M][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; } // loop return opch[M]; } template<typename SC> MatrixElements<SC> SymmetryQSZ<SC>::recalc_triplet(const DiagInfo<SC> &diag, const MatrixElements<SC> &cold) const { MatrixElements<SC> cnew; if (!P.substeps) { for(const auto &[I1, eig]: diag) { int q1 = I1.get("Q"); int ssz1 = I1.get("SSZ"); Invar Ip; Ip = Invar(q1, ssz1); switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "qsz/qsz-1ch-triplets.dat" << ", Iop=" << Invar(0, 0) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-1ch-triplets.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 0)); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "qsz/qsz-2ch-triplets.dat" << ", Iop=" << Invar(0, 0) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-2ch-triplets.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 0)); } } } } break; case 3: { { nrglog('f', "RECALC(fn=" << "qsz/qsz-3ch-triplets.dat" << ", Iop=" << Invar(0, 0) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-3ch-triplets.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, 0)); } } } } break; default: my_assert_not_reached(); }; Ip = Invar(q1, ssz1+2); switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "qsz/qsz-1ch-tripletp.dat" << ", Iop=" << Invar(0, -2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-1ch-tripletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, -2)); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "qsz/qsz-2ch-tripletp.dat" << ", Iop=" << Invar(0, -2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-2ch-tripletp.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, -2)); } } } } break; default: my_assert_not_reached(); }; Ip = Invar(q1, ssz1-2); switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "qsz/qsz-1ch-tripletm.dat" << ", Iop=" << Invar(0, +2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-1ch-tripletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, +2)); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "qsz/qsz-2ch-tripletm.dat" << ", Iop=" << Invar(0, +2) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "qsz/qsz-2ch-tripletm.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(0, +2)); } } } } break; default: my_assert_not_reached(); }; } // loop } else { // substeps my_assert_not_reached(); } return cnew; } #undef SPINZ #define SPINZ(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef Q1U #define Q1U(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef Q1D #define Q1D(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) template<typename SC> void SymmetryQSZ<SC>::recalc_global(const Step &step, const DiagInfo<SC> &diag, const std::string name, MatrixElements<SC> &cnew) const { if (name == "SZtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "qsz/qsz-1ch-spinz.dat" break; case 2: #include "qsz/qsz-2ch-spinz.dat" break; case 3: #include "qsz/qsz-3ch-spinz.dat" break; default: my_assert_not_reached(); } } return; } if (name == "Q1u") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "qsz/qsz-1ch-q1u.dat" break; default: my_assert_not_reached(); } } return; } if (name == "Q1d") { for(const auto &[I1, eig]: diag) { const Twoinvar II = {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "qsz/qsz-1ch-q1d.dat" break; default: my_assert_not_reached(); } } return; } my_assert_not_reached(); } }
18,084
C++
.h
505
31.491089
137
0.578851
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,750
sym-ISOSZLR.hpp
rokzitko_nrgljubljana/c++/symmetry/sym-ISOSZLR.hpp
namespace NRG { template <typename S> std::unique_ptr<Symmetry<S>> mk_ISOSZLR(const Params &P); }
100
C++
.h
4
23.5
57
0.755319
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,751
nrg-recalc-NONE.hpp
rokzitko_nrgljubljana/c++/symmetry/nrg-recalc-NONE.hpp
namespace NRG { // *** WARNING!!! Modify nrg-recalc-NONE.cc.m4, not nrg-recalc-NONE.cc !!! // Quantum number dependent recalculation routines // Rok Zitko, rok.zitko@ijs.si, June 2006, April 2010 // This file pertains to the case with no symmetry. namespace NRG { // m4 macros for nrg-recalc-*.cc files // Rok Zitko, rok.zitko@ijs.si, 2007-2020 } template<typename SC> Opch<SC> SymmetryNONE<SC>::recalc_irreduc(const Step &step, const DiagInfo<SC> &diag) const { Opch<SC> opch(P); for(const auto &[Ip, eig]: diag) { Invar I1 = Invar(); switch (P.channels) { case 1: { { nrglog('f', "RECALC_F(fn=" << "none/none-1ch-a-CR-DO.dat" << ", ch=" << 0 << ", n=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "none/none-1ch-a-CR-DO.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "none/none-1ch-a-CR-UP.dat" << ", ch=" << 0 << ", n=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "none/none-1ch-a-CR-UP.dat" }; opch[0][1][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; } break; case 2: { { nrglog('f', "RECALC_F(fn=" << "none/none-2ch-a-CR-DO.dat" << ", ch=" << 0 << ", n=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "none/none-2ch-a-CR-DO.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "none/none-2ch-b-CR-DO.dat" << ", ch=" << 1 << ", n=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "none/none-2ch-b-CR-DO.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "none/none-2ch-a-CR-UP.dat" << ", ch=" << 0 << ", n=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "none/none-2ch-a-CR-UP.dat" }; opch[0][1][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "none/none-2ch-b-CR-UP.dat" << ", ch=" << 1 << ", n=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "none/none-2ch-b-CR-UP.dat" }; opch[1][1][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } } } break; default: my_assert_not_reached(); }; } return opch; } template<typename SC> MatrixElements<SC> SymmetryNONE<SC>::recalc_doublet(const DiagInfo<SC> &diag, const MatrixElements<SC> &cold) const { MatrixElements<SC> cnew; for(const auto &[I1, eig]: diag) { Invar Ip = Invar(); switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "none/none-1ch-doublet.dat" << ", Iop=" << Invar() << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "none/none-1ch-doublet.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar()); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "none/none-2ch-doublet.dat" << ", Iop=" << Invar() << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "none/none-2ch-doublet.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar()); } } } } break; default: my_assert_not_reached(); }; } return cnew; } #undef SPINX #define SPINX(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef SPINZ #define SPINZ(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) // Isospin operator need an appropriate phase factor (bipartite sublattice index) #define USEISOFACTOR #if defined(USEISOFACTOR) #define ISOFACTOR psgn(step.getnn() + 1) #else #define ISOFACTOR 1 #endif #undef SPINY #define SPINY(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef ISOSPINY #define ISOSPINY(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value * std::complex<double>(ISOFACTOR)) #undef Complex #define Complex(x, y) cmpl(x, y) #undef CHARGE #define CHARGE(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef ISOSPINZ #define ISOSPINZ(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef ISOSPINX #define ISOSPINX(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value *ISOFACTOR) #undef ISOSPINP #define ISOSPINP(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value *ISOFACTOR) #undef ISOSPINM #define ISOSPINM(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value *ISOFACTOR) template<typename SC> void SymmetryNONE<SC>::recalc_global(const Step &step, const DiagInfo<SC> &diag, const std::string name, MatrixElements<SC> &cnew) const { if (name == "SZtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II{I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "none/none-1ch-spinz.dat" break; case 2: #include "none/none-2ch-spinz.dat" break; default: my_assert_not_reached(); } } return; } if constexpr (std::is_same_v<SC, std::complex<double>>) { if (name == "SYtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II{I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "none/none-1ch-spiny.dat" break; case 2: #include "none/none-2ch-spiny.dat" break; default: my_assert_not_reached(); } } return; } } if (name == "SXtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II{I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "none/none-1ch-spinx.dat" break; case 2: #include "none/none-2ch-spinx.dat" break; default: my_assert_not_reached(); } } return; } if (name == "Qtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II{I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "none/none-1ch-Qtot.dat" break; case 2: #include "none/none-2ch-Qtot.dat" break; default: my_assert_not_reached(); } } return; } if (name == "Iztot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "none/none-1ch-Iztot.dat" break; case 2: #include "none/none-2ch-Iztot.dat" break; default: my_assert_not_reached(); } } return; } if (name == "Ixtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "none/none-1ch-Ixtot.dat" break; case 2: #include "none/none-2ch-Ixtot.dat" break; default: my_assert_not_reached(); } } return; } if constexpr (std::is_same_v<SC, std::complex<double>>) { if (name == "Iytot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "none/none-1ch-Iytot.dat" break; case 2: #include "none/none-2ch-Iytot.dat" break; default: my_assert_not_reached(); } } return; } } if (name == "Iptot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "none/none-1ch-Iptot.dat" break; case 2: #include "none/none-2ch-Iptot.dat" break; default: my_assert_not_reached(); } } return; } if (name == "Imtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "none/none-1ch-Imtot.dat" break; case 2: #include "none/none-2ch-Imtot.dat" break; default: my_assert_not_reached(); } } return; } my_assert_not_reached(); } }
9,621
C++
.h
307
26.482085
138
0.587022
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,752
nrg-recalc-P.hpp
rokzitko_nrgljubljana/c++/symmetry/nrg-recalc-P.hpp
namespace NRG { // *** WARNING!!! Modify nrg-recalc-P.cc.m4, not nrg-recalc-P.cc !!! // Quantum number dependent recalculation routines // Rok Zitko, rok.zitko@ijs.si, July 2017 // This file pertains to the case with only fermion number parity. namespace NRG { // m4 macros for nrg-recalc-*.cc files // Rok Zitko, rok.zitko@ijs.si, 2007-2020 } template<typename SC> Opch<SC> SymmetryP<SC>::recalc_irreduc(const Step &step, const DiagInfo<SC> &diag) const { Opch<SC> opch(P); for(const auto &[Ip, eig]: diag) { int p = Ip.get("P"); Invar I1 = Invar(-p); // always the opposite fermion parity! switch (P.channels) { case 1: { { nrglog('f', "RECALC_F(fn=" << "p/p-1ch-a-CR-DO.dat" << ", ch=" << 0 << ", n=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "p/p-1ch-a-CR-DO.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "p/p-1ch-a-CR-UP.dat" << ", ch=" << 0 << ", n=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "p/p-1ch-a-CR-UP.dat" }; opch[0][1][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "p/p-1ch-a-AN-DO.dat" << ", ch=" << 0 << ", n=" << 2 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "p/p-1ch-a-AN-DO.dat" }; opch[0][2][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "p/p-1ch-a-AN-UP.dat" << ", ch=" << 0 << ", n=" << 3 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "p/p-1ch-a-AN-UP.dat" }; opch[0][3][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; } break; case 2: { { nrglog('f', "RECALC_F(fn=" << "p/p-2ch-a-CR-DO.dat" << ", ch=" << 0 << ", n=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "p/p-2ch-a-CR-DO.dat" }; opch[0][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "p/p-2ch-b-CR-DO.dat" << ", ch=" << 1 << ", n=" << 0 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "p/p-2ch-b-CR-DO.dat" }; opch[1][0][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "p/p-2ch-a-CR-UP.dat" << ", ch=" << 0 << ", n=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "p/p-2ch-a-CR-UP.dat" }; opch[0][1][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "p/p-2ch-b-CR-UP.dat" << ", ch=" << 1 << ", n=" << 1 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "p/p-2ch-b-CR-UP.dat" }; opch[1][1][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "p/p-2ch-a-AN-DO.dat" << ", ch=" << 0 << ", n=" << 2 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "p/p-2ch-a-AN-DO.dat" }; opch[0][2][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "p/p-2ch-b-AN-DO.dat" << ", ch=" << 1 << ", n=" << 2 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "p/p-2ch-b-AN-DO.dat" }; opch[1][2][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "p/p-2ch-a-AN-UP.dat" << ", ch=" << 0 << ", n=" << 3 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "p/p-2ch-a-AN-UP.dat" }; opch[0][3][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; { nrglog('f', "RECALC_F(fn=" << "p/p-2ch-b-AN-UP.dat" << ", ch=" << 1 << ", n=" << 3 << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip) && this->recalc_f_coupled(I1, Ip, this->Invar_f)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc_f<SC>> recalc_table = { #include "p/p-2ch-b-AN-UP.dat" }; opch[1][3][II] = this->recalc_f(diag, I1, Ip, recalc_table); } } }; } break; default: my_assert_not_reached(); }; } return opch; } template<typename SC> MatrixElements<SC> SymmetryP<SC>::recalc_doublet(const DiagInfo<SC> &diag, const MatrixElements<SC> &cold) const { MatrixElements<SC> cnew; for(const auto &[I1, eig]: diag) { int p1 = I1.get("P"); Invar Ip = Invar(-p1); // always the opposite fermion parity! switch (P.channels) { case 1: { { nrglog('f', "RECALC(fn=" << "p/p-1ch-doublet.dat" << ", Iop=" << Invar(-1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "p/p-1ch-doublet.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(-1)); } } } } break; case 2: { { nrglog('f', "RECALC(fn=" << "p/p-2ch-doublet.dat" << ", Iop=" << Invar(-1) << ")"); auto II = Twoinvar(I1, Ip); if (diag.count(I1) && diag.count(Ip)) { if (diag.at(I1).getnrstored() && diag.at(Ip).getnrstored()) { std::initializer_list<Recalc<SC>> recalc_table = { #include "p/p-2ch-doublet.dat" }; cnew[II] = this->recalc_general(diag, cold, I1, Ip, recalc_table, Invar(-1)); } } } } break; default: my_assert_not_reached(); }; } return cnew; } #undef SPINX #define SPINX(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef SPINZ #define SPINZ(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) // Isospin operator need an appropriate phase factor (bipartite sublattice index) #define USEISOFACTOR #if defined(USEISOFACTOR) #define ISOFACTOR psgn(step.getnn() + 1) #else #define ISOFACTOR 1 #endif #undef SPINY #define SPINY(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef ISOSPINY #define ISOSPINY(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value * std::complex<double>(ISOFACTOR)) #undef Complex #define Complex(x, y) cmpl(x, y) #undef CHARGE #define CHARGE(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef ISOSPINZ #define ISOSPINZ(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value) #undef ISOSPINX #define ISOSPINX(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value *ISOFACTOR) #undef ISOSPINP #define ISOSPINP(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value *ISOFACTOR) #undef ISOSPINM #define ISOSPINM(i1, ip, ch, value) this->recalc1_global(diag, I1, cn, i1, ip, value *ISOFACTOR) template<typename SC> void SymmetryP<SC>::recalc_global(const Step &step, const DiagInfo<SC> &diag, const std::string name, MatrixElements<SC> &cnew) const { if (name == "SZtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "p/p-1ch-spinz.dat" break; case 2: #include "p/p-2ch-spinz.dat" break; default: my_assert_not_reached(); } } return; } if constexpr (std::is_same_v<SC, std::complex<double>>) { if (name == "SYtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "p/p-1ch-spiny.dat" break; case 2: #include "p/p-2ch-spiny.dat" break; default: my_assert_not_reached(); } } return; } } if (name == "SXtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "p/p-1ch-spinx.dat" break; case 2: #include "p/p-2ch-spinx.dat" break; default: my_assert_not_reached(); } } return; } if (name == "Qtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "p/p-1ch-Qtot.dat" break; case 2: #include "p/p-2ch-Qtot.dat" break; default: my_assert_not_reached(); } } return; } if (name == "Iztot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "p/p-1ch-Iztot.dat" break; case 2: #include "p/p-2ch-Iztot.dat" break; default: my_assert_not_reached(); } } return; } if (name == "Ixtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "p/p-1ch-Ixtot.dat" break; case 2: #include "p/p-2ch-Ixtot.dat" break; default: my_assert_not_reached(); } } return; } if constexpr (std::is_same_v<SC, std::complex<double>>) { if (name == "Iytot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "p/p-1ch-Iytot.dat" break; case 2: #include "p/p-2ch-Iytot.dat" break; default: my_assert_not_reached(); } } return; } } if (name == "Iptot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "p/p-1ch-Iptot.dat" break; case 2: #include "p/p-2ch-Iptot.dat" break; default: my_assert_not_reached(); } } return; } if (name == "Imtot") { for(const auto &[I1, eig]: diag) { const Twoinvar II {I1, I1}; Matrix &cn = cnew[II]; switch (P.channels) { case 1: #include "p/p-1ch-Imtot.dat" break; case 2: #include "p/p-2ch-Imtot.dat" break; default: my_assert_not_reached(); } } return; } my_assert_not_reached(); } }
12,400
C++
.h
381
27.695538
135
0.566009
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,753
sym-QSZ.hpp
rokzitko_nrgljubljana/c++/symmetry/sym-QSZ.hpp
namespace NRG { template <typename S> std::unique_ptr<Symmetry<S>> mk_QSZ(const Params &P); }
96
C++
.h
4
22.5
53
0.744444
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,754
sym-ISOSZ.hpp
rokzitko_nrgljubljana/c++/symmetry/sym-ISOSZ.hpp
namespace NRG { template <typename S> std::unique_ptr<Symmetry<S>> mk_ISOSZ(const Params &P); }
98
C++
.h
4
23
55
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,755
main.cpp
wiiu-env_homebrew_on_menu_plugin/src/main.cpp
#include "main.h" #include "FileInfos.h" #include "SaveRedirection.h" #include "bootLogoTex_tga.h" #include "bootMovie_h264.h" #include "fs/CFile.hpp" #include "fs/FileReader.h" #include "fs/FileReaderWUHB.h" #include "globals.h" #include "iconTex_tga.h" #include "utils/StringTools.h" #include "utils/ini.h" #include <algorithm> #include <content_redirection/redirection.h> #include <coreinit/cache.h> #include <coreinit/debug.h> #include <coreinit/filesystem.h> #include <coreinit/mcp.h> #include <coreinit/memory.h> #include <coreinit/systeminfo.h> #include <coreinit/title.h> #include <cstring> #include <fnmatch.h> #include <forward_list> #include <fs/DirList.h> #include <malloc.h> #include <map> #include <nn/acp.h> #include <notifications/notifications.h> #include <optional> #include <rpxloader/rpxloader.h> #include <sdutils/sdutils.h> #include <sysapp/launch.h> #include <sysapp/title.h> #include <utils/logger.h> #include <wuhb_utils/utils.h> #include <wups.h> #include <wups/config/WUPSConfigItemBoolean.h> #include <wups/storage.h> typedef struct ACPMetaData { char bootmovie[80696]; char bootlogo[28604]; } ACPMetaData; WUPS_PLUGIN_NAME("Homebrew on Wii U menu"); WUPS_PLUGIN_DESCRIPTION("Allows the user to load homebrew from the Wii U menu"); WUPS_PLUGIN_VERSION(VERSION_FULL); WUPS_PLUGIN_AUTHOR("Maschell"); WUPS_PLUGIN_LICENSE("GPL"); #define UPPER_TITLE_ID_HOMEBREW 0x0005000F #define TITLE_ID_HOMEBREW_MASK (((uint64_t) UPPER_TITLE_ID_HOMEBREW) << 32) ACPMetaXml gLaunchXML = {}; MCPTitleListType current_launched_title_info = {}; BOOL gHomebrewLaunched = {}; std::mutex fileInfosMutex; std::forward_list<std::shared_ptr<FileInfos>> fileInfos; std::mutex fileReaderListMutex; std::forward_list<std::unique_ptr<FileReader>> openFileReaders; void readCustomTitlesFromSD(); WUPS_USE_WUT_DEVOPTAB(); WUPS_USE_STORAGE("homebrew_on_menu"); // Use the storage API #define HIDE_HOMEBREW_STRING "hideHomebrew" #define PREFER_WUHB_OVER_RPX_STRING "hideRPXIfWUHBExists" #define HIDE_ALL_RPX_STRING "hideAllRPX" #define HOMEBREW_APPS_DIRECTORY "fs:/vol/external01/wiiu/apps" #define IGNORE_FILE_PATH HOMEBREW_APPS_DIRECTORY "/.ignore" #define HOMEBREW_LAUNCHER_FILENAME "homebrew_launcher.wuhb" #define HOMEBREW_LAUNCHER_OPTIONAL_DIRECTORY "homebrew_launcher" #define HOMEBREW_LAUNCHER_PATH HOMEBREW_APPS_DIRECTORY "/" HOMEBREW_LAUNCHER_FILENAME #define HOMEBREW_LAUNCHER_PATH2 HOMEBREW_APPS_DIRECTORY "/" HOMEBREW_LAUNCHER_OPTIONAL_DIRECTORY "/" HOMEBREW_LAUNCHER_FILENAME #define DEFAULT_HIDE_HOMEBREW_VALUE false #define DEFAULT_PREFER_WUHB_OVER_RPX_VALUE true #define DEFAULT_HIDE_ALL_RPX_VALUE false bool gHideHomebrew = DEFAULT_HIDE_HOMEBREW_VALUE; bool gPreferWUHBOverRPX = DEFAULT_PREFER_WUHB_OVER_RPX_VALUE; bool gHideAllRPX = DEFAULT_HIDE_ALL_RPX_VALUE; bool prevHideValue = false; bool prevPreferWUHBOverRPXValue = false; bool prevHideAllRPX = false; bool gHomebrewLauncherExists = false; std::vector<std::string> gIgnorePatterns; WUPSConfigAPICallbackStatus ConfigMenuOpenedCallback(WUPSConfigCategoryHandle rootHandle); void ConfigMenuClosedCallback(); INITIALIZE_PLUGIN() { memset((void *) &current_launched_title_info, 0, sizeof(current_launched_title_info)); memset((void *) &gLaunchXML, 0, sizeof(gLaunchXML)); gHomebrewLaunched = FALSE; gSerialId = {}; if (!Utils::GetSerialId(gSerialId) || gSerialId.empty()) { DEBUG_FUNCTION_LINE_ERR("Homebrew on Menu Plugin: Failed to get the serial id"); OSFatal("Homebrew on menu plugin: Failed to get the serial id"); } // Use libwuhbutils. WUHBUtilsStatus error; if ((error = WUHBUtils_InitLibrary()) != WUHB_UTILS_RESULT_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Homebrew on menu plugin: Failed to init WUHBUtils. Error %s [%d]", WUHBUtils_GetStatusStr(error), error); OSFatal("Homebrew on menu plugin: Failed to init WUHBUtils."); } // Use libcontentredirection. ContentRedirectionStatus error2; if ((error2 = ContentRedirection_InitLibrary()) != CONTENT_REDIRECTION_RESULT_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Homebrew on menu plugin: Failed to init ContentRedirection. Error %s [%d]", ContentRedirection_GetStatusStr(error2), error2); OSFatal("Homebrew on menu plugin: Failed to init ContentRedirection."); } // Use librpxloader. RPXLoaderStatus error3; if ((error3 = RPXLoader_InitLibrary()) != RPX_LOADER_RESULT_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Homebrew on menu plugin: Failed to init RPXLoader. Error %s [%d]", RPXLoader_GetStatusStr(error3), error3); OSFatal("Homebrew on menu plugin: Failed to init RPXLoader."); } // Use libnotifications. NotificationModuleStatus error4; if ((error4 = NotificationModule_InitLibrary()) != NOTIFICATION_MODULE_RESULT_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Homebrew on menu plugin: Failed to init NotificationModule. Error %s [%d]", NotificationModule_GetStatusStr(error4), error4); OSFatal("Homebrew on menu plugin: Failed to init NotificationModule."); } WUPSConfigAPIOptionsV1 configOptions = {.name = "Homebrew On Wii U Menu Plugin"}; if (WUPSConfigAPI_Init(configOptions, ConfigMenuOpenedCallback, ConfigMenuClosedCallback) != WUPSCONFIG_API_RESULT_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Failed to init config api"); } WUPSStorageError storageError; storageError = WUPSStorageAPI::GetOrStoreDefault(HIDE_HOMEBREW_STRING, gHideHomebrew, DEFAULT_HIDE_HOMEBREW_VALUE); if (storageError != WUPS_STORAGE_ERROR_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Failed to get or set default bool: %s", WUPSStorageAPI::GetStatusStr(storageError).data()); } storageError = WUPSStorageAPI::GetOrStoreDefault(PREFER_WUHB_OVER_RPX_STRING, gPreferWUHBOverRPX, DEFAULT_PREFER_WUHB_OVER_RPX_VALUE); if (storageError != WUPS_STORAGE_ERROR_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Failed to get or set default bool: %s", WUPSStorageAPI::GetStatusStr(storageError).data()); } storageError = WUPSStorageAPI::GetOrStoreDefault(HIDE_ALL_RPX_STRING, gHideAllRPX, DEFAULT_HIDE_ALL_RPX_VALUE); if (storageError != WUPS_STORAGE_ERROR_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Failed to get or set default bool: %s", WUPSStorageAPI::GetStatusStr(storageError).data()); } // save storage storageError = WUPSStorageAPI::SaveStorage(); if (storageError != WUPS_STORAGE_ERROR_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Failed to save storage: %s", WUPSStorageAPI::GetStatusStr(storageError).data()); } prevHideValue = gHideHomebrew; prevPreferWUHBOverRPXValue = gPreferWUHBOverRPX; prevHideAllRPX = gHideAllRPX; } void hideHomebrewChanged(ConfigItemBoolean *item, bool newValue) { DEBUG_FUNCTION_LINE_VERBOSE("New value in gHideHomebrew: %d", newValue); gHideHomebrew = newValue; // If the value has changed, we store it in the storage. WUPSStorageError storageRes = WUPSStorageAPI::Store(HIDE_HOMEBREW_STRING, gHideHomebrew); if (storageRes != WUPS_STORAGE_ERROR_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Failed to store bool: %s", WUPSStorageAPI::GetStatusStr(storageRes).data()); } } void preferWUHBOverRPXChanged(ConfigItemBoolean *item, bool newValue) { DEBUG_FUNCTION_LINE_VERBOSE("New value in gPreferWUHBOverRPX: %d", newValue); gPreferWUHBOverRPX = newValue; // If the value has changed, we store it in the storage. WUPSStorageError storageRes = WUPSStorageAPI::Store(PREFER_WUHB_OVER_RPX_STRING, gPreferWUHBOverRPX); if (storageRes != WUPS_STORAGE_ERROR_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Failed to store bool: %s", WUPSStorageAPI::GetStatusStr(storageRes).data()); } } void hideAllRPXChanged(ConfigItemBoolean *item, bool newValue) { DEBUG_FUNCTION_LINE_VERBOSE("New value in gHideAllRPX: %d", newValue); gHideAllRPX = newValue; // If the value has changed, we store it in the storage. WUPSStorageError storageRes = WUPSStorageAPI::Store(HIDE_ALL_RPX_STRING, gHideAllRPX); if (storageRes != WUPS_STORAGE_ERROR_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Failed to store bool: %s", WUPSStorageAPI::GetStatusStr(storageRes).data()); } } WUPSConfigAPICallbackStatus ConfigMenuOpenedCallback(WUPSConfigCategoryHandle rootHandle) { try { WUPSConfigCategory root = WUPSConfigCategory(rootHandle); root.add(WUPSConfigItemBoolean::Create(HIDE_HOMEBREW_STRING, gHomebrewLauncherExists ? "Hide all homebrew except Homebrew Launcher" : "Hide all homebrew", DEFAULT_HIDE_HOMEBREW_VALUE, gHideHomebrew, &hideHomebrewChanged)); root.add(WUPSConfigItemBoolean::Create(PREFER_WUHB_OVER_RPX_STRING, "Prefer .wuhb over .rpx", DEFAULT_PREFER_WUHB_OVER_RPX_VALUE, gPreferWUHBOverRPX, &preferWUHBOverRPXChanged)); root.add(WUPSConfigItemBoolean::Create(HIDE_ALL_RPX_STRING, "Hide all .rpx", DEFAULT_HIDE_ALL_RPX_VALUE, gHideAllRPX, &hideAllRPXChanged)); } catch (std::exception &e) { OSReport("Exception: %s\n", e.what()); return WUPSCONFIG_API_CALLBACK_RESULT_ERROR; } return WUPSCONFIG_API_CALLBACK_RESULT_SUCCESS; } bool sSDUtilsInitDone = false; bool sSDIsMounted = false; bool sTitleRebooting = false; void ConfigMenuClosedCallback() { // Save all changes auto saveErr = WUPSStorageAPI::SaveStorage(); if (saveErr != WUPS_STORAGE_ERROR_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Failed to save storage: %s", WUPSStorageAPI::GetStatusStr(saveErr).data()); } if (prevHideValue != gHideHomebrew || prevPreferWUHBOverRPXValue != gPreferWUHBOverRPX || prevHideAllRPX != gHideAllRPX) { if (!sTitleRebooting) { _SYSLaunchTitleWithStdArgsInNoSplash(OSGetTitleID(), nullptr); sTitleRebooting = true; } } prevHideValue = gHideHomebrew; prevPreferWUHBOverRPXValue = gPreferWUHBOverRPX; prevHideAllRPX = gHideAllRPX; } void Cleanup() { { const std::lock_guard<std::mutex> lock1(fileReaderListMutex); openFileReaders.clear(); } { const std::lock_guard<std::mutex> lock(fileInfosMutex); fileInfos.clear(); } } void SDCleanUpHandlesHandler() { Cleanup(); } void SDAttachedHandler([[maybe_unused]] SDUtilsAttachStatus status) { if (OSGetForegroundBucket(nullptr, nullptr) && !sTitleRebooting) { _SYSLaunchTitleWithStdArgsInNoSplash(OSGetTitleID(), nullptr); sTitleRebooting = true; } } ON_APPLICATION_START() { Cleanup(); initLogging(); sSDIsMounted = false; if (OSGetTitleID() == 0x0005001010040000L || // Wii U Menu JPN OSGetTitleID() == 0x0005001010040100L || // Wii U Menu USA OSGetTitleID() == 0x0005001010040200L) { // Wii U Menu EUR CFile file(IGNORE_FILE_PATH, CFile::ReadOnly); if (file.isOpen()) { std::string strBuffer; strBuffer.resize(file.size()); file.read((uint8_t *) &strBuffer[0], strBuffer.size()); file.close(); //! remove all windows crap signs size_t position; while (true) { position = strBuffer.find('\r'); if (position == std::string::npos) { break; } strBuffer.erase(position, 1); } gIgnorePatterns = StringTools::StringSplit(strBuffer, "\n"); // Ignore all lines that start with '#' gIgnorePatterns.erase(std::remove_if(gIgnorePatterns.begin(), gIgnorePatterns.end(), [](auto &line) { return line.starts_with('#'); }), gIgnorePatterns.end()); } else { DEBUG_FUNCTION_LINE_INFO("No ignore found"); } gInWiiUMenu = true; struct stat st {}; if (stat(HOMEBREW_LAUNCHER_PATH, &st) >= 0 || stat(HOMEBREW_LAUNCHER_PATH2, &st) >= 0) { gHomebrewLauncherExists = true; } else { gHomebrewLauncherExists = false; } if (SDUtils_InitLibrary() == SDUTILS_RESULT_SUCCESS) { sSDUtilsInitDone = true; sTitleRebooting = false; if (SDUtils_AddAttachHandler(SDAttachedHandler) != SDUTILS_RESULT_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Failed to add AttachedHandler"); } if (SDUtils_AddCleanUpHandlesHandler(SDCleanUpHandlesHandler) != SDUTILS_RESULT_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Failed to add CleanUpHandlesHandler"); } if (SDUtils_IsSdCardMounted(&sSDIsMounted) != SDUTILS_RESULT_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("IsSdCardMounted failed"); } } else { DEBUG_FUNCTION_LINE_WARN("Failed to init SDUtils. Make sure to have the SDHotSwapModule loaded!"); } } else { gInWiiUMenu = false; } if (_SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY) != OSGetTitleID()) { gHomebrewLaunched = FALSE; } } ON_APPLICATION_ENDS() { Cleanup(); SaveRedirectionCleanUp(); deinitLogging(); gInWiiUMenu = false; if (sSDUtilsInitDone) { SDUtils_RemoveAttachHandler(SDAttachedHandler); SDUtils_RemoveCleanUpHandlesHandler(SDCleanUpHandlesHandler); SDUtils_DeInitLibrary(); sSDUtilsInitDone = false; } sSDIsMounted = false; } std::optional<std::shared_ptr<FileInfos>> getIDByLowerTitleID(uint32_t titleid_lower) { std::lock_guard<std::mutex> lock(fileInfosMutex); for (auto &cur : fileInfos) { if (cur->lowerTitleID == titleid_lower) { return cur; } } return {}; } void fillXmlForTitleID(uint32_t titleid_upper, uint32_t titleid_lower, ACPMetaXml *out_buf) { auto titleIdInfoOpt = getIDByLowerTitleID(titleid_lower); if (!titleIdInfoOpt.has_value()) { DEBUG_FUNCTION_LINE_ERR("Failed to get info by titleid"); return; } auto &titleInfo = titleIdInfoOpt.value(); out_buf->title_id = (((uint64_t) titleid_upper) << 32) + titleid_lower; strncpy(out_buf->longname_en, titleInfo->longname.c_str(), sizeof(out_buf->longname_en) - 1); strncpy(out_buf->shortname_en, titleInfo->shortname.c_str(), sizeof(out_buf->shortname_en) - 1); strncpy(out_buf->publisher_en, titleInfo->author.c_str(), sizeof(out_buf->publisher_en) - 1); out_buf->e_manual = 1; out_buf->e_manual_version = 0; out_buf->title_version = 1; out_buf->network_use = 1; out_buf->launching_flag = 4; out_buf->online_account_use = 1; out_buf->os_version = 0x000500101000400A; out_buf->region = 0xFFFFFFFF; out_buf->common_save_size = 0x0000000001790000; out_buf->group_id = 0x400; out_buf->drc_use = 1; out_buf->version = 1; out_buf->reserved_flag0 = 0x00010001; out_buf->reserved_flag6 = 0x00000003; out_buf->pc_usk = 128; strncpy(out_buf->product_code, "WUP-P-HBLD", sizeof(out_buf->product_code) - 1); strncpy(out_buf->content_platform, "WUP", sizeof(out_buf->content_platform) - 1); strncpy(out_buf->company_code, "0001", sizeof(out_buf->company_code) - 1); } static int handler(void *user, const char *section, const char *name, const char *value) { auto *fInfo = (std::shared_ptr<FileInfos> *) user; #define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0 if (MATCH("menu", "longname")) { fInfo->operator->()->longname = value; } else if (MATCH("menu", "shortname")) { fInfo->operator->()->shortname = value; } else if (MATCH("menu", "author")) { fInfo->operator->()->author = value; } else { return 0; /* unknown section/name, error */ } return 1; } bool CheckFileExistsHelper(const char *path); void readCustomTitlesFromSD() { std::lock_guard<std::mutex> lock(fileInfosMutex); if (!fileInfos.empty()) { DEBUG_FUNCTION_LINE_VERBOSE("Using cached value"); return; } std::vector<std::string> listOfExecutables; if (gHideHomebrew) { struct stat st {}; if (stat(HOMEBREW_LAUNCHER_PATH, &st) >= 0) { listOfExecutables.emplace_back(HOMEBREW_LAUNCHER_PATH); } else if (stat(HOMEBREW_LAUNCHER_PATH2, &st) >= 0) { listOfExecutables.emplace_back(HOMEBREW_LAUNCHER_PATH2); } } else { // Reset current infos DirList dirList(HOMEBREW_APPS_DIRECTORY, ".rpx,.wuhb", DirList::Files | DirList::CheckSubfolders, 1); dirList.SortList(); if (gHideAllRPX) { for (int i = 0; i < dirList.GetFilecount(); i++) { if (dirList.GetFilepath(i) != nullptr && !std::string_view(dirList.GetFilepath(i)).ends_with(".rpx")) { listOfExecutables.emplace_back(dirList.GetFilepath(i)); } } } else if (gPreferWUHBOverRPX) { // map<[path without extension], vector<[extension]>> std::map<std::string, std::vector<std::string>> pathWithoutExtensionMap; for (int i = 0; i < dirList.GetFilecount(); i++) { std::string pathNoExtension = StringTools::remove_extension(dirList.GetFilepath(i)); if (pathWithoutExtensionMap.count(pathNoExtension) == 0) { pathWithoutExtensionMap[pathNoExtension] = std::vector<std::string>(); } pathWithoutExtensionMap[pathNoExtension].push_back(StringTools::get_extension(dirList.GetFilename(i))); } for (auto &l : pathWithoutExtensionMap) { if (l.second.size() == 1 && l.second.at(0) == ".rpx") { listOfExecutables.push_back(l.first + ".rpx"); } else { listOfExecutables.push_back(l.first + ".wuhb"); } } } else { for (int i = 0; i < dirList.GetFilecount(); i++) { listOfExecutables.emplace_back(dirList.GetFilepath(i)); } } // Remove any executable that matches the ignore pattern. listOfExecutables.erase(std::remove_if(listOfExecutables.begin(), listOfExecutables.end(), [&](const auto &item) { auto path = item.substr(strlen(HOMEBREW_APPS_DIRECTORY) + 1); return std::ranges::any_of(gIgnorePatterns.begin(), gIgnorePatterns.end(), [&](const auto &pattern) { if (fnmatch(pattern.c_str(), path.c_str(), FNM_CASEFOLD) == 0) { DEBUG_FUNCTION_LINE_INFO("Ignore \"%s\" because it matched pattern \"%s\"", path.c_str(), pattern.c_str()); return true; } return false; }); }), listOfExecutables.end()); } for (auto &filePath : listOfExecutables) { auto filename = StringTools::FullpathToFilename(filePath.c_str()); //! skip wiiload temp files if (strcasecmp(filename, "temp.rpx") == 0) { continue; } //! skip wiiload temp files if (strcasecmp(filename, "temp.wuhb") == 0) { continue; } //! skip wiiload temp files if (strcasecmp(filename, "temp2.wuhb") == 0) { continue; } //! skip hidden linux and mac files if (filename[0] == '.' || filename[0] == '_') { continue; } auto repl = "fs:/vol/external01/"; auto input = filePath.c_str(); const char *relativeFilepath; if (filePath.starts_with(repl)) { relativeFilepath = &input[strlen(repl)]; } else { DEBUG_FUNCTION_LINE_ERR("Skip %s, Path doesn't start with %s (This should never happen", input, repl); continue; } auto fileInfo = make_shared_nothrow<FileInfos>(relativeFilepath); if (!fileInfo) { DEBUG_FUNCTION_LINE_ERR("No more memory"); break; } std::lock_guard<std::mutex> infoLock(fileInfo->accessLock); auto *cur_title_info = &(fileInfo->titleInfo); snprintf(cur_title_info->path, sizeof(cur_title_info->path), "/custom/%08X%08X", UPPER_TITLE_ID_HOMEBREW, fileInfo->lowerTitleID); const char *indexedDevice = "mlc"; strncpy(cur_title_info->indexedDevice, indexedDevice, sizeof(cur_title_info->indexedDevice) - 1); fileInfo->filename = filename; fileInfo->longname = filename; fileInfo->shortname = filename; fileInfo->author = filename; // System apps don't have a splash screen. cur_title_info->appType = MCP_APP_TYPE_SYSTEM_APPS; DEBUG_FUNCTION_LINE_VERBOSE("Check %s", fileInfo->filename.c_str()); // Check if the bootTvTex and bootDrcTex exists if (std::string_view(fileInfo->filename).ends_with(".wuhb")) { int result = 0; #define TMP_BUNDLE_NAME "romfscheck" if (WUHBUtils_MountBundle(TMP_BUNDLE_NAME, filePath.c_str(), BundleSource_FileDescriptor, &result) == WUHB_UTILS_RESULT_SUCCESS && result >= 0) { fileInfo->isBundle = true; uint8_t *buffer; uint32_t bufferSize; auto readRes = WUHBUtils_ReadWholeFile(TMP_BUNDLE_NAME ":/meta/meta.ini", &buffer, &bufferSize); if (readRes == WUHB_UTILS_RESULT_SUCCESS) { buffer[bufferSize - 1] = '\0'; if (ini_parse_string((const char *) buffer, handler, &fileInfo) < 0) { DEBUG_FUNCTION_LINE_ERR("Failed to parse meta.ini"); } free(buffer); buffer = nullptr; } else { DEBUG_FUNCTION_LINE_ERR("Failed to open or read meta.ini: %d", readRes); } auto bootTvTexPath = TMP_BUNDLE_NAME ":/meta/bootTvTex.tga"; auto bootDrcTexPath = TMP_BUNDLE_NAME ":/meta/bootDrcTex.tga"; if (CheckFileExistsHelper(bootTvTexPath) && CheckFileExistsHelper(bootDrcTexPath)) { // Show splash screens cur_title_info->appType = MCP_APP_TYPE_GAME; DEBUG_FUNCTION_LINE_VERBOSE("Title has splashscreen"); } int32_t unmountRes; if (WUHBUtils_UnmountBundle(TMP_BUNDLE_NAME, &unmountRes) == WUHB_UTILS_RESULT_SUCCESS) { if (unmountRes != 0) { DEBUG_FUNCTION_LINE_ERR("Unmount result was \"%s\"", TMP_BUNDLE_NAME); } } else { DEBUG_FUNCTION_LINE_ERR("Failed to unmount \"%s\"", TMP_BUNDLE_NAME); } } else { DEBUG_FUNCTION_LINE_ERR("%s is not a valid .wuhb file: %d", filePath.c_str(), result); continue; } } cur_title_info->titleId = TITLE_ID_HOMEBREW_MASK | fileInfo->lowerTitleID; cur_title_info->titleVersion = 1; cur_title_info->groupId = 0x400; cur_title_info->osVersion = OSGetOSID(); cur_title_info->sdkVersion = __OSGetProcessSDKVersion(); cur_title_info->unk0x60 = 0; fileInfos.push_front(fileInfo); } OSMemoryBarrier(); } bool CheckFileExistsHelper(const char *path) { int32_t exists; int32_t res; if ((res = WUHBUtils_FileExists(path, &exists)) == WUHB_UTILS_RESULT_SUCCESS) { if (!exists) { DEBUG_FUNCTION_LINE_VERBOSE("## WARN ##: Missing %s", path); return false; } return true; } DEBUG_FUNCTION_LINE_ERR("Failed to check if %s exists: %d", path, res); return false; } DECL_FUNCTION(int32_t, MCP_TitleList, uint32_t handle, uint32_t *outTitleCount, MCPTitleListType *titleList, uint32_t size) { int32_t result = real_MCP_TitleList(handle, outTitleCount, titleList, size); if (!gInWiiUMenu) { DEBUG_FUNCTION_LINE_VERBOSE("Not in Wii U Menu"); return result; } uint32_t titleCount = *outTitleCount; { std::lock_guard<std::mutex> lock(fileInfosMutex); readCustomTitlesFromSD(); for (auto &gFileInfo : fileInfos) { memcpy(&(titleList[titleCount]), &(gFileInfo->titleInfo), sizeof(MCPTitleListType)); titleCount++; } } *outTitleCount = titleCount; return result; } DECL_FUNCTION(int32_t, ACPCheckTitleLaunchByTitleListTypeEx, MCPTitleListType *title, uint32_t u2) { if ((title->titleId & TITLE_ID_HOMEBREW_MASK) == TITLE_ID_HOMEBREW_MASK) { std::lock_guard<std::mutex> lock(fileInfosMutex); auto fileInfo = getIDByLowerTitleID(title->titleId & 0xFFFFFFFF); if (fileInfo.has_value()) { DEBUG_FUNCTION_LINE("Starting a homebrew title"); fillXmlForTitleID((title->titleId & 0xFFFFFFFF00000000) >> 32, (title->titleId & 0xFFFFFFFF), &gLaunchXML); gHomebrewLaunched = TRUE; if (RPXLoader_PrepareLaunchFromSD(fileInfo.value()->relativeFilepath.c_str()) == RPX_LOADER_RESULT_SUCCESS) { return 0; } DEBUG_FUNCTION_LINE_ERR("Failed to prepare launch for %s", fileInfo.value()->relativeFilepath.c_str()); } else { DEBUG_FUNCTION_LINE_ERR("Failed to get info for titleID %016llX", title->titleId); } } return real_ACPCheckTitleLaunchByTitleListTypeEx(title, u2); } DECL_FUNCTION(int, FSOpenFile, FSClient *client, FSCmdBlock *block, char *path, const char *mode, uint32_t *handle, int error) { const char *start = "/vol/storage_mlc01/sys/title/0005000F"; const char *tga = ".tga"; const char *iconTex = "iconTex.tga"; const char *sound = ".btsnd"; std::string_view pathStr = path; if (pathStr.starts_with(start)) { std::unique_ptr<FileReader> reader; if (pathStr.ends_with(tga) || pathStr.ends_with(sound)) { char *id = path + 1 + strlen(start); id[8] = 0; char *relativePath = id + 9; auto lowerTitleID = strtoul(id, 0, 16); auto fileInfo = getIDByLowerTitleID(lowerTitleID); if (fileInfo.has_value()) { reader = make_unique_nothrow<FileReaderWUHB>(fileInfo.value(), relativePath, !gHomebrewLaunched); if (reader && !reader->isReady()) { reader.reset(); } } } // If the icon is requested and loading it from a bundle failed, we fall back to a default one. if (reader == nullptr && pathStr.ends_with(iconTex)) { reader = make_unique_nothrow<FileReader>((uint8_t *) iconTex_tga, iconTex_tga_size); if (reader && !reader->isReady()) { reader.reset(); } } if (reader) { std::lock_guard<std::mutex> lock(fileReaderListMutex); *handle = reader->getHandle(); openFileReaders.push_front(std::move(reader)); return FS_STATUS_OK; } } int result = real_FSOpenFile(client, block, path, mode, handle, error); return result; } DECL_FUNCTION(FSStatus, FSCloseFile, FSClient *client, FSCmdBlock *block, FSFileHandle handle, uint32_t flags) { if (remove_locked_first_if(fileReaderListMutex, openFileReaders, [handle](auto &cur) { return cur->getHandle() == handle; })) { return FS_STATUS_OK; } return real_FSCloseFile(client, block, handle, flags); } DECL_FUNCTION(FSStatus, FSReadFile, FSClient *client, FSCmdBlock *block, uint8_t *buffer, uint32_t size, uint32_t count, FSFileHandle handle, uint32_t unk1, uint32_t flags) { { const std::lock_guard<std::mutex> lock(fileReaderListMutex); for (auto &reader : openFileReaders) { if ((uint32_t) reader.get() == (uint32_t) handle) { return (FSStatus) (reader->read(buffer, size * count) / size); } } } FSStatus result = real_FSReadFile(client, block, buffer, size, count, handle, unk1, flags); return result; } DECL_FUNCTION(int32_t, ACPGetTitleMetaXmlByDevice, uint32_t titleid_upper, uint32_t titleid_lower, ACPMetaXml *out_buf, uint32_t device, uint32_t u1) { int result = real_ACPGetTitleMetaXmlByDevice(titleid_upper, titleid_lower, out_buf, device, u1); if (titleid_upper == UPPER_TITLE_ID_HOMEBREW) { fillXmlForTitleID(titleid_upper, titleid_lower, out_buf); result = 0; } return result; } DECL_FUNCTION(int32_t, ACPGetTitleMetaDirByDevice, uint32_t titleid_upper, uint32_t titleid_lower, char *out_buf, uint32_t size, int device) { if (titleid_upper == UPPER_TITLE_ID_HOMEBREW) { snprintf(out_buf, 53, "/vol/storage_mlc01/sys/title/%08X/%08X/meta", titleid_upper, titleid_lower); return 0; } int result = real_ACPGetTitleMetaDirByDevice(titleid_upper, titleid_lower, out_buf, size, device); return result; } /* * Load the H&S app instead */ DECL_FUNCTION(int32_t, _SYSLaunchTitleByPathFromLauncher, char *pathToLoad, uint32_t u2) { const char *start = "/custom/"; if (strncmp(pathToLoad, start, strlen(start)) == 0) { strcpy(current_launched_title_info.path, pathToLoad); uint64_t titleID = _SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY); snprintf(pathToLoad, 47, "/vol/storage_mlc01/sys/title/%08x/%08x", (uint32_t) (titleID >> 32), (uint32_t) (0x00000000FFFFFFFF & titleID)); } int32_t result = real__SYSLaunchTitleByPathFromLauncher(pathToLoad, strlen(pathToLoad)); return result; } DECL_FUNCTION(int32_t, ACPGetLaunchMetaXml, ACPMetaXml *metaxml) { int result = real_ACPGetLaunchMetaXml(metaxml); if (gHomebrewLaunched) { memcpy(metaxml, &gLaunchXML, sizeof(gLaunchXML)); } return result; } DECL_FUNCTION(uint32_t, ACPGetApplicationBox, uint32_t *u1, uint32_t *u2, uint32_t u3, uint32_t u4) { if (u3 == UPPER_TITLE_ID_HOMEBREW) { uint64_t titleID = _SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY); u3 = (uint32_t) (titleID >> 32); u4 = (uint32_t) (0x00000000FFFFFFFF & titleID); } uint32_t result = real_ACPGetApplicationBox(u1, u2, u3, u4); return result; } /* * Redirect the launchable check to H&S */ DECL_FUNCTION(uint32_t, PatchChkStart__3RplFRCQ3_2nn6drmapp8StartArg, uint32_t *param) { if (param[2] == UPPER_TITLE_ID_HOMEBREW) { uint64_t titleID = _SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY); param[2] = (uint32_t) (titleID >> 32); param[3] = (uint32_t) (0x00000000FFFFFFFF & titleID); } uint32_t result = real_PatchChkStart__3RplFRCQ3_2nn6drmapp8StartArg(param); return result; } /* * Redirect the launchable check to H&S */ DECL_FUNCTION(uint32_t, MCP_RightCheckLaunchable, uint32_t *u1, uint32_t *u2, uint32_t u3, uint32_t u4, uint32_t u5) { if (u3 == UPPER_TITLE_ID_HOMEBREW) { uint64_t titleID = _SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY); u3 = (uint32_t) (titleID >> 32); u4 = (uint32_t) (0x00000000FFFFFFFF & titleID); } uint32_t result = real_MCP_RightCheckLaunchable(u1, u2, u3, u4, u5); return result; } /* * Patch the boot movie and and boot logo */ DECL_FUNCTION(uint32_t, ACPGetLaunchMetaData, struct ACPMetaData *metadata) { uint32_t result = real_ACPGetLaunchMetaData(metadata); if (gHomebrewLaunched) { memcpy(metadata->bootmovie, bootMovie_h264, bootMovie_h264_size); memcpy(metadata->bootlogo, bootLogoTex_tga, bootLogoTex_tga_size); DCFlushRange(metadata->bootmovie, bootMovie_h264_size); DCFlushRange(metadata->bootlogo, bootMovie_h264_size); } return result; } typedef struct TitleVersionInfo TitleVersionInfo; struct WUT_PACKED TitleVersionInfo { uint16_t currentVersion; uint16_t neededVersion; uint8_t needsUpdate; }; WUT_CHECK_OFFSET(TitleVersionInfo, 0x00, currentVersion); WUT_CHECK_OFFSET(TitleVersionInfo, 0x02, neededVersion); WUT_CHECK_OFFSET(TitleVersionInfo, 0x04, needsUpdate); WUT_CHECK_SIZE(TitleVersionInfo, 0x05); DECL_FUNCTION(uint32_t, GetTitleVersionInfo__Q2_2nn4vctlFPQ3_2nn4vctl16TitleVersionInfoULQ3_2nn4Cafe9MediaType, TitleVersionInfo *titleVersionInfo, uint32_t u2, uint32_t u3, uint32_t u4, uint32_t u5) { int32_t result = real_GetTitleVersionInfo__Q2_2nn4vctlFPQ3_2nn4vctl16TitleVersionInfoULQ3_2nn4Cafe9MediaType(titleVersionInfo, u2, u3, u4, u5); if (result < 0) { // Fake result if it's H&S uint64_t titleID = _SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY); auto expected_u3 = (uint32_t) (titleID >> 32); auto expected_u4 = (uint32_t) (0x00000000FFFFFFFF & titleID); if (expected_u3 == u3 && expected_u4 == u4) { if (titleVersionInfo != nullptr) { titleVersionInfo->currentVersion = 129; titleVersionInfo->neededVersion = 129; titleVersionInfo->needsUpdate = 0; } return 0; } } return result; } DECL_FUNCTION(uint32_t, GetUpdateInfo__Q2_2nn4vctlFPQ3_2nn4vctl10UpdateInfoULQ3_2nn4Cafe9MediaType, uint32_t u1, uint32_t u2, uint32_t u3, uint32_t u4, uint32_t u5, uint32_t u6) { uint32_t result = real_GetUpdateInfo__Q2_2nn4vctlFPQ3_2nn4vctl10UpdateInfoULQ3_2nn4Cafe9MediaType(u1, u2, u3, u4, u5, u6); uint64_t titleID = _SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_HEALTH_AND_SAFETY); auto expected_u3 = (uint32_t) (titleID >> 32); auto expected_u4 = (uint32_t) (0x00000000FFFFFFFF & titleID); if (expected_u3 == u3 && expected_u4 == u4) { return 0xa121f480; } return result; } DECL_FUNCTION(uint32_t, MCPGetTitleInternal, uint32_t mcp_handle, void *input, uint32_t type, MCPTitleListType *titles, uint32_t out_cnt) { if (input != nullptr) { auto *inputPtrAsU32 = (uint32_t *) input; if (inputPtrAsU32[0] == UPPER_TITLE_ID_HOMEBREW && out_cnt >= 1) { for (auto &gFileInfo : fileInfos) { if (gFileInfo->lowerTitleID == inputPtrAsU32[1]) { memcpy(&titles[0], &(gFileInfo->titleInfo), sizeof(MCPTitleListType)); return 1; } } DEBUG_FUNCTION_LINE_ERR("Failed to find lower TID %08X", inputPtrAsU32[1]); } } uint32_t result = real_MCPGetTitleInternal(mcp_handle, input, type, titles, out_cnt); return result; } WUPS_MUST_REPLACE_FOR_PROCESS(GetTitleVersionInfo__Q2_2nn4vctlFPQ3_2nn4vctl16TitleVersionInfoULQ3_2nn4Cafe9MediaType, WUPS_LOADER_LIBRARY_NN_VCTL, GetTitleVersionInfo__Q2_2nn4vctlFPQ3_2nn4vctl16TitleVersionInfoULQ3_2nn4Cafe9MediaType, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(GetUpdateInfo__Q2_2nn4vctlFPQ3_2nn4vctl10UpdateInfoULQ3_2nn4Cafe9MediaType, WUPS_LOADER_LIBRARY_NN_VCTL, GetUpdateInfo__Q2_2nn4vctlFPQ3_2nn4vctl10UpdateInfoULQ3_2nn4Cafe9MediaType, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(ACPGetApplicationBox, WUPS_LOADER_LIBRARY_NN_ACP, ACPGetApplicationBox, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(PatchChkStart__3RplFRCQ3_2nn6drmapp8StartArg, WUPS_LOADER_LIBRARY_DRMAPP, PatchChkStart__3RplFRCQ3_2nn6drmapp8StartArg, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(MCP_RightCheckLaunchable, WUPS_LOADER_LIBRARY_COREINIT, MCP_RightCheckLaunchable, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(MCP_TitleList, WUPS_LOADER_LIBRARY_COREINIT, MCP_TitleList, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(ACPCheckTitleLaunchByTitleListTypeEx, WUPS_LOADER_LIBRARY_NN_ACP, ACPCheckTitleLaunchByTitleListTypeEx, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(ACPGetTitleMetaXmlByDevice, WUPS_LOADER_LIBRARY_NN_ACP, ACPGetTitleMetaXmlByDevice, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(ACPGetLaunchMetaXml, WUPS_LOADER_LIBRARY_NN_ACP, ACPGetLaunchMetaXml, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(ACPGetTitleMetaDirByDevice, WUPS_LOADER_LIBRARY_NN_ACP, ACPGetTitleMetaDirByDevice, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(_SYSLaunchTitleByPathFromLauncher, WUPS_LOADER_LIBRARY_SYSAPP, _SYSLaunchTitleByPathFromLauncher, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(ACPGetLaunchMetaData, WUPS_LOADER_LIBRARY_NN_ACP, ACPGetLaunchMetaData, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(FSReadFile, WUPS_LOADER_LIBRARY_COREINIT, FSReadFile, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(FSOpenFile, WUPS_LOADER_LIBRARY_COREINIT, FSOpenFile, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(FSCloseFile, WUPS_LOADER_LIBRARY_COREINIT, FSCloseFile, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_PHYSICAL_FOR_PROCESS(MCPGetTitleInternal, (0x3001C400 + 0x0205a590), (0x0205a590 - 0xFE3C00), WUPS_FP_TARGET_PROCESS_WII_U_MENU);
38,376
C++
.cpp
762
41.875328
270
0.6489
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,756
SaveRedirection.cpp
wiiu-env_homebrew_on_menu_plugin/src/SaveRedirection.cpp
#include "SaveRedirection.h" #include "globals.h" #include <content_redirection/redirection.h> #include <coreinit/mcp.h> #include <coreinit/title.h> #include <fs/FSUtils.h> #include <functional> #include <nn/act.h> #include <nn/save.h> #include <notifications/notifications.h> #include <string> #include <utils/StringTools.h> #include <utils/logger.h> #include <wups.h> bool gInWiiUMenu __attribute__((section(".data"))) = false; CRLayerHandle saveLayer __attribute__((section(".data"))) = 0; static inline std::string getBaseSavePathLegacy() { return std::string(HOMEBREW_ON_MENU_PLUGIN_DATA_PATH) + "/save"; } static inline std::string getBaseSavePathLegacyFS() { return std::string("fs:") + getBaseSavePathLegacy(); } static inline std::string getBaseSavePath() { return string_format(HOMEBREW_ON_MENU_PLUGIN_DATA_PATH "/%s/save", gSerialId.c_str()); } static inline std::string getBaseSavePathFS() { return "fs:" + getBaseSavePath(); } void SaveRedirectionCleanUp() { if (saveLayer != 0) { DEBUG_FUNCTION_LINE("Remove save redirection: %s -> %s", "/vol/save", getBaseSavePathFS().c_str()); auto res = ContentRedirection_RemoveFSLayer(saveLayer); if (res != CONTENT_REDIRECTION_RESULT_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Failed to remove save FSLayer"); } saveLayer = 0; } } void CopyExistingFiles() { nn::act::Initialize(); nn::act::PersistentId persistentId = nn::act::GetPersistentId(); nn::act::Finalize(); std::string user = string_format("%s/%08X", getBaseSavePathFS().c_str(), 0x80000000 | persistentId); std::string userLegacy = string_format("%s/%08X", getBaseSavePathLegacyFS().c_str(), 0x80000000 | persistentId); std::string userOriginal = string_format("fs:/vol/save/%08X", 0x80000000 | persistentId); FSUtils::CreateSubfolder(user.c_str()); auto BaristaAccountSaveFilePathNew = user + "/BaristaAccountSaveFile.dat"; auto BaristaAccountSaveFilePathOriginal = userOriginal + "/BaristaAccountSaveFile.dat"; auto BaristaAccountSaveFilePathLegacy = userLegacy + "/BaristaAccountSaveFile.dat"; if (!FSUtils::CheckFile(BaristaAccountSaveFilePathNew.c_str())) { if (FSUtils::CheckFile(BaristaAccountSaveFilePathLegacy.c_str())) { DEBUG_FUNCTION_LINE("Copy %s to %s", BaristaAccountSaveFilePathLegacy.c_str(), BaristaAccountSaveFilePathNew.c_str()); if (!FSUtils::copyFile(BaristaAccountSaveFilePathLegacy, BaristaAccountSaveFilePathNew)) { DEBUG_FUNCTION_LINE_ERR("Failed to copy file: %s -> %s", BaristaAccountSaveFilePathLegacy.c_str(), BaristaAccountSaveFilePathNew.c_str()); } else { if (remove(BaristaAccountSaveFilePathLegacy.c_str()) < 0) { DEBUG_FUNCTION_LINE_ERR("Failed to delete %s", BaristaAccountSaveFilePathLegacy.c_str()); } } } else { DEBUG_FUNCTION_LINE("Copy %s to %s", BaristaAccountSaveFilePathOriginal.c_str(), BaristaAccountSaveFilePathNew.c_str()); if (!FSUtils::copyFile(BaristaAccountSaveFilePathOriginal, BaristaAccountSaveFilePathNew)) { DEBUG_FUNCTION_LINE_ERR("Failed to copy file: %s -> %s", BaristaAccountSaveFilePathOriginal.c_str(), BaristaAccountSaveFilePathNew.c_str()); } } } } void initSaveData() { SaveRedirectionCleanUp(); CopyExistingFiles(); nn::act::Initialize(); nn::act::PersistentId persistentId = nn::act::GetPersistentId(); nn::act::Finalize(); std::string replaceDir = string_format("%s/%08X", getBaseSavePathFS().c_str(), 0x80000000 | persistentId); DEBUG_FUNCTION_LINE("Setup save redirection: %s -> %s", string_format("/vol/save/%08X", 0x80000000 | persistentId), replaceDir.c_str()); auto res = ContentRedirection_AddFSLayer(&saveLayer, "homp_save_redirection", replaceDir.c_str(), FS_LAYER_TYPE_SAVE_REPLACE_FOR_CURRENT_USER); if (res != CONTENT_REDIRECTION_RESULT_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("Failed to add save FS Layer: %d", res); NotificationModule_AddErrorNotification("homebrew on menu plugin: Failed to initialize /vol/save redirection"); } } DECL_FUNCTION(int32_t, LoadConsoleAccount__Q2_2nn3actFUc13ACTLoadOptionPCcb, nn::act::SlotNo slot, nn::act::ACTLoadOption unk1, char const *unk2, bool unk3) { int32_t result = real_LoadConsoleAccount__Q2_2nn3actFUc13ACTLoadOptionPCcb(slot, unk1, unk2, unk3); if (result >= 0 && gInWiiUMenu) { DEBUG_FUNCTION_LINE("Changed account, we need to init the save data"); // If the account has changed, we need to init save data for this account initSaveData(); } return result; } extern bool gHideHomebrew; extern bool sSDIsMounted; DECL_FUNCTION(int32_t, SAVEInit) { auto res = real_SAVEInit(); if (res >= 0) { if (!sSDIsMounted || gHideHomebrew) { DEBUG_FUNCTION_LINE_VERBOSE("Skip SD redirection, no SD Card is mounted"); return res; } if (OSGetTitleID() == 0x0005001010040000L || // Wii U Menu JPN OSGetTitleID() == 0x0005001010040100L || // Wii U Menu USA OSGetTitleID() == 0x0005001010040200L) { // Wii U Menu EUR initSaveData(); gInWiiUMenu = true; } else { gInWiiUMenu = false; } } return res; } DECL_FUNCTION(FSError, FSGetLastErrorCodeForViewer, FSClient *client) { auto res = real_FSGetLastErrorCodeForViewer(client); if (!gInWiiUMenu) { return res; } if ((uint32_t) res == 1503030) { // If we encounter error 1503030 when running the Wii U Menu we probably hit a Wii U Menu save related issue // Either the sd card is write locked or the save on the sd card it corrupted. Let the user now about this. std::string deleteHint = string_format("If not write locked, backup and delete this directory: \"sd:" HOMEBREW_ON_MENU_PLUGIN_DATA_PATH_BASE "/%s\".", gSerialId.c_str()); NotificationModuleHandle handle; NotificationModule_AddDynamicNotification("Caution: This resets the order of application on the Wii U Menu when using Aroma.", &handle); NotificationModule_AddDynamicNotification("", &handle); NotificationModule_AddDynamicNotification(deleteHint.c_str(), &handle); NotificationModule_AddDynamicNotification("", &handle); NotificationModule_AddDynamicNotification("", &handle); NotificationModule_AddDynamicNotification("The SD card appears to be write-locked or the Wii U Menu save on the SD card is corrupted. Check the SD card write lock.", &handle); } return res; } WUPS_MUST_REPLACE_FOR_PROCESS(SAVEInit, WUPS_LOADER_LIBRARY_NN_SAVE, SAVEInit, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(LoadConsoleAccount__Q2_2nn3actFUc13ACTLoadOptionPCcb, WUPS_LOADER_LIBRARY_NN_ACT, LoadConsoleAccount__Q2_2nn3actFUc13ACTLoadOptionPCcb, WUPS_FP_TARGET_PROCESS_WII_U_MENU); WUPS_MUST_REPLACE_FOR_PROCESS(FSGetLastErrorCodeForViewer, WUPS_LOADER_LIBRARY_COREINIT, FSGetLastErrorCodeForViewer, WUPS_FP_TARGET_PROCESS_WII_U_MENU);
7,178
C++
.cpp
132
48.189394
201
0.702349
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,757
StringTools.cpp
wiiu-env_homebrew_on_menu_plugin/src/utils/StringTools.cpp
/*************************************************************************** * Copyright (C) 2010 * by Dimok * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any * damages arising from the use of this software. * * Permission is granted to anyone to use this software for any * purpose, including commercial applications, and to alter it and * redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you * must not claim that you wrote the original software. If you use * this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and * must not be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. * * for WiiXplorer 2010 ***************************************************************************/ #include <cstring> #include <string> #include <strings.h> #include <utils/StringTools.h> #include <wut_types.h> std::string StringTools::remove_extension(const std::string &filename) { size_t lastdot = filename.find_last_of('.'); if (lastdot == std::string::npos) return filename; return filename.substr(0, lastdot); } std::string StringTools::get_extension(const std::string &filename) { size_t lastdot = filename.find_last_of('.'); if (lastdot == std::string::npos) return ""; return filename.substr(lastdot); } int32_t StringTools::strtokcmp(const char *string, const char *compare, const char *separator) { if (!string || !compare) return -1; char TokCopy[512]; strncpy(TokCopy, compare, sizeof(TokCopy)); TokCopy[511] = '\0'; char *strTok = strtok(TokCopy, separator); while (strTok != nullptr) { if (strcasecmp(string, strTok) == 0) { return 0; } strTok = strtok(nullptr, separator); } return -1; } const char *StringTools::FullpathToFilename(const char *path) { if (!path) return path; const char *ptr = path; const char *Filename = ptr; while (*ptr != '\0') { if (ptr[0] == '/' && ptr[1] != '\0') Filename = ptr + 1; ++ptr; } return Filename; } void StringTools::RemoveDoubleSlashs(std::string &str) { uint32_t length = str.size(); //! clear relativeFilepath of double slashes for (uint32_t i = 1; i < length; ++i) { if (str[i - 1] == '/' && str[i] == '/') { str.erase(i, 1); i--; length--; } } } std::vector<std::string> StringTools::StringSplit(const std::string &inValue, const std::string &splitter) { std::string value = inValue; std::vector<std::string> result; while (true) { unsigned int index = value.find(splitter); if (index == std::string::npos) { result.push_back(value); break; } std::string first = value.substr(0, index); result.push_back(first); if (index + splitter.size() == value.length()) { result.push_back(""); break; } if (index + splitter.size() > value.length()) { break; } value = value.substr(index + splitter.size(), value.length()); } return result; }
3,475
C++
.cpp
100
29.47
108
0.607324
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,758
utils.cpp
wiiu-env_homebrew_on_menu_plugin/src/utils/utils.cpp
#include "utils.h" #include "logger.h" #include <coreinit/mcp.h> #include <string> /* hash: compute hash value of string */ unsigned int hash_string(const char *str) { unsigned int h; unsigned char *p; h = 0; for (p = (unsigned char *) str; *p != '\0'; p++) { h = 37 * h + *p; } return h; // or, h % ARRAY_SIZE; } bool Utils::GetSerialId(std::string &serialID) { bool result = false; alignas(0x40) MCPSysProdSettings settings{}; auto handle = MCP_Open(); if (handle >= 0) { if (MCP_GetSysProdSettings(handle, &settings) == 0) { serialID = std::string(settings.code_id) + settings.serial_id; result = true; } else { DEBUG_FUNCTION_LINE_ERR("Failed to get SerialId"); } MCP_Close(handle); } else { DEBUG_FUNCTION_LINE_ERR("MCP_Open failed"); } return result; }
899
C++
.cpp
31
23.548387
74
0.58776
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,760
FileReader.cpp
wiiu-env_homebrew_on_menu_plugin/src/fs/FileReader.cpp
#include "FileReader.h" #include "../utils/logger.h" #include <cstring> int64_t FileReader::read(uint8_t *buffer, uint32_t size) { if (isReadFromBuffer) { if (input_buffer == nullptr) { return -1; } uint32_t toRead = size; if (toRead > input_size - input_pos) { toRead = input_size - input_pos; } if (toRead == 0) { return 0; } memcpy(buffer, &input_buffer[input_pos], toRead); input_pos += toRead; return toRead; } else if (isReadFromFile) { int res = ::read(file_fd, buffer, size); return res; } return -2; } FileReader::FileReader(std::string &path) { int fd; if ((fd = open(path.c_str(), O_RDONLY)) >= 0) { this->isReadFromFile = true; this->isReadFromBuffer = false; this->file_fd = fd; } else { DEBUG_FUNCTION_LINE("## INFO ## Failed to open file %s", path.c_str()); } } FileReader::~FileReader() { if (isReadFromFile) { ::close(this->file_fd); } } FileReader::FileReader(uint8_t *buffer, uint32_t size) { this->input_buffer = buffer; this->input_size = size; this->input_pos = 0; this->isReadFromBuffer = true; this->isReadFromFile = false; } bool FileReader::isReady() { return this->isReadFromFile || this->isReadFromBuffer; }
1,406
C++
.cpp
49
22.795918
79
0.571323
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,763
FileReaderWUHB.cpp
wiiu-env_homebrew_on_menu_plugin/src/fs/FileReaderWUHB.cpp
#include "FileReaderWUHB.h" #include "utils/StringTools.h" #include "utils/logger.h" #include <coreinit/cache.h> #include <wuhb_utils/utils.h> FileReaderWUHB::FileReaderWUHB(const std::shared_ptr<FileInfos> &info, const std::string &relativeFilepath, bool autoUnmount) { if (!info) { DEBUG_FUNCTION_LINE_ERR("Info was NULL"); return; } if (!info->isBundle) { DEBUG_FUNCTION_LINE("Failed to init file reader for %s, is not a bundle.", info->relativeFilepath.c_str()); return; } this->autoUnmount = autoUnmount; this->info = info; std::lock_guard<std::mutex> lock(info->accessLock); auto romfsName = string_format("%08X", info->lowerTitleID); if (!info->MountBundle(romfsName)) { return; } auto filepath = romfsName.append(":/").append(relativeFilepath); WUHBUtilsStatus status; if ((status = WUHBUtils_FileOpen(filepath.c_str(), &this->fileHandle)) != WUHB_UTILS_RESULT_SUCCESS) { DEBUG_FUNCTION_LINE("Failed to open file in bundle: %s error: %d", filepath.c_str(), status); UnmountBundle(); return; } this->info->fileCount++; this->initDone = true; OSMemoryBarrier(); } FileReaderWUHB::~FileReaderWUHB() { if (!this->initDone) { return; } std::lock_guard<std::mutex> lock(info->accessLock); if (this->fileHandle != 0) { if (WUHBUtils_FileClose(this->fileHandle) != WUHB_UTILS_RESULT_SUCCESS) { DEBUG_FUNCTION_LINE_ERR("WUHBUtils_FileClose failed for %08X", this->fileHandle); } this->fileHandle = 0; info->fileCount--; } UnmountBundle(); OSMemoryBarrier(); } int64_t FileReaderWUHB::read(uint8_t *buffer, uint32_t size) { if (!this->initDone) { DEBUG_FUNCTION_LINE_ERR("read file but init was not successful"); return -1; } int32_t outRes = -1; if (WUHBUtils_FileRead(this->fileHandle, buffer, size, &outRes) == WUHB_UTILS_RESULT_SUCCESS) { return outRes; } DEBUG_FUNCTION_LINE_ERR("WUHBUtils_FileRead failed"); return -1; } bool FileReaderWUHB::isReady() { return this->initDone; } void FileReaderWUHB::UnmountBundle() { if (autoUnmount && info->fileCount <= 0) { if (!info->UnmountBundle()) { DEBUG_FUNCTION_LINE_ERR("Failed to unmount"); } } else { DEBUG_FUNCTION_LINE_VERBOSE("Filecount is %d, we don't want to unmount yet", info->fileCount); } }
2,488
C++
.cpp
71
29.394366
127
0.647108
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,764
FileInfos.h
wiiu-env_homebrew_on_menu_plugin/src/FileInfos.h
#pragma once #include "utils/logger.h" #include "utils/utils.h" #include <coreinit/mcp.h> #include <mutex> #include <string> #include <wuhb_utils/utils.h> class FileInfos { public: explicit FileInfos(const std::string &relativePath) : relativeFilepath(relativePath) { this->lowerTitleID = hash_string(relativePath.c_str()); } ~FileInfos() { std::lock_guard<std::mutex> lock(mountLock); if (isMounted) { UnmountBundle(); } } bool MountBundle(const std::string &romfsName) { if (isMounted) { if (mountPath != romfsName) { DEBUG_FUNCTION_LINE_ERR("Can't mount as %s because it's already mounted with a different name (%s)", romfsName.c_str(), mountPath.c_str()); return false; } return true; } if (!isBundle) { DEBUG_FUNCTION_LINE_VERBOSE("Mounting not possible, is not a bundle"); return false; } auto fullMountPath = std::string("/vol/external01/").append(this->relativeFilepath); int32_t outRes = -1; if (WUHBUtils_MountBundle(romfsName.c_str(), fullMountPath.c_str(), BundleSource_FileDescriptor_CafeOS, &outRes) != WUHB_UTILS_RESULT_SUCCESS || outRes < 0) { DEBUG_FUNCTION_LINE_ERR("Failed to mount bundle: %s", romfsName.c_str()); return false; } DEBUG_FUNCTION_LINE_VERBOSE("Succesfully mounted %s", romfsName.c_str()); this->isMounted = true; mountPath = romfsName; return true; } bool UnmountBundle() { if (!isBundle) { DEBUG_FUNCTION_LINE_VERBOSE("Skip unmounting, is not a bundle"); return true; } if (!isMounted) { DEBUG_FUNCTION_LINE_VERBOSE("Skip unmounting, is not mounted"); return true; } int32_t outRes = -1; if (WUHBUtils_UnmountBundle(mountPath.c_str(), &outRes) != WUHB_UTILS_RESULT_SUCCESS || outRes < 0) { DEBUG_FUNCTION_LINE_ERR("Failed to unmount bundle: %s", mountPath.c_str()); return false; } else { DEBUG_FUNCTION_LINE_VERBOSE("Successfully unmounted bundle %s", this->mountPath.c_str()); } this->isMounted = false; this->mountPath.clear(); return true; } std::string relativeFilepath; std::string filename; std::string longname; std::string shortname; std::string author; uint32_t lowerTitleID; MCPTitleListType titleInfo{}; int32_t fileCount = 0; bool isBundle = false; std::mutex accessLock; private: std::mutex mountLock; std::string mountPath; bool isMounted = false; };
2,733
C++
.h
76
28.105263
166
0.610272
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,765
main.h
wiiu-env_homebrew_on_menu_plugin/src/main.h
#pragma once #include "version.h" #define VERSION "v0.1.8" #define VERSION_FULL VERSION VERSION_EXTRA
109
C++
.h
4
25.75
42
0.757282
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,766
SaveRedirection.h
wiiu-env_homebrew_on_menu_plugin/src/SaveRedirection.h
#pragma once extern bool gInWiiUMenu; #define HOMEBREW_ON_MENU_PLUGIN_DATA_PATH_BASE "/wiiu/homebrew_on_menu_plugin" #define HOMEBREW_ON_MENU_PLUGIN_DATA_PATH "/vol/external01" HOMEBREW_ON_MENU_PLUGIN_DATA_PATH_BASE void SaveRedirectionCleanUp();
254
C++
.h
5
49.4
103
0.801619
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,767
utils.h
wiiu-env_homebrew_on_menu_plugin/src/utils/utils.h
#pragma once #include <cstdint> #include <forward_list> #include <malloc.h> #include <memory> #include <mutex> #include <string> uint32_t hash_string(const char *); template<class T, class... Args> std::unique_ptr<T> make_unique_nothrow(Args &&...args) noexcept(noexcept(T(std::forward<Args>(args)...))) { return std::unique_ptr<T>(new (std::nothrow) T(std::forward<Args>(args)...)); } template<class T, class... Args> std::shared_ptr<T> make_shared_nothrow(Args &&...args) noexcept(noexcept(T(std::forward<Args>(args)...))) { return std::shared_ptr<T>(new (std::nothrow) T(std::forward<Args>(args)...)); } template<typename T, class Allocator, class Predicate> bool remove_locked_first_if(std::mutex &mutex, std::forward_list<T, Allocator> &list, Predicate pred) { std::lock_guard<std::mutex> lock(mutex); auto oit = list.before_begin(), it = std::next(oit); while (it != list.end()) { if (pred(*it)) { list.erase_after(oit); return true; } oit = it++; } return false; } namespace Utils { bool GetSerialId(std::string &serialID); }
1,118
C++
.h
32
31.28125
107
0.656799
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,768
logger.h
wiiu-env_homebrew_on_menu_plugin/src/utils/logger.h
#pragma once #include <coreinit/debug.h> #include <string.h> #include <whb/log.h> #ifdef __cplusplus extern "C" { #endif #define LOG_APP_TYPE "P" #define LOG_APP_NAME "homebrew_on_menu" #define __FILENAME_X__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__) #define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILENAME_X__) #define LOG(LOG_FUNC, FMT, ARGS...) LOG_EX(LOG_FUNC, "", "", FMT, ##ARGS) #define LOG_EX(LOG_FUNC, LOG_LEVEL, LINE_END, FMT, ARGS...) \ do { \ LOG_FUNC("[(%s)%18s][%23s]%30s@L%04d: " LOG_LEVEL "" FMT "" LINE_END, LOG_APP_TYPE, LOG_APP_NAME, __FILENAME__, __FUNCTION__, __LINE__, ##ARGS); \ } while (0) #ifdef DEBUG #ifdef VERBOSE_DEBUG #define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) LOG(WHBLogPrintf, FMT, ##ARGS) #else #define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) while (0) #endif #define DEBUG_FUNCTION_LINE(FMT, ARGS...) LOG(WHBLogPrintf, FMT, ##ARGS) #define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...) LOG(WHBLogWritef, FMT, ##ARGS) #define DEBUG_FUNCTION_LINE_ERR(FMT, ARGS...) LOG_EX(WHBLogPrintf, "##ERROR## ", "", FMT, ##ARGS) #define DEBUG_FUNCTION_LINE_WARN(FMT, ARGS...) LOG_EX(WHBLogPrintf, "##WARN ## ", "", FMT, ##ARGS) #define DEBUG_FUNCTION_LINE_INFO(FMT, ARGS...) LOG_EX(WHBLogPrintf, "##INFO ## ", "", FMT, ##ARGS) #else #define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) while (0) #define DEBUG_FUNCTION_LINE(FMT, ARGS...) while (0) #define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...) while (0) #define DEBUG_FUNCTION_LINE_ERR(FMT, ARGS...) LOG_EX(OSReport, "##ERROR## ", "\n", FMT, ##ARGS) #define DEBUG_FUNCTION_LINE_WARN(FMT, ARGS...) LOG_EX(OSReport, "##WARN ## ", "\n", FMT, ##ARGS) #define DEBUG_FUNCTION_LINE_INFO(FMT, ARGS...) LOG_EX(OSReport, "##INFO ## ", "\n", FMT, ##ARGS) #endif void initLogging(); void deinitLogging(); #ifdef __cplusplus } #endif
2,211
C++
.h
40
53.35
154
0.550233
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,769
StringTools.h
wiiu-env_homebrew_on_menu_plugin/src/utils/StringTools.h
/*************************************************************************** * Copyright (C) 2010 * by Dimok * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any * damages arising from the use of this software. * * Permission is granted to anyone to use this software for any * purpose, including commercial applications, and to alter it and * redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you * must not claim that you wrote the original software. If you use * this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and * must not be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. * * for WiiXplorer 2010 ***************************************************************************/ #pragma once #include <memory> #include <string> #include <vector> template<typename... Args> std::string string_format(const std::string &format, Args... args) { int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0' auto size = static_cast<size_t>(size_s); auto buf = std::make_unique<char[]>(size); std::snprintf(buf.get(), size, format.c_str(), args...); return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside } class StringTools { public: static std::string remove_extension(const std::string &filename); static std::string get_extension(const std::string &filename); static int32_t strtokcmp(const char *string, const char *compare, const char *separator); static const char *FullpathToFilename(const char *path); static void RemoveDoubleSlashs(std::string &str); static std::vector<std::string> StringSplit(const std::string &inValue, const std::string &splitter); };
2,075
C++
.h
46
42.456522
105
0.674913
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,773
FileReaderWUHB.h
wiiu-env_homebrew_on_menu_plugin/src/fs/FileReaderWUHB.h
#pragma once #include "../FileInfos.h" #include "FileReader.h" #include <wuhb_utils/utils.h> class FileReaderWUHB : public FileReader { bool initDone = false; std::shared_ptr<FileInfos> info; WUHBFileHandle fileHandle = 0; bool autoUnmount = false; public: explicit FileReaderWUHB(const std::shared_ptr<FileInfos> &info, const std::string &relativeFilepath, bool autoUnmount); ~FileReaderWUHB() override; int64_t read(uint8_t *buffer, uint32_t size) override; bool isReady() override; void UnmountBundle(); };
558
C++
.h
16
31.4375
123
0.725417
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,774
FileReader.h
wiiu-env_homebrew_on_menu_plugin/src/fs/FileReader.h
#pragma once #include <fcntl.h> #include <string> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> class FileReader { public: FileReader(uint8_t *buffer, uint32_t size); explicit FileReader(std::string &path); virtual ~FileReader(); virtual int64_t read(uint8_t *buffer, uint32_t size); virtual bool isReady(); virtual uint32_t getHandle() { return reinterpret_cast<uint32_t>(this); } protected: FileReader() = default; private: bool isReadFromBuffer = false; uint8_t *input_buffer = nullptr; uint32_t input_size = 0; uint32_t input_pos = 0; bool isReadFromFile = false; int file_fd = 0; };
695
C++
.h
26
22.846154
57
0.674772
wiiu-env/homebrew_on_menu_plugin
31
0
4
GPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,775
buddy_check.cpp
metno_titanlib/src/buddy_check.cpp
#include <vector> #include <algorithm> #include <iostream> #define _USE_MATH_DEFINES #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics.hpp> #include <boost/accumulators/statistics/variance.hpp> #include <exception> #include "titanlib.h" using namespace titanlib; ivec titanlib::buddy_check(const Points& points, const vec& values, const vec& radius, const ivec& num_min, float threshold, float max_elev_diff, float elev_gradient, float min_std, int num_iterations, const ivec& obs_to_check) { bool debug = false; const int s = points.size(); // assert that the arrays we expect are of size s if(values.size() != s) { std::stringstream ss; ss <<"'values' (" << values.size() << ") does not have the same length as points (" << s << ")" << std::endl; throw std::invalid_argument(ss.str()); } else if(radius.size() != s && radius.size() != 1) { std::stringstream ss; ss <<"'radius' (" << radius.size() << ") does not have the same length as points (" << s << ")" << std::endl; throw std::invalid_argument(ss.str()); } if(num_min.size() != s && num_min.size() != 1) { std::stringstream ss; ss <<"'num_min' (" << num_min.size() << ") does not have the same length as points (" << s << ")" << std::endl; throw std::invalid_argument(ss.str()); } if(obs_to_check.size() != s && obs_to_check.size() != 1 && obs_to_check.size() !=0) { std::stringstream ss; ss <<"'obs_to_check' (" << obs_to_check.size() << ") does not have the same length as points (" << s << ")" << std::endl; throw std::invalid_argument(ss.str()); } // Check that buddies min is more than 0 for(int i = 0; i < num_min.size(); i++) { if(num_min[i] <= 0) throw std::runtime_error("Buddies_min must be > 0"); } const vec& lats = points.get_lats(); const vec& lons = points.get_lons(); const vec& elevs = points.get_elevs(); // resize the flags and set them to 0 ivec flags(s, 0); if(s==0) { // if no data return empty array return flags; } for(int i = 0; i < num_min.size(); i++) { if(!titanlib::is_valid(values[i])) flags[i] = 1; } // if obs_to_check is empty then check all bool check_all = obs_to_check.size() != s; int num_removed_last_iteration = 0; for(int it = 0; it < num_iterations; it++) { ivec flags_prev = flags; #pragma omp parallel for for(int i = 0; i < s; i++) { // is this one we are supposed to check? int b_i = (num_min.size() == s) ? i : 0; int d_i = (radius.size() == s) ? i : 0; if(flags_prev[i] != 0) continue; if(check_all || obs_to_check[i] == 1) { if(debug) { std::cout << "point: " << lats[i] << " " << lons[i] << " " << elevs[i]; std::cout << ", and min buddies: " << num_min[b_i]; std::cout << '\n'; } // get all neighbours that are close enough ivec neighbour_indices = points.get_neighbours(lats[i], lons[i], radius[d_i], false); int n_buddies = 0; vec list_buddies; // based on tree do have enough neighbours? if(neighbour_indices.size() >= num_min[b_i]) { // loop over everything that was near enough // count buddies and make list of values (adjusting for height diff if needed) for(int j = 0; j < neighbour_indices.size(); j++) { // don't use ones that differ too much in height (max_elev_diff) if(flags_prev[neighbour_indices[j]] != 0) continue; if(max_elev_diff > 0) { float elev_diff = fabs(elevs[neighbour_indices[j]] - elevs[i]); if(elev_diff <= max_elev_diff) { // correction for the elevation differences (add or subtract -0.0065 degC/m) // m difference from point in question float elev_diff = elevs[i] - elevs[neighbour_indices[j]]; //std::cout << "height diff: " << elev_diff; float adjusted_value = values[neighbour_indices[j]] + (elev_diff * elev_gradient); //std::cout << ", adjusted value: " << adjusted_value; //std::cout << '\n'; list_buddies.push_back(adjusted_value); n_buddies++; } else { if(debug) { std::cout << "too much height difference: " << elev_diff << '\n'; } } } // if max_elev_diff is negative then don't check elevation difference else { // can use this station list_buddies.push_back(values[neighbour_indices[j]]); n_buddies++; } } } if(debug) { std::cout << "buddies: " << n_buddies << '\n'; } if(n_buddies >= num_min[b_i]) { // compute the average and standard deviation of the values boost::accumulators::accumulator_set<float, boost::accumulators::features<boost::accumulators::tag::mean, boost::accumulators::tag::variance> > acc; for(int k = 0; k < list_buddies.size(); k++) { acc(list_buddies[k]); } float mean = boost::accumulators::mean(acc); float variance = boost::accumulators::variance(acc); if(debug) { std::cout << "mean: " << mean << '\n'; std::cout << "variance: " << variance << '\n'; } float std = sqrt(variance); float std_adjusted = sqrt(variance + variance / n_buddies); if(std_adjusted < min_std) { std_adjusted = min_std; } float pog = fabs(values[i] - mean)/std_adjusted; if(pog > threshold) { flags[i] = 1; } } } // end if observation is to check } // end loop over values // Check if we need to stop early int num_removed = 0; for(int i = 0; i < s; i++) { if(flags[i] != 0) num_removed++; } int num_removed_curr_iteration = num_removed - num_removed_last_iteration; if(debug) { std::cout << "iteration, number of bad observations: " << it + 1 << ", " << num_removed_curr_iteration << '\n'; } if(num_removed_curr_iteration == 0) { if(debug) std::cout << "Stopping early after iteration " << it + 1 << std::endl; break; } num_removed_last_iteration = num_removed_curr_iteration; } // end loop over num_iterations return flags; }
7,648
C++
.cpp
164
32.018293
168
0.473755
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,776
util.cpp
metno_titanlib/src/util.cpp
#include "titanlib.h" #include <cmath> #include <math.h> #include <assert.h> #include <execinfo.h> #include <signal.h> #include <iomanip> #include <cstdio> #include <exception> #include <sys/time.h> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/vector_proxy.hpp> #include <boost/numeric/ublas/triangular.hpp> #include <boost/numeric/ublas/lu.hpp> #include <boost/numeric/ublas/io.hpp> #include <boost/numeric/ublas/matrix.hpp> #ifdef DEBUG extern "C" void __gcov_flush(); #endif using namespace titanlib; bool titanlib::is_valid(float value) { return !std::isnan(value) && !std::isinf(value) && value != titanlib::MV; } std::string titanlib::version() { return __version__; } void titanlib::initialize_omp() { #ifdef _OPENMP int num_threads = 1; const char* num_threads_char = std::getenv("OMP_NUM_THREADS"); if(num_threads_char != NULL) { std::istringstream(std::string(num_threads_char)) >> num_threads; if(num_threads <= 0) num_threads = 1; } titanlib::set_omp_threads(num_threads); #endif } void titanlib::set_omp_threads(int num) { #ifdef _OPENMP // omp_set_dynamic(0); omp_set_num_threads(num); #endif } int titanlib::get_omp_threads() { #ifdef _OPENMP return omp_get_max_threads(); #endif return 0; } double titanlib::clock() { timeval t; gettimeofday(&t, NULL); double sec = (t.tv_sec); double msec= (t.tv_usec); return sec + msec/1e6; } bool titanlib::convert_coordinates(const vec& lats, const vec& lons, vec& x_coords, vec& y_coords, vec& z_coords) { int N = lats.size(); x_coords.resize(N); y_coords.resize(N); z_coords.resize(N); for(int i = 0; i < N; i++) { convert_coordinates(lats[i], lons[i], x_coords[i], y_coords[i], z_coords[i]); } return true; } bool titanlib::convert_coordinates(float lat, float lon, float& x_coord, float& y_coord, float& z_coord) { float earth_radius = 6.37e6; double lonr = M_PI / 180 * lon; double latr = M_PI / 180 * lat; // std::cout << lon << " " << lat << std::endl; x_coord = std::cos(latr) * std::cos(lonr) * earth_radius; y_coord = std::cos(latr) * std::sin(lonr) * earth_radius; z_coord = std::sin(latr) * earth_radius; return true; } float titanlib::calc_distance(float lat1, float lon1, float lat2, float lon2) { if(!(fabs(lat1) <= 90 && fabs(lat2) <= 90 && fabs(lon1) <= 360 && fabs(lon2) <= 360)) { // std::cout << " Cannot calculate distance, invalid lat/lon: (" << lat1 << "," << lon1 << ") (" << lat2 << "," << lon2 << ")"; // std::cout << '\n'; } if(lat1 == lat2 && lon1 == lon2) return 0; double lat1r = deg2rad(lat1); double lat2r = deg2rad(lat2); double lon1r = deg2rad(lon1); double lon2r = deg2rad(lon2); double radiusEarth = 6.378137e6; double ratio = cos(lat1r)*cos(lon1r)*cos(lat2r)*cos(lon2r) + cos(lat1r)*sin(lon1r)*cos(lat2r)*sin(lon2r) + sin(lat1r)*sin(lat2r); double dist = acos(ratio)*radiusEarth; return (float) dist; } float titanlib::calc_distance(float x0, float y0, float z0, float x1, float y1, float z1) { return sqrt((x0 - x1)*(x0 - x1) + (y0 - y1)*(y0 - y1) + (z0 - z1)*(z0 - z1)); } float titanlib::deg2rad(float deg) { return (deg * M_PI / 180); } vec titanlib::interpolate_to_points(const vec2& input_lats, const vec2& input_lons, const vec2& input_values, const vec& output_lats, const vec& output_lons) { assert(input_lats.size() > 0); assert(input_lats[0].size() > 0); vec output_values(output_lats.size(), 0); vec input_lats_flat(input_lats.size() * input_lats[0].size(), 0); vec input_lons_flat(input_lats.size() * input_lats[0].size(), 0); int X = input_lats[0].size(); int Y = input_lats.size(); int count = 0; for(int i = 0; i < Y; i++) { for(int j = 0; j < X; j++) { input_lats_flat[count] = input_lats[i][j]; input_lons_flat[count] = input_lons[i][j]; count++; } } titanlib::KDTree tree(input_lats_flat, input_lons_flat); for(int i = 0; i < output_lats.size(); i++) { int index = tree.get_nearest_neighbour(output_lats[i], output_lons[i], true); int index_x = index % X; int index_y = index / X; output_values[i] = input_values[index_y][index_x]; } return output_values; } float titanlib::compute_quantile(double quantile, const vec& array) { int n = array.size(); if(n == 0) { throw std::runtime_error("Cannot compute quantile on empty array"); } vec array_copy; array_copy.reserve(n); // make a copy of the vector for(int i = 0; i < n; i++) { if(titanlib::is_valid(array[i])) array_copy.push_back(array[i]); } float exact_q; std::sort(array_copy.begin(), array_copy.end()); n = array_copy.size(); if(n == 0) { throw std::runtime_error("Cannot compute quantile on empty array"); } // get the quantile from sorted array int lowerIndex = floor(quantile * (n-1)); int upperIndex = ceil(quantile * (n-1)); float lowerValue = array_copy[lowerIndex]; float upperValue = array_copy[upperIndex]; float lowerQuantile = (float) lowerIndex / (n-1); float upperQuantile = (float) upperIndex / (n-1); if(lowerIndex == upperIndex) { exact_q = lowerValue; } else { assert(upperQuantile > lowerQuantile); assert(quantile >= lowerQuantile); float f = (quantile - lowerQuantile)/(upperQuantile - lowerQuantile); assert(f >= 0); assert(f <= 1); exact_q = lowerValue + (upperValue - lowerValue) * f; } assert(titanlib::is_valid(exact_q)); return exact_q; } Points titanlib::subset(const Points& input, const ivec& indices) { if(input.size() == 0) return input; if(indices.size() == 0) return input; int size = indices.size(); vec ilats = input.get_lats(); vec ilons = input.get_lons(); vec ielevs = input.get_elevs(); vec ilafs = input.get_lafs(); vec lats(size); vec lons(size); vec elevs(size); vec lafs(size); for(int i=0; i < size; i++) { int index = indices[i]; assert(index < input.size()); lats[i] = ilats[index]; lons[i] = ilons[index]; elevs[i] = ielevs[index]; lafs[i] = ilafs[index]; } return Points(lats, lons, elevs, lafs); } bool titanlib::invert_matrix(const boost::numeric::ublas::matrix<float>& input, boost::numeric::ublas::matrix<float>& inverse) { using namespace boost::numeric::ublas; typedef permutation_matrix<std::size_t> pmatrix; // create a working copy of the input matrix<float> A(input); // create a permutation matrix for the LU-factorization pmatrix pm(A.size1()); // perform LU-factorization int res = lu_factorize(A,pm); if( res != 0 ) return false; // create identity matrix of "inverse" inverse.assign(boost::numeric::ublas::identity_matrix<float>(A.size1())); // backsubstitute to get the inverse lu_substitute(A, pm, inverse); return true; } //+ Set indices when inner and outer circles are present bool titanlib::set_indices( const ivec& indices_global_outer_guess, const ivec& obs_test, const ivec& dqcflags, const vec& dist_outer_guess, float inner_radius, int test_just_this, ivec& indices_global_outer, ivec& indices_global_test, ivec& indices_outer_inner, ivec& indices_outer_test, ivec& indices_inner_test) { /*----------------------------------------------------------------------------- Set all the vectors of indices linking the vectors operating over the different regions that we have defined: global, outer circle, inner circle, observations to test within the inner circle If the index test_just_this is set to a value greater than 0 (i.e. it does point to an observation of the global vectors), then the only observation to test is test_just_this. Rules for an observation to be assigned to: 1) outer circle. Within outer_radius from the centroid and flag!=1 2) inner circle. In the outer circle AND within inner_radius from the centroid 3) test. In the inner circle AND flag!=0 AND the user want to test it ----------------------------------------------------------------------------*/ int p_outer_guess = indices_global_outer_guess.size(); indices_global_outer.reserve(p_outer_guess); indices_global_test.reserve(p_outer_guess); indices_outer_inner.reserve(p_outer_guess); indices_outer_test.reserve(p_outer_guess); indices_inner_test.reserve(p_outer_guess); int i = -1; // counter for indices on outer int l = -1; // counter for indices on inner for(int count=0; count<p_outer_guess; count++) { int g = indices_global_outer_guess[count]; if(dqcflags[g] != 1 && g != test_just_this) { indices_global_outer.push_back(g); i++; if(dist_outer_guess[count] <= inner_radius) { indices_outer_inner.push_back(i); l++; if (test_just_this < 0 && dqcflags[g] != 0 && obs_test[g] == 1) { indices_global_test.push_back(g); indices_outer_test.push_back(i); indices_inner_test.push_back(l); } } } } if ( test_just_this >= 0) { // add global index to global_outer indices as its last element indices_global_outer.push_back(test_just_this); // add global index to global_test as its only element indices_global_test.push_back(test_just_this); // adjust outer_inner, last element of outer_inner points to last element of outer indices_outer_inner.push_back(indices_global_outer.size()-1); // adjust outer_test, only element of test points to last element of outer indices_outer_test.push_back(indices_global_outer.size()-1); // adjust inner_test, only element of test points to last element of inner indices_inner_test.push_back(indices_outer_inner.size()-1); } // return true; } float titanlib::find_k_closest(const vec& array, int k) { int n = array.size(); if(n == 0) { throw std::runtime_error("Cannot compute quantile on empty array"); } vec array_copy(n); // make a copy of the vector for(int i = 0; i < n; i++) array_copy[i] = array[i]; std::sort(array_copy.begin(), array_copy.end()); if(k > n) { k = n-1; } else { k = k-1; } float value = array_copy[k]; return value; }
10,844
C++
.cpp
286
31.933566
159
0.612309
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,777
point.cpp
metno_titanlib/src/point.cpp
#include "titanlib.h" using namespace titanlib; titanlib::Point::Point(float lat, float lon, float elev, float laf, CoordinateType type) { this->lat = lat; this->lon = lon; this->elev = elev; this->laf = laf; this->type = type; }
252
C++
.cpp
9
24.555556
90
0.66805
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,778
isolation_check.cpp
metno_titanlib/src/isolation_check.cpp
#include <vector> #include <math.h> #include "titanlib.h" #include <assert.h> #include <iostream> using namespace titanlib; ivec titanlib::isolation_check(const Points& points, int num_min, float radius, float vertical_radius) { const int s = points.size(); ivec flags(s, 0); const vec& lats = points.get_lats(); const vec& lons = points.get_lons(); const vec& elevs = points.get_elevs(); ivec num_min_array(s); vec radius_array(s); vec vertical_radius_array(s); for(int i = 0; i < s; i++) { num_min_array[i] = num_min; radius_array[i] = radius; vertical_radius_array[i] = vertical_radius; } return isolation_check(points, num_min_array, radius_array, vertical_radius_array); } ivec titanlib::isolation_check(const Points& points, const ivec& num_min, const vec& radius, const vec& vertical_radius) { const int s = points.size(); if(num_min.size() != s) { std::stringstream ss; ss <<"'num_min' (" << num_min.size() << ") does not have the same length as points (" << s << ")" << std::endl; throw std::invalid_argument(ss.str()); } else if(radius.size() != s) { std::stringstream ss; ss <<"'radius' (" << radius.size() << ") does not have the same length as points (" << s << ")" << std::endl; throw std::invalid_argument(ss.str()); } else if(vertical_radius.size() > 0 && vertical_radius.size() != s) { std::stringstream ss; ss <<"'vertical_radius' (" << vertical_radius.size() << ") does not have the same length as points (" << s << ")" << std::endl; throw std::invalid_argument(ss.str()); } ivec flags(s, 0); const vec& lats = points.get_lats(); const vec& lons = points.get_lons(); const vec& elevs = points.get_elevs(); #pragma omp parallel for for(int i = 0; i < s; i++) { if(!titanlib::is_valid(lats[i]) || !titanlib::is_valid(lons[i])) { flags[i] = 1; continue; } if(vertical_radius.size() > 0 && titanlib::is_valid(vertical_radius[i])) { if(!titanlib::is_valid(elevs[i])) { flags[i] = 1; continue; } ivec indices = points.get_neighbours(lats[i], lons[i], radius[i], false); int num = 0; for(int j = 0; j < indices.size(); j++) { int index = indices[j]; if(titanlib::is_valid(elevs[index]) && titanlib::is_valid(elevs[i])) { if(fabs(elevs[index] - elevs[i]) <= vertical_radius[i]) num++; } } if(num < num_min[i]) { flags[i] = 1; } } else { // Faster version when we don't need to check elevations int num = points.get_num_neighbours(lats[i], lons[i], radius[i], false); if(num < num_min[i]) { flags[i] = 1; } } } return flags; }
3,066
C++
.cpp
83
28.361446
135
0.53497
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,779
background.cpp
metno_titanlib/src/background.cpp
#include <vector> #include <math.h> #include "titanlib.h" #include <assert.h> #include <iostream> #include <numeric> #include <exception> #include <gsl/gsl_multimin.h> #include <gsl/gsl_linalg.h> using namespace titanlib; /*---------------------------------------------------------------------------- BACKGROUND FUNCTIONS */ namespace { double basic_vertical_profile_optimizer_function(const gsl_vector *v, void *data); vec basic_vertical_profile(const int n, const double *elevs, const double t0, const double gamma); double vertical_profile_optimizer_function(const gsl_vector *v, void *data); vec vertical_profile(const int n, const double *elevs, const double t0, const double gamma, const double a, const double h0, const double h1i); } /*---------------------------------------------------------------------------- BACKGROUND FUNCTIONS */ //+ Compute the background for all the observations in the outer circle vec titanlib::background(const vec& elevs, const vec& values, int num_min_prof, float min_elev_diff, float value_minp, float value_maxp, BackgroundType background_type, const vec& external_background_values, const ivec& indices_global_outer, bool debug) { vec bvalues; int p = values.size(); if( background_type == titanlib::VerticalProfile) { // vertical profile is independent from the curr-th observation bvalues = titanlib::compute_vertical_profile(elevs, elevs, values, num_min_prof, min_elev_diff, debug); } else if( background_type == titanlib::VerticalProfileTheilSen) { // vertical profile is independent from the curr-th observation bvalues = ::compute_vertical_profile_Theil_Sen(elevs, elevs, values, num_min_prof, min_elev_diff, debug); } else if( background_type == titanlib::MeanOuterCircle){ // vertical profile is independent from the curr-th observation float mean_val = std::accumulate(values.begin(), values.end(), 0.0) / p; bvalues.resize(p, mean_val); } else if( background_type == titanlib::MedianOuterCircle){ // vertical profile is independent from the curr-th observation float median_val = titanlib::compute_quantile( 0.5, values); bvalues.resize(p, median_val); } else if( background_type == titanlib::External){ bvalues = titanlib::subset(external_background_values, indices_global_outer); } // set the range for(int i=0; i<p; i++) { if(titanlib::is_valid(value_minp) && bvalues[i] < value_minp) bvalues[i] = value_minp; if(titanlib::is_valid(value_maxp) && bvalues[i] > value_maxp) bvalues[i] = value_maxp; } // return bvalues; } vec titanlib::compute_vertical_profile(const vec& elevs, const vec& oelevs, const vec& values, int num_min_prof, double min_elev_diff, bool debug) { if(elevs.size() == 0) throw std::invalid_argument("Elevs must have length > 0"); if(oelevs.size() == 0) return vec(); // Starting value guesses double gamma = -0.0065; double a = 5.0; double meanT = std::accumulate(values.begin(), values.end(), 0.0) / values.size(); // Special case when all observations have the same elevation if ( std::min_element(elevs.begin(),elevs.end()) == std::max_element(elevs.begin(),elevs.end())) { vec vp( oelevs.size(), meanT); return vp; } double exact_p10 = titanlib::compute_quantile(0.10, elevs); double exact_p90 = titanlib::compute_quantile(0.90, elevs); // optimize inputs for VP (using Nelder-Mead Simplex algorithm) const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex2; gsl_multimin_fminimizer *s = NULL; gsl_vector *step_size; gsl_multimin_function vp_optim; int iter = 0; int status; double size; // data (params) that needs to be passed into vp double nd = (double) elevs.size(); // cast + resize to double double nod = (double) oelevs.size(); // cast + resize to double std::vector<double> delevs(elevs.begin(), elevs.end()); std::vector<double> doelevs(oelevs.begin(), oelevs.end()); std::vector<double> dvalues(values.begin(), values.end()); double * dpelevs = delevs.data(); double * dpoelevs = doelevs.data(); double * dpvalues = dvalues.data(); double * data[3] = {&nd, dpelevs, dpvalues}; // Check if terrain is too flat double z05 = titanlib::compute_quantile(0.05, elevs); double z95 = titanlib::compute_quantile(0.95, elevs); bool disable_vertical_profile = (z95 - z05) < min_elev_diff; assert(titanlib::is_valid(exact_p10)); assert(titanlib::is_valid(exact_p90)); assert(titanlib::is_valid(meanT)); vec vp; if(disable_vertical_profile) { vp = basic_vertical_profile(nod, dpoelevs, meanT, 0); } else { // should we use the basic or more complicated vertical profile? bool use_basic = (elevs.size() < num_min_prof); gsl_vector* input; if(use_basic) { vp_optim.n = 2; input = gsl_vector_alloc(vp_optim.n); gsl_vector_set(input, 0, meanT); gsl_vector_set(input, 1, gamma); vp_optim.f = basic_vertical_profile_optimizer_function; } else { vp_optim.n = 5; input = gsl_vector_alloc(vp_optim.n); gsl_vector_set(input, 0, meanT); gsl_vector_set(input, 1, gamma); gsl_vector_set(input, 2, a); gsl_vector_set(input, 3, exact_p10); gsl_vector_set(input, 4, exact_p90); vp_optim.f = vertical_profile_optimizer_function; } step_size = gsl_vector_alloc (vp_optim.n); gsl_vector_set_all (step_size, 1.0); vp_optim.params = data; s = gsl_multimin_fminimizer_alloc (T, vp_optim.n); gsl_multimin_fminimizer_set (s, &vp_optim, input, step_size); do { iter++; status = gsl_multimin_fminimizer_iterate(s); if (status) break; size = gsl_multimin_fminimizer_size (s); status = gsl_multimin_test_size (size, 1e-2); } while (status == GSL_CONTINUE && iter < 100); // then actually calculate the vertical profile using the minima if(use_basic) { vp = basic_vertical_profile(nod, dpoelevs, gsl_vector_get(s->x, 0), gsl_vector_get(s->x, 1)); if(debug) std::cout << "vp - meanT=" << gsl_vector_get(s->x, 0) << " gamma=" << gsl_vector_get(s->x, 1) << std::endl; } else { // then actually calculate the vertical profile using the minima vp = vertical_profile(nod, dpoelevs, gsl_vector_get(s->x, 0), gsl_vector_get(s->x, 1), gsl_vector_get(s->x, 2), gsl_vector_get(s->x, 3), gsl_vector_get(s->x, 4)); if(debug) std::cout << "vp - t0 " << gsl_vector_get(s->x, 0) << " gamma=" << gsl_vector_get(s->x, 1) << " a=" << gsl_vector_get(s->x, 2) << " h0=" << gsl_vector_get(s->x, 3) << " h1i=" << gsl_vector_get(s->x, 4) << std::endl; } gsl_vector_free(input); gsl_vector_free(step_size); gsl_multimin_fminimizer_free (s); } return vp; } vec titanlib::compute_vertical_profile_Theil_Sen(const vec& elevs, const vec& oelevs, const vec& values, int num_min_prof, double min_elev_diff, bool debug) { // Starting value guesses double gamma = -0.0065; double min_diff = (double) min_elev_diff; double meanT = std::accumulate(values.begin(), values.end(), 0.0) / values.size(); // Special case when all observations have the same elevation if ( std::min_element(elevs.begin(),elevs.end()) == std::max_element(elevs.begin(),elevs.end())) { vec vp( oelevs.size(), meanT); return vp; } // Check if terrain is too flat double z05 = titanlib::compute_quantile(0.05, elevs); double z95 = titanlib::compute_quantile(0.95, elevs); // should we use the basic or more complicated vertical profile? bool use_basic = elevs.size() < num_min_prof || (z95 - z05) < min_diff; // Theil-Sen (Median-slope) Regression (Wilks (2019), p. 284) int n = elevs.size(); int no = oelevs.size(); int nm = n * (n - 1) / 2; std::vector<float> q(n), m(nm); double m_median; if ( use_basic) { m_median = gamma; } else { int k = 0; for(int i=0; i<(n-1); i++) { for(int j=(i+1); j<n; j++) { float dz = fabs( elevs[i] - elevs[j]); if ( dz < 1 ) { m[k] = 0; } else { m[k] = ( values[i] - values[j]) / ( elevs[i] - elevs[j]); } k++; } } m_median = titanlib::compute_quantile( 0.5, m); } for(int i=0; i<n; i++) { q[i] = values[i] - m_median * elevs[i]; } double q_median = titanlib::compute_quantile( 0.5, q); vec vp(no); if (debug) std::cout << "Theil-Sen vp - m q " << m_median << " " << q_median << std::endl; for(int i=0; i<no; i++) { vp[i] = q_median + m_median * oelevs[i]; } // return vp; } namespace { double basic_vertical_profile_optimizer_function(const gsl_vector *v, void *data) { double **p = (double **)data; int n = (int) *p[0]; // is of type double but should be an int double *dpelevs = p[1]; double *dpvalues = p[2]; if(n == 0) throw std::runtime_error("Cannot optimize basic vertical profile without any data"); // the parameters to mess with double meanT = gsl_vector_get(v,0); double gamma = gsl_vector_get(v,1); // give everything to vp to compute t_out vec t_out = basic_vertical_profile(n, dpelevs, meanT, gamma); // RMS float total = 0; for(int i=0; i<n; i++) { total += pow((t_out[i]-dpvalues[i]),2); } double value = pow((total / n),0.5); if(value < 1e-6) value = 1e-6; value = log(value); assert(titanlib::is_valid(value)); return value; } vec basic_vertical_profile(const int n, const double *elevs, const double t0, const double gamma) { vec t_out(n, titanlib::MV); for(int i=0; i<n; i++) t_out[i] = t0 + gamma*elevs[i]; return t_out; } double vertical_profile_optimizer_function(const gsl_vector *v, void *data) { double **p = (double **)data; int n = (int) *p[0]; // is of type double but should be an int double *dpelevs = p[1]; double *dpvalues = p[2]; // the parameters to mess with double meanT = gsl_vector_get(v,0); double gamma = gsl_vector_get(v,1); double a = gsl_vector_get(v,2); double exact_p10 = gsl_vector_get(v,3); double exact_p90 = gsl_vector_get(v,4); // give everything to vp to compute t_out vec t_out = vertical_profile(n, dpelevs, meanT, gamma, a, exact_p10, exact_p90); // RMS double total = 0; for(int i=0; i<n; i++) { total += pow((t_out[i]-dpvalues[i]),2); } double value = pow((total / n),0.5); if(value < 1e-6) value = 1e-6; value = log(value); assert(titanlib::is_valid(value)); return value; } vec vertical_profile(const int n, const double *elevs, const double t0, const double gamma, const double a, const double h0, const double h1i) { double h1 = h0 + fabs(h1i); // h1<-h0+abs(h1i) // loop over the array of elevations vec t_out; t_out.resize(n, -999); for(int i=0; i<n; i++) { // define some bools bool z_le_h0 = elevs[i] <= h0; // z.le.h0<-which(z<=h0) bool z_ge_h1 = elevs[i] >= h1; // z.ge.h1<-which(z>=h1) bool z_in = (elevs[i]>h0 && elevs[i]<h1); // z.in<-which(z>h0 & z<h1) if(z_le_h0) { t_out[i] = t0+gamma*elevs[i]-a; } if(z_ge_h1) { t_out[i] = t0+gamma*elevs[i]; } if(z_in) { t_out[i] = t0+gamma*elevs[i]-a/2*(1+cos(M_PI*(elevs[i]-h0)/(h1-h0))); } } return t_out; } }
12,290
C++
.cpp
275
36.683636
255
0.583897
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,780
sct_resistant.cpp
metno_titanlib/src/sct_resistant.cpp
#include <vector> #include <math.h> #include "titanlib.h" #include <assert.h> #include <iostream> #include <numeric> #include <exception> #include <gsl/gsl_multimin.h> #include <gsl/gsl_linalg.h> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/vector_proxy.hpp> #include <boost/numeric/ublas/triangular.hpp> #include <boost/numeric/ublas/lu.hpp> #include <boost/numeric/ublas/io.hpp> #include <boost/numeric/ublas/matrix.hpp> using namespace titanlib; // SCT within the inner circle bool sct_core( const vec& lats, const vec& lons, const vec& elevs, const vec& yo, const vec& yb, float Dh_min, float Dh_max, int kth_close, float Dz, const vec& eps2, float minp, float maxp, const vec& mina, const vec& maxa, const vec& minv, const vec& maxv, const vec& tpos, const vec& tneg, const ivec& indices_global_test, const ivec& indices_outer_inner, const ivec& indices_outer_test, const ivec& indices_inner_test, bool debug, bool basic, float na, bool set_flag0, int& thrown_out, vec& scores, ivec& flags); //============================================================================= //+ SCT - Spatial Consistency Test ivec titanlib::sct_resistant( const Points& points, const vec& values, const ivec& obs_to_check, const vec& background_values, BackgroundType background_elab_type, int num_min_outer, int num_max_outer, float inner_radius, float outer_radius, int num_iterations, int num_min_prof, float min_elev_diff, float min_horizontal_scale, float max_horizontal_scale, int kth_closest_obs_horizontal_scale, float vertical_scale, const vec& values_mina, const vec& values_maxa, const vec& values_minv, const vec& values_maxv, const vec& eps2, const vec& tpos, const vec& tneg, bool debug, bool basic, vec& scores) { /* -+-+ Spatial Consistency Test +-+- + Description: Flag observations that are (likely) affected by gross measurement errors (GE) based on neighbouring observations. Observations are affected by GEs if their values are (a) [not related to the actual atmospheric state] OR (b) [affected by such large representativeness errors (REs) that they are difficult to reconstruct using the neighbouring observations]. For simplicity, we will refer to observations affected by GE as bad observations, viceversa good observations are those not affected by GEs. + Reference: Lussana, C., Uboldi, F. and Salvati, M.R. (2010), A spatial consistency test for surface observations from mesoscale meteorological networks. Q.J.R. Meteorol. Soc., 136: 1075-1088. doi:10.1002/qj.622 (Reference Abbreviation: LUS10) See also the wiki-pages https://github.com/metno/titanlib/wiki/Spatial-consistency-test + Algorithm: The big task of applying the SCT over the whole observational network is splitted into several smaller tasks. The SCT is applied many times in sequence. Each time, the SCT is applied over a small region centered on an observation location (i.e. the centroid observation). Based on the centroid, we define an inner circle and an outer circle. The outer circle is used to obtain a spatial trend of the observed variable over the region, the so-called background. There are many ways to compute such background values. The observations to test are those within the inner circle that have not been tested yet. The quality of those observations is determined by comparing them against estimates calculated considering all observations within the outer circle. Considering an observations, we use an estimate that depends on the observed value (analysis) and one that is indipendent of it (leave-one-out cross-validation analysis, or cv-analysis). See also the comments of the function "sct_core" for more details. The application of the sequence of SCTs over the whole observational network is repeated several times, until no GEs are found within the observations tested. In fact, the core of SCT is to test a single observation against an independent estimate that is obtained assuming all the neighbouring observations are good ones. As a consequence, a bad observation can influence the results of some tests on neighbouring observations before being rejected. We apply special care to avoid "false positives" (good flagged as bad). For each SCT over a centroid, we flag as bad only the observation showing the worst result. In addition, an extra-loop is done over the bad observations where only the good ones are considered. We may "save" bad observations. Analogously, to avoid "false negatives" (bad flagged as good), the last loop is done over the bad observations where only the good ones are considered. We may "save" bad observations during this last loop. (*) Notes on prior information (see also comments in sct_core): the user is expected to provide two different range of values, that inform about the desired tolerance level of the SCT. i. The range of admissible values (values_mina,values_maxa). A range for each observation. The observed value have to be within the corresponding range (e.g. observation=2, then OK if values_mina=0 & values_maxa=4; not OK if values_mina=10 & values_maxa=14). A cv-analysis outside this range warns us about possible problems with the observation. a. The range of plausible values (value_minp,value_maxp) is derived from the range of admissible values and it is used to check the analyses and backgrounds. Outside this range the values do not make sense. ii. The range of valid values (values_minv,values_maxv). A range for each observation. The observed value have to be within the corresponding range. If the cv-analysis is within this range, then we assume the corresponding observation is a good one, regardless of the SCT score. Examples: Temperature: 3 observed values(degC)=( 10, 15, 5). (values_mina,values_maxa) = observed values plus/minus 15 degC. (values_minv,values_maxv) = observed values plus/minus 1 degC. Precipitation: 3 observed values(mm)=( 0, 50, 1). (values_mina,values_maxa) = observed values plus/minus either 10 mm or 50% of the value. (values_minv,values_maxv) = observed values plus/minus either 1 mm or 10% of the value. (*) Notes on the data structures (see also comments in set_indices): we have defined a hierarchy of data structures global -> outer -> inner -> test global vectors are the input vectors. The other data structures refer to a specific iteration when a centroid observation has been identified. outer are the vectors of data on the outer circle, not yet flagged as bad. inner are the data on the inner circle, not yet flagged as bad. test data are the observations in the inner circle and still to test. We use the same counter variables for the data structures: g -> global; i,j -> outer; l -> inner; m -> test There are vectors of indices matching the different structures. For example, indices_outer_inner matches the outer and the inner vectors. indices_outer_inner is a vector of the dimension of the number of observations in the inner circle. The instruction i=indices_outer_inner[l] maps the l-th element of inner-type vectors as the i-th element of outer-type vectors. (*) Notes on the thresholds. Different thresholds can be used for different observations. The thresholds vectors have the same dimensions of the observations vectors (global). For each observation, two thresholds (tpos,tneg) have to be set by the user. tpos is the threshold used when the observed value is higher than the cv-analysis, otherwise tneg is used. + Pseudo-code: Loop over the number of iterations prescribed Loop over the p observations (observation index is "curr"). Decide if the observation is suitable for a centroid Define outer/inner cirles, observations to test and set all the vector of indices Check if the observation is isolated Compute the background If the deviations between observations and background is small enough that further steps are not needed and the observations to test are flagged as good ones SCT over the inner circle, either flag the worse observation as bad or flag all of them as good ones NOTE: observations can be flagged as good ones only after the first iteration (after rejecting the worst) Loop over the observations without QC flags (nor good neither bad) and use each of them as a centroid Loop over the bad observations and use each of them as a centroid + Returned values: scores. only for observations rejected by the SCT, z-score (See sct_core) flags. -999 = not checked; 0 = passed (good); 1 = failed (bad); 11 = isolated (<2 inside inner); 12 = isolated (<num_min_outer inside outer) */ double s_time = titanlib::clock(); const vec& lats = points.get_lats(); const vec& lons = points.get_lons(); const vec& elevs = points.get_elevs(); const int p = values.size(); if( lats.size() != p || lons.size() != p || elevs.size() != p || values.size() != p || tpos.size() != p || tneg.size() != p || eps2.size() != p || values_mina.size() != p || values_maxa.size() != p || values_minv.size() != p || values_maxv.size() != p) throw std::runtime_error("Dimension mismatch"); if(num_min_outer < 2) throw std::invalid_argument("num_min_outer must be > 1"); if(num_max_outer < num_min_outer) throw std::invalid_argument("num_max_outer must be > num_min_outer"); if(num_iterations < 1) throw std::invalid_argument("num_iterations must be >= 1"); if(min_elev_diff <= 0) throw std::invalid_argument("min_elev_diff must be > 0"); if(min_horizontal_scale <= 0) throw std::invalid_argument("min_horizontal_scale must be > 0"); if(kth_closest_obs_horizontal_scale <= 0) throw std::invalid_argument("kth_closest_obs_horizontal_scale must be > 0"); if(vertical_scale <= 0) throw std::invalid_argument("vertical_scale must be > 0"); if(inner_radius < 0) throw std::invalid_argument("inner_radius must be >= 0"); if(outer_radius < inner_radius) throw std::invalid_argument("outer_radius must be >= inner_radius"); if(background_elab_type == titanlib::VerticalProfile && num_min_prof<0) throw std::invalid_argument("num_min_prof must be >=0"); if(background_elab_type == External && background_values.size() != p) throw std::runtime_error("Background vector dimension mismatch"); // initializations float na = -999.; // code for "Not Available". Any type of missing data ivec flags( p, na); ivec obs_test( p, 1); bool set_all_good = false; scores.clear(); scores.resize( p, na); if (obs_to_check.size() == p) { for(int g=0; g < p; g++) obs_test[g] = obs_to_check[g]; } /* plausible values are inferred from admissible values note: a range check should be performed before doing the SCT. The SCT can mistake obvious large errors for good observations if they happen to be close enough that they support each other */ float value_minp = values_mina[0]; float value_maxp = values_maxa[0]; for(int g=1; g < p; g++) { if ( values_mina[g] < value_minp) value_minp = values_mina[g]; if ( values_maxa[g] > value_maxp) value_maxp = values_maxa[g]; } if(debug) std::cout << "=============================================== " << p << std::endl; if(debug) std::cout << "Number of observations to test is " << p << std::endl; if(debug) std::cout << "Min and max acceptable values are " << value_minp << " " << value_maxp << std::endl; // KDtree has to do with fast computation of distances titanlib::KDTree tree(lats, lons); // if(debug) { std::cout << "g lats lons elevs obs:" << std::endl; for(int g=0; g < p; g++) { std::cout << g << " " << lats[g] << " " << lons[g] << " " << elevs[g] << " " << values[g] << std::endl; } } // SCT iterations for(int iteration = 0; iteration < num_iterations; iteration++) { if(debug) std::cout << " +++++ Iteration " << iteration << " ++++++++++++++++" << std::endl; double s_time0 = titanlib::clock(); // reset this number each loop (this is for breaking if we don't throw anything new out) int thrown_out = 0; // diagnostic. count the number of times OI is performed int count_oi = 0; // loop over observations for(int curr=0; curr < p; curr++) { if(debug) std::cout << "===> curr " << curr << " ===============" << std::endl; // -~- Can the observation be used as a centroid for the definition of inner and outer circles? // jump to next if observation not to be checked or already checked if(obs_test[curr] != 1 || flags[curr] >= 0) { if(debug) std::cout << "..observation not suitable as a centroid " << curr << std::endl; continue; } // -~- Define outer/inner circles and which are the observations to test // get all neighbours that are close enough (inside outer circle) vec distances; ivec indices_global_outer_guess = tree.get_neighbours_with_distance(lats[curr], lons[curr], outer_radius, distances, true); if(indices_global_outer_guess.size() > num_max_outer) { int N = indices_global_outer_guess.size(); std::vector<std::pair<float,int> > pairs(N); for(int i = 0; i < indices_global_outer_guess.size(); i++) { pairs[i] = std::pair<float, int>(distances[i], indices_global_outer_guess[i]); } std::sort(pairs.begin(), pairs.end(), titanlib::sort_pair_first<float,int>()); distances.clear(); indices_global_outer_guess.clear(); distances.resize(num_max_outer); indices_global_outer_guess.resize(num_max_outer); for(int i = 0; i < num_max_outer; i++) { distances[i] = pairs[i].first; indices_global_outer_guess[i] = pairs[i].second; } } if(debug) { int p_dist = distances.size(); std::cout << "p_dist " << p_dist << std::endl; } // set all the indices linking the different levels ivec indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test; bool res = titanlib::set_indices( indices_global_outer_guess, obs_test, flags, distances, inner_radius, -1, indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test); int p_outer = indices_global_outer.size(); int p_inner = indices_outer_inner.size(); int p_test = indices_global_test.size(); if(debug) std::cout << "p_outer inner test " << p_outer << " " << p_inner << " " << "" << p_test << std::endl; // -~- Check if there are enough observations in the outer/inner circles if(p_outer < num_min_outer) { flags[curr] = 12; if(debug) std::cout << "@@isolated (outer) " << curr << std::endl; continue; } if( p_inner < 2) { flags[curr] = 11; if(debug) std::cout << "@@isolated (inner) " << curr << std::endl; continue; } // -~- Vectors on the outer circle vec lons_outer = titanlib::subset(lons, indices_global_outer); vec elevs_outer = titanlib::subset(elevs, indices_global_outer); vec lats_outer = titanlib::subset(lats, indices_global_outer); vec values_outer = titanlib::subset(values, indices_global_outer); vec eps2_outer = titanlib::subset(eps2, indices_global_outer); vec tpos_outer = titanlib::subset(tpos, indices_global_outer); vec tneg_outer = titanlib::subset(tneg, indices_global_outer); vec mina_outer = titanlib::subset(values_mina, indices_global_outer); vec minv_outer = titanlib::subset(values_minv, indices_global_outer); vec maxa_outer = titanlib::subset(values_maxa, indices_global_outer); vec maxv_outer = titanlib::subset(values_maxv, indices_global_outer); // Debug for indices if(debug) { ivec flags_outer; flags_outer.resize( p_outer, na); for(int i=0; i < p_outer; i++) { int g = indices_global_outer[i]; flags_outer[i] = flags[g]; } std::cout << "curr lats lons elevs obs:" << std::endl; std::cout << curr << " " << lats[curr] << " " << lons[curr] << " " << elevs[curr] << " " << values[curr] << std::endl; std::cout << "indices_global_outer - i g lats lons elevs obs flags:" << std::endl; for(int i=0; i<p_outer; i++) { int g = indices_global_outer[i]; std::cout << std::setprecision(6) << i << " " << g << " " << lats[g] << " " << lons[g] << " " << elevs[g] << " " << values[g] << " " << flags[g] << std::endl; } std::cout << "outer - i lats lons elevs obs flags:" << std::endl; for(int i=0; i<p_outer; i++) { std::cout << std::setprecision(6) << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_outer_inner - l i lats lons elevs obs flags:" << std::endl; for(int l=0; l<p_inner; l++) { int i = indices_outer_inner[l]; std::cout << std::setprecision(6) << l << " " << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_outer_test - l m lats lons elevs obs flags:" << std::endl; for(int m=0; m<p_test; m++) { int i = indices_outer_test[m]; std::cout << std::setprecision(6) << m << " " << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_inner_test - l m lats lons elevs obs flags:" << std::endl; for(int m=0; m<p_test; m++) { int l = indices_inner_test[m]; int i = indices_outer_inner[l]; std::cout << std::setprecision(6) << m << " " << l << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } } // -~- Compute the background vec bvalues_outer = titanlib::background(elevs_outer, values_outer, num_min_prof, min_elev_diff, value_minp, value_maxp, background_elab_type, background_values, indices_global_outer, debug); if(debug) { std::cout << "... background ok ..." << std::endl; std::cout << "outer - i lats lons elevs yo yb flags:" << std::endl; for(int i=0; i<p_outer; i++) { int g = indices_global_outer[i]; std::cout << std::setprecision(6) << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << values_outer[i] << " " << bvalues_outer[i] << " " << flags[g] << std::endl; } } // -~- If deviations between backgrounds and observations are small then flag = 0 /* if observations and background are almost identical (within the range of valid estimates), then take a shortcut and flag = 0 for all observations in the inner circle */ bool small_innov = true; for(int m=0; m<p_test; m++) { int j = indices_outer_test[m]; if(bvalues_outer[j] < minv_outer[j] || bvalues_outer[j] > maxv_outer[j]) small_innov = false; } if (small_innov) { for(int m=0; m<p_test; m++) { int g = indices_global_test[m]; flags[g] = 0; if (debug) std::cout << " small_innov - index " << g << std::endl; } continue; } // -~- SCT on a selection of observations to test in the inner circle bool set_flag0 = iteration > 0; res = sct_core( lats_outer, lons_outer, elevs_outer, values_outer, bvalues_outer, min_horizontal_scale, max_horizontal_scale, kth_closest_obs_horizontal_scale, vertical_scale, eps2_outer, value_minp, value_maxp, mina_outer, maxa_outer, minv_outer, maxv_outer, tpos_outer, tneg_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test, debug, basic, na, set_flag0, thrown_out, scores, flags); // thrown_out is reset every new iteration // problems during the matrix inversion if ( !res) { flags[curr] = 100; if(debug) std::cout << " oi - flags=100 - index " << curr << std::endl; continue; } count_oi++; // one more OI } // end loop over observations double e_time0 = titanlib::clock(); if (debug) std::cout << "SCT loop - Removing " << thrown_out << " observations. Number of OI " << count_oi << " time=" << e_time0 - s_time0 << " secs" << std::endl; if(thrown_out == 0) { if ( iteration == 0) set_all_good = true; if(iteration + 1 < num_iterations) if (debug) std::cout << "Stopping early after " << iteration + 1<< " iterations" << std::endl; break; } } // end of SCT iterations /* enter if the first iteration has been completed without flagging any bad observation The loop flags all the observations as good ones */ if ( set_all_good) { int count_zero = 0; for(int curr=0; curr < p; curr++) { if ( flags[curr] == na && obs_test[curr] == 1) { flags[curr] = 0; count_zero++; } } if(debug) std::cout << "Remaining " << count_zero << " observations set to \"good\" " << std::endl; } /* check on observations missing QC flags */ if(debug) std::cout << " +++++ check on observations missing QC flags ++++++++++++++++" << std::endl; double s_time0 = titanlib::clock(); // reset this number each loop (this is for breaking if we don't throw anything new out) int thrown_out = 0; // diagnostic. count the number of times OI is performed int count_oi = 0; // loop over observations for(int curr=0; curr < p; curr++) { if(debug) std::cout << "===> curr " << curr << " ===============" << std::endl; // -~- Can the observation be used as a centroid for the definition of inner and outer circles? if(obs_test[curr] != 1 || flags[curr] >= 0) { if(debug) std::cout << "..skip " << curr << std::endl; continue; } // -~- Define outer/inner circles and which are the observations to test // get all neighbours that are close enough (inside outer circle) vec distances; ivec indices_global_outer_guess = tree.get_neighbours_with_distance(lats[curr], lons[curr], outer_radius, distances, true); if(indices_global_outer_guess.size() > num_max_outer) { int N = indices_global_outer_guess.size(); std::vector<std::pair<float,int> > pairs(N); for(int i = 0; i < indices_global_outer_guess.size(); i++) { pairs[i] = std::pair<float, int>(distances[i], indices_global_outer_guess[i]); } std::sort(pairs.begin(), pairs.end(), titanlib::sort_pair_first<float,int>()); distances.clear(); indices_global_outer_guess.clear(); distances.resize(num_max_outer); indices_global_outer_guess.resize(num_max_outer); for(int i = 0; i < num_max_outer; i++) { distances[i] = pairs[i].first; indices_global_outer_guess[i] = pairs[i].second; } } // set all the indices linking the different levels // note that the only observation to test is curr ivec indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test; bool res = titanlib::set_indices( indices_global_outer_guess, obs_test, flags, distances, inner_radius, curr, indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test); int p_outer = indices_global_outer.size(); int p_inner = indices_outer_inner.size(); int p_test = indices_global_test.size(); if(debug) std::cout << "p_outer inner test " << p_outer << " " << p_inner << " " << p_test << std::endl; // -~- Check if there are enough observations in the outer/inner circles if(p_outer < num_min_outer) { flags[curr] = 12; if(debug) std::cout << "@@isolated (outer) " << curr << std::endl; continue; } if( p_inner < 2) { flags[curr] = 11; if(debug) std::cout << "@@isolated (inner) " << curr << std::endl; continue; } // -~- Vectors on the outer circle vec lons_outer = titanlib::subset(lons, indices_global_outer); vec elevs_outer = titanlib::subset(elevs, indices_global_outer); vec lats_outer = titanlib::subset(lats, indices_global_outer); vec values_outer = titanlib::subset(values, indices_global_outer); vec eps2_outer = titanlib::subset(eps2, indices_global_outer); vec tpos_outer = titanlib::subset(tpos, indices_global_outer); vec tneg_outer = titanlib::subset(tneg, indices_global_outer); vec mina_outer = titanlib::subset(values_mina, indices_global_outer); vec minv_outer = titanlib::subset(values_minv, indices_global_outer); vec maxa_outer = titanlib::subset(values_maxa, indices_global_outer); vec maxv_outer = titanlib::subset(values_maxv, indices_global_outer); // -~- Compute the background vec bvalues_outer = titanlib::background(elevs_outer, values_outer, num_min_prof, min_elev_diff, value_minp, value_maxp, background_elab_type, background_values, indices_global_outer, debug); if(debug) { std::cout << "... background ok ..." << std::endl; std::cout << "outer - i lats lons elevs yo yb flags:" << std::endl; for(int i=0; i<p_outer; i++) { int g = indices_global_outer[i]; std::cout << std::setprecision(6) << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << values_outer[i] << " " << bvalues_outer[i] << " " << flags[g] << std::endl; } } // -~- If deviations between backgrounds and observations are small then flag = 0 /* if observations and background are almost identical (within the range of valid estimates), then take a shortcut and flag = 0 for all observations in the inner circle */ int j = indices_outer_test[0]; if(bvalues_outer[j] > minv_outer[j] && bvalues_outer[j] < maxv_outer[j]) { int g = indices_global_test[0]; flags[g] = 0; if (debug) std::cout << " small_innov - index " << g << std::endl; continue; } // -~- SCT on a selection of observations to test in the inner circle res = sct_core( lats_outer, lons_outer, elevs_outer, values_outer, bvalues_outer, min_horizontal_scale, max_horizontal_scale, kth_closest_obs_horizontal_scale, vertical_scale, eps2_outer, value_minp, value_maxp, mina_outer, maxa_outer, minv_outer, maxv_outer, tpos_outer, tneg_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test, debug, basic, na, true, thrown_out, scores, flags); // problems during the matrix inversion if ( !res) { flags[curr] = 100; if(debug) std::cout << " oi - flags=100 - index " << curr << std::endl; continue; } count_oi++; // one more OI } // end loop over observations double e_time0 = titanlib::clock(); if (debug) std::cout << "QC missing - Removing " << thrown_out << " observations. Number of OI " << count_oi << " time=" << e_time0 - s_time0 << " secs" << std::endl; /* final check on the bad observations it may happen that a good observation is flagged as a bad one because of the order the SCT has been done and the uncertainty made in the estimation of the background (remember that bad observations may have been used to get the background). This final check is made only on bad observations and uses only good observations. */ if(debug) std::cout << " +++++ final check on the bad observations ++++++++++++++++" << std::endl; s_time0 = titanlib::clock(); // reset this number each loop (this is for breaking if we don't throw anything new out) thrown_out = 0; // diagnostic. count the number of times OI is performed count_oi = 0; // loop over observations for(int curr=0; curr < p; curr++) { if(debug) std::cout << "===> curr " << curr << " ===============" << std::endl; // -~- Can the observation be used as a centroid for the definition of inner and outer circles? if(obs_test[curr] != 1 || flags[curr] != 1 || values[curr] < value_minp || values[curr] > value_maxp) { if(debug) std::cout << "..skip " << curr << std::endl; continue; } // -~- Define outer/inner circles and which are the observations to test // get all neighbours that are close enough (inside outer circle) vec distances; ivec indices_global_outer_guess = tree.get_neighbours_with_distance(lats[curr], lons[curr], outer_radius, distances, true); if(indices_global_outer_guess.size() > num_max_outer) { int N = indices_global_outer_guess.size(); std::vector<std::pair<float,int> > pairs(N); for(int i = 0; i < indices_global_outer_guess.size(); i++) { pairs[i] = std::pair<float, int>(distances[i], indices_global_outer_guess[i]); } std::sort(pairs.begin(), pairs.end(), titanlib::sort_pair_first<float,int>()); distances.clear(); indices_global_outer_guess.clear(); distances.resize(num_max_outer); indices_global_outer_guess.resize(num_max_outer); for(int i = 0; i < num_max_outer; i++) { distances[i] = pairs[i].first; indices_global_outer_guess[i] = pairs[i].second; } } // set all the indices linking the different levels ivec indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test; bool res = titanlib::set_indices( indices_global_outer_guess, obs_test, flags, distances, inner_radius, curr, indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test); int p_outer = indices_global_outer.size(); int p_inner = indices_outer_inner.size(); int p_test = indices_global_test.size(); if(debug) std::cout << "p_outer inner test " << p_outer << " " << p_inner << " " << p_test << std::endl; // -~- Decide if there are enough observations in the outer/inner circles if(p_outer < num_min_outer) { flags[curr] = 12; if(debug) std::cout << "@@isolated (outer) " << curr << std::endl; continue; } if( p_inner < 2) { flags[curr] = 11; if(debug) std::cout << "@@isolated (inner) " << curr << std::endl; continue; } // -~- Set vectors on the outer circle vec lons_outer = titanlib::subset(lons, indices_global_outer); vec elevs_outer = titanlib::subset(elevs, indices_global_outer); vec lats_outer = titanlib::subset(lats, indices_global_outer); vec values_outer = titanlib::subset(values, indices_global_outer); vec eps2_outer = titanlib::subset(eps2, indices_global_outer); vec tpos_outer = titanlib::subset(tpos, indices_global_outer); vec tneg_outer = titanlib::subset(tneg, indices_global_outer); vec mina_outer = titanlib::subset(values_mina, indices_global_outer); vec minv_outer = titanlib::subset(values_minv, indices_global_outer); vec maxa_outer = titanlib::subset(values_maxa, indices_global_outer); vec maxv_outer = titanlib::subset(values_maxv, indices_global_outer); // Debug for indices if(debug) { ivec flags_outer; flags_outer.resize( p_outer, na); for(int i=0; i < p_outer; i++) { int g = indices_global_outer[i]; flags_outer[i] = flags[g]; } std::cout << "curr lats lons elevs obs:" << std::endl; std::cout << curr << " " << lats[curr] << " " << lons[curr] << " " << elevs[curr] << " " << values[curr] << std::endl; std::cout << "indices_global_outer - i g lats lons elevs obs flags:" << std::endl; for(int i=0; i<p_outer; i++) { int g = indices_global_outer[i]; std::cout << std::setprecision(6) << i << " " << g << " " << lats[g] << " " << lons[g] << " " << elevs[g] << " " << values[g] << " " << flags[g] << std::endl; } std::cout << "outer - i lats lons elevs obs flags:" << std::endl; for(int i=0; i<p_outer; i++) { std::cout << std::setprecision(6) << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_outer_inner - l i lats lons elevs obs flags:" << std::endl; for(int l=0; l<p_inner; l++) { int i = indices_outer_inner[l]; std::cout << std::setprecision(6) << l << " " << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_outer_test - l m lats lons elevs obs flag:" << std::endl; for(int m=0; m<p_test; m++) { int i = indices_outer_test[m]; std::cout << std::setprecision(6) << m << " " << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_inner_test - l m lats lons elevs obs flags:" << std::endl; for(int m=0; m<p_test; m++) { int l = indices_inner_test[m]; int i = indices_outer_inner[l]; std::cout << std::setprecision(6) << m << " " << l << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } } // -~- Compute the background vec bvalues_outer = titanlib::background(elevs_outer, values_outer, num_min_prof, min_elev_diff, value_minp, value_maxp, background_elab_type, background_values, indices_global_outer, debug); if(debug) { int j = indices_outer_test[0]; for(int i=0; i < p_outer; i++) { std::cout << std::setprecision(6) << "values backg minv maxv " << values_outer[i] << " " << bvalues_outer[i] << " " << minv_outer[i] << " " << maxv_outer[i] << " " << std::endl; } std::cout << "j " << j << std::endl; std::cout << "... background ok ..." << std::endl; std::cout << "outer - i lats lons elevs yo yb flags:" << std::endl; for(int i=0; i<p_outer; i++) { int g = indices_global_outer[i]; std::cout << std::setprecision(6) << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << values_outer[i] << " " << bvalues_outer[i] << " " << flags[g] << std::endl; } } if(debug) std::cout << "... background ok ..." << std::endl; // -~- If deviations between backgrounds and observations are small then flag = 0 /* if observations and background are almost identical (within the range of valid estimates), then take a shortcut and flag = 0 for all observations in the inner circle */ int j = indices_outer_test[0]; if(bvalues_outer[j] > minv_outer[j] && bvalues_outer[j] < maxv_outer[j]) { int g = indices_global_test[0]; flags[g] = 0; if (debug) std::cout << " small_innov - index " << g << std::endl; continue; } // -~- SCT within the inner circle // note that the only observation to test is curr res = sct_core( lats_outer, lons_outer, elevs_outer, values_outer, bvalues_outer, min_horizontal_scale, max_horizontal_scale, kth_closest_obs_horizontal_scale, vertical_scale, eps2_outer, value_minp, value_maxp, mina_outer, maxa_outer, minv_outer, maxv_outer, tpos_outer, tneg_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test, debug, basic, na, true, thrown_out, scores, flags); // problems during the matrix inversion if ( !res) { flags[curr] = 100; if(debug) std::cout << " oi - flags=100 - index " << curr << std::endl; continue; } count_oi++; // one more OI } // end loop over observations e_time0 = titanlib::clock(); if (debug) std::cout << "Re-check bad obs - Removing " << thrown_out << " observations. Number of OI " << count_oi << "time = " << e_time0 - s_time0 << " secs" << std::endl; // if(debug) { int count_bad = 0; int count_good = 0; int count_missing = 0; int count_iso_inner = 0; int count_iso_outer = 0; int count_fail_matinv = 0; int count_impossible = 0; // loop over observations for(int curr=0; curr < p; curr++) { if( flags[curr] == 1) { count_bad++; } else if( flags[curr] == 0) { count_good++; } else if ( flags[curr] == na) { count_missing++; } else if( flags[curr] == 11) { count_iso_inner++; } else if( flags[curr] == 12) { count_iso_outer++; } else if( flags[curr] == 100) { count_fail_matinv++; } else { count_impossible++; } } std::cout << std::setprecision(3) << "summary - # TOT good bad missing isolated(inner) isolated(outer): " << p << " " << count_good << " " << count_bad << " " << count_missing << " " << count_iso_inner << " " << count_iso_outer << std::endl; if(count_fail_matinv > 0) std::cout << std::setprecision(3) << "!!!! failure in matrix inversion: " << count_fail_matinv << std::endl; if(count_impossible > 0) std::cout << std::setprecision(3) << "!!!! unknown flag: " << count_impossible << std::endl; } // if(debug) std::cout << ">> Total Time " << e_time0 - s_time << "secs" << std::endl; // return flags; } // end SCT // //----------------------------------------------------------------------------// // SCT WITHIN THE INNER CIRCLE // Smallets SCT unit bool sct_core( const vec& lats, const vec& lons, const vec& elevs, const vec& yo, const vec& yb, float Dh_min, float Dh_max, int kth_close, float Dz, const vec& eps2, float minp, float maxp, const vec& mina, const vec& maxa, const vec& minv, const vec& maxv, const vec& tpos, const vec& tneg, const ivec& indices_global_test, const ivec& indices_outer_inner, const ivec& indices_outer_test, const ivec& indices_inner_test, bool debug, bool basic, float na, bool set_flag0, int& thrown_out, vec& scores, ivec& flags) { /*----------------------------------------------------------------------------- Spatial consistency test for a selection of observations to test within the inner circle, considering all the observations in the outer circle. The inner and outer circles are defined with respect to a centroid observation. Each observation to test is compared against an estimated value (cvanalysis) obtained considering the neighbouring observations but without considering the observation under test (leave-one-out cross-validation). In addition, the SCT evaluate the likelihood that the observed value is draw from a Gaussian(good) rather than a uniform(bad) PDF. The evaluation requires the computation of an additional estimate, the analysis, which is the best estimate of the value at an observation location when we consider all the observed values, even the observation under test. Both analysis and cvanalysis are calculated taking into consideration all observations in the outer circle. SCT scores: chi = sqrt( analysis_residual * cvanalysis_residual) analysis residual = yo - ya cvanalysis residual = yo - yav basic mode: z = chi advanced (non basic) mode: z = (chi - mu) / (sigma + sigma_mu) mu = median( chi(*)) sigma = inter-quartile range of chi(*) sigma_mu = sigma / sqrt(n(*)) (*) statistics based on the n observations that are within the inner circle and with a cvanalysis within the range of admissible values. SCT fails (the test shows the uniform PDF as the most likely) when: z > tpos, yo >= yav z > tneg, yo < yav Our prior knowledge includes the definition of two confidence levels for the cvanalysis: - valid values, range [minv,maxv] cvanalysis is so close that it validates the corresponding observation - admissible values, range [mina,maxa] if cvanalysis is outside this range, then the observation is bad Note that the statistics defining the spread used in the SCT is based on deviations between observations and estimates that lie within the range of admissible values only. Decision tree: ALL observations are set to bad when: the cvanalyses all lie outside the range of admissible values ONE observation is deemed as bad when: fails the SCT with the largest z-score AND cvanalysis is outside the range of valid values ALL observations are set to good when: the user allows the procedure to flag them as good ones (set_flag0 is true) AND the cvanalyses all lie within the range of valid values OR none of the cvanalysis fail the SCT test Output values: flags, global vector. return updated quality control flag values (1 = bad, 0 = good) scores, global vector. return updated scores. Note that only for the case of a single bad observation we store the z-score thrown_out, integer. update the number of observations flagged as bad ones -----------------------------------------------------------------------------*/ using namespace boost::numeric::ublas; // init int p_outer = yo.size(); int p_inner = indices_outer_inner.size(); int p_test = indices_global_test.size(); /* Compute Dh. The location-dependent horizontal de-correlation lenght scale used for the background error correlation matrix */ boost::numeric::ublas::matrix<float> disth(p_outer, p_outer); boost::numeric::ublas::matrix<float> distz(p_outer, p_outer); boost::numeric::ublas::vector<float> Dh(p_outer); for(int i=0; i < p_outer; i++) { vec Dh_vector(p_outer); int k = 0; for(int j=i; j < p_outer; j++) { disth(i, j) = titanlib::calc_distance( lats[i], lons[i], lats[j], lons[j]); distz(i, j) = fabs( elevs[i] - elevs[j]); if(i != j) { disth(j, i) = disth(i, j); distz(j, i) = distz(i, j); Dh_vector[k] = disth(i, j); k++; } } for(int j=0; j <= i; j++) { Dh_vector[k] = disth(i, j); k++; } // find distance to the k-th closest observations Dh(i) = titanlib::find_k_closest(Dh_vector, kth_close); if(debug) std::cout << "i Dh " << i << " " << Dh(i) << std::endl; } float Dh_mean = std::accumulate(std::begin(Dh), std::end(Dh), 0.0) / Dh.size(); if(Dh_mean < Dh_min) { if(debug) std::cout << "Dh_mean (<min_horizontal_scale) " << Dh_mean << std::endl; Dh_mean = Dh_min; } if(Dh_mean > Dh_max) { if(debug) std::cout << "Dh_mean (>max_horizontal_scale) " << Dh_mean << std::endl; Dh_mean = Dh_max; } if(debug) std::cout << "Dh_mean " << Dh_mean << std::endl; if(debug) std::cout << "Dz " << Dz << std::endl; // Compute S + eps2*I and store it in S boost::numeric::ublas::matrix<float> S(p_outer,p_outer); boost::numeric::ublas::matrix<float> Sinv(p_outer,p_outer); for(int i=0; i < p_outer; i++) { for(int j=i; j < p_outer; j++) { float value = std::exp(-.5 * std::pow((disth(i, j) / Dh_mean), 2) - .5 * std::pow((distz(i, j) / Dz), 2)); if(i==j) { // weight the diagonal, this also ensure an invertible matrix value = value + eps2[i]; } else { S(j,i) = value; } S(i,j) = value; } } // Compute ( S + eps2 * I )^(-1) ans store it in Sinv bool b = invert_matrix(S, Sinv); if( !b) return( false); // Definitions boost::numeric::ublas::vector<float> Sinv_d(p_outer); // Matrix multiplications ( S + eps2 * I )^(-1) * (yo - yb) for(int i=0; i<p_outer; i++) { S(i,i) -= eps2[i]; float acc = 0; for(int j=0; j<p_outer; j++) { acc += Sinv(i,j) * (yo[j] - yb[j]); } Sinv_d(i) = acc; } // obtain chi = sqrt( analysis_residual * cvanalysis_residual) // two chi vectors are obtained: // 1. chi_inner, chi for all observations in the inner circle // 2. chi_stat, chi values used to extract summary stastics // observations in the inner circle AND yav has an admissible value vec chi_stat; vec chi_stat_alt; chi_stat.reserve(p_inner); chi_stat_alt.reserve(p_inner); boost::numeric::ublas::vector<float> chi_inner(p_inner); boost::numeric::ublas::vector<float> chi_inner_alt(p_inner); boost::numeric::ublas::vector<float> yav(p_inner); if(debug) std::cout << "analysis - i l lon lat elevs yo yb ya yav chi chi_alt" << std::endl; for(int l=0; l<p_inner; l++) { int i = indices_outer_inner[l]; float ya = yb[i]; for(int j=0; j<p_outer; j++) ya += S(i,j)*Sinv_d(j); yav(l) = yo[i] - Sinv_d(i) / Sinv(i,i); if(ya < minp) ya = minp; if(ya > maxp) ya = maxp; if(yav(l) < minp) yav(l) = minp; if(yav(l) > maxp) yav(l) = maxp; chi_inner(l) = std::sqrt( (yo[i] - ya) * (yo[i] - yav(l))); chi_inner_alt(l) = std::sqrt( eps2[i] / ( 1 + eps2[i])) * ( maxv[i] - minv[i]); if ( yav(l) >= mina[i] && yav(l) <= maxa[i]) { chi_stat.push_back(chi_inner(l)); chi_stat_alt.push_back(chi_inner_alt(l)); } if(debug) std::cout << std::setprecision(6) << i << " " << l << " " << lons[i] << " " << lats[i] << " " << elevs[i] << " " << yo[i] << " " << yb[i] << " " << ya << " " << yav(l) << " " << chi_inner(l) << " " << chi_inner_alt(l) << std::endl; } // chi_stat is empty (yav all outside the range of admissible values), set all flags to 1 if(chi_stat.size() == 0) { for(int m=0; m<p_test; m++) { int g = indices_global_test[m]; flags[g] = 1; thrown_out++; if(debug) std::cout << std::setprecision(3) << "chi_stat empty - flag as bad " << g << std::endl; } return true; } // chi summary statistics float mu=0., sigma=0., sigma_mu=0.; if (!basic) { mu = titanlib::compute_quantile( 0.5, chi_stat); sigma = titanlib::compute_quantile( 0.75, chi_stat) - titanlib::compute_quantile( 0.25, chi_stat); float sigma_alt = titanlib::compute_quantile( 0.75, chi_stat_alt) - titanlib::compute_quantile( 0.25, chi_stat_alt); if (sigma_alt > sigma) sigma = sigma_alt; if(sigma == 0) { if(debug) std::cout << "sigma = 0, not possible to perform the spatial check " << std::endl; return true; } sigma_mu = sigma / std::sqrt( chi_stat.size()); if(debug) { std::cout << " chi_stat, dim = " << chi_stat.size() << std::endl; for(int l=0; l<chi_stat.size(); l++) std::cout << std::setprecision(6) << chi_stat[l] << std::endl; std::cout << std::setprecision(6) << " mu sigma sigma_mu " << mu << " " << sigma << " " << sigma_mu << std::endl; } } // z = ( chi - mu ) / ( sigma + sigma_mu ) float zmx = -10000; int mmx = -1; if(debug) std::cout << "z_test - i l lons lats elevs yo yb yav chi z " << std::endl; for(int m=0; m<p_test; m++) { int i = indices_outer_test[m]; int l = indices_inner_test[m]; float z; if (basic) { z = chi_inner(l); } else { z = (chi_inner(l) - mu) / (sigma + sigma_mu); } if (z > zmx && (yav(l) < minv[i] || yav(l) > maxv[i])) { zmx = z; mmx = m; } if(debug) std::cout << std::setprecision(6) << i << " " << l << " " << lons[i] << " " << lats[i] << " " << elevs[i] << " " << yo[i] << " " << yb[i] << " " << yav(l) << " " << chi_inner(l) << " " << z << std::endl; } // Decision making float thr = 0; int i = 0; int l = 0; if ( mmx >= 0) { i = indices_outer_test[mmx]; l = indices_inner_test[mmx]; // set the threshold thr = tneg[i]; if ( (yo[i] - yb[i]) >= 0) thr = tpos[i]; } // if the largest z is larger than the threshold, then flag IT as bad ... if ( zmx > thr) { int g = indices_global_test[mmx]; scores[g] = zmx; flags[g] = 1; thrown_out++; if(debug) std::cout << std::setprecision(6) << "SCT failed - flag as bad - index yo yav chi z " << g << " " << yo[i] << " " << yav(l) << " " << chi_inner(l) << " " << zmx << std::endl; // ... BUT if the largest z is smaller than the threshold (and we are confindet in flagging), then flag ALL as good } else if (set_flag0) { for(int m=0; m<p_test; m++) { int g = indices_global_test[m]; flags[g] = 0; if(debug) std::cout << "all set to good - g " << g << std::endl; } } // normal exit return true; }
52,854
C++
.cpp
878
49.454442
516
0.576966
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,781
kdtree.cpp
metno_titanlib/src/kdtree.cpp
#include "titanlib.h" #include <boost/function_output_iterator.hpp> using namespace titanlib; titanlib::KDTree::KDTree(vec lats, vec lons, CoordinateType type) { mLats = lats; mLons = lons; mType = type; vec x, y, z; titanlib::KDTree::convert_coordinates(mLats, mLons, x, y, z); for(int i = 0; i < mLats.size(); i++) { point p(x[i], y[i], z[i]); mTree.insert(std::make_pair(p, i)); } } int titanlib::KDTree::get_num_neighbours(float lat, float lon, float radius, bool include_match) const { #if 0 // This doesn't seem to be any faster float x, y, z; titanlib::KDTree::convert_coordinates(lat, lon, x, y, z); size_t cardinality = 0; auto count_only = boost::make_function_output_iterator([&cardinality] (boost::geometry::index::rtree< value, boost::geometry::index::quadratic<16> >::value_type const&) { ++cardinality; }); point p(x, y, z); within_radius r(p, radius); if(!include_match) { // Include match search is_not_equal s(p); mTree.query(boost::geometry::index::satisfies(r) && boost::geometry::index::satisfies(s), count_only); } else { mTree.query(boost::geometry::index::satisfies(r), count_only); } int num = cardinality; return num; #else ivec indices = get_neighbours(lat, lon, radius, include_match); return indices.size(); #endif } ivec titanlib::KDTree::get_neighbours_with_distance(float lat, float lon, float radius, vec& distances, bool include_match) const { float x, y, z; titanlib::KDTree::convert_coordinates(lat, lon, x, y, z); ivec indices = get_neighbours(lat, lon, radius, include_match); int num = indices.size(); distances.resize(num); for(int i = 0; i < num; i++) { float x1, y1, z1; titanlib::KDTree::convert_coordinates(mLats[indices[i]], mLons[indices[i]], x1, y1, z1); distances[i] = titanlib::KDTree::calc_distance(x, y, z, x1, y1, z1); } return indices; } ivec titanlib::KDTree::get_neighbours(float lat, float lon, float radius, bool include_match) const { float x, y, z; titanlib::KDTree::convert_coordinates(lat, lon, x, y, z); std::vector<value> results; #if 1 point p(x, y, z); within_radius r(p, radius); if(!include_match) { // Include match search is_not_equal s(p); mTree.query(boost::geometry::index::satisfies(r) && boost::geometry::index::satisfies(s), std::back_inserter(results)); } else { mTree.query(boost::geometry::index::satisfies(r), std::back_inserter(results)); } int num = results.size(); ivec ret; ret.reserve(num); for(int i = 0; i < num; i++) { ret.push_back(results[i].second); } #else box bx(point(x - radius, y - radius, z - radius), point(x + radius, y + radius, z + radius)); mTree.query(boost::geometry::index::within(bx), std::back_inserter(results)); int num = results.size(); ivec ret; ret.reserve(num); for(int i = 0; i < num; i++) { float x1, y1, z1; titanlib::KDTree::convert_coordinates(mLats[results[i].second], mLons[results[i].second], x1, y1, z1); float dist = titanlib::KDTree::calc_distance(x, y, z, x1, y1, z1); if(dist <= radius) { ret.push_back(results[i].second); } } #endif return ret; } ivec titanlib::KDTree::get_closest_neighbours(float lat, float lon, int num, bool include_match) const { float x, y, z; titanlib::KDTree::convert_coordinates(lat, lon, x, y, z); point p(x, y, z); std::vector<value> results; if(!include_match) { is_not_equal s(p); mTree.query(boost::geometry::index::nearest(p, num) && boost::geometry::index::satisfies(s), std::back_inserter(results)); } else { mTree.query(boost::geometry::index::nearest(p, num), std::back_inserter(results)); } int num_found = results.size(); ivec ret; ret.reserve(num); for(int i = 0; i < num_found; i++) { ret.push_back(results[i].second); } return ret; } int titanlib::KDTree::get_nearest_neighbour(float lat, float lon, bool include_match) const { return get_closest_neighbours(lat, lon, 1, include_match)[0]; } bool titanlib::KDTree::convert_coordinates(const vec& lats, const vec& lons, vec& x_coords, vec& y_coords, vec& z_coords) const { int N = lats.size(); x_coords.resize(N); y_coords.resize(N); z_coords.resize(N); for(int i = 0; i < N; i++) { convert_coordinates(lats[i], lons[i], x_coords[i], y_coords[i], z_coords[i]); } return true; } bool titanlib::KDTree::convert_coordinates(float lat, float lon, float& x_coord, float& y_coord, float& z_coord) const { if(mType == titanlib::Cartesian) { x_coord = lon; y_coord = lat; z_coord = 0; } else { double lonr = M_PI / 180 * lon; double latr = M_PI / 180 * lat; // std::cout << lon << " " << lat << std::endl; x_coord = std::cos(latr) * std::cos(lonr) * titanlib::radius_earth; y_coord = std::cos(latr) * std::sin(lonr) * titanlib::radius_earth; z_coord = std::sin(latr) * titanlib::radius_earth; } return true; } float titanlib::KDTree::calc_distance(float lat1, float lon1, float lat2, float lon2, CoordinateType type) { if(type == titanlib::Cartesian) { float dx = lon1 - lon2; float dy = lat1 - lat2; return sqrt(dx * dx + dy * dy); } else if(type == titanlib::Geodetic){ if(!(fabs(lat1) <= 90 && fabs(lat2) <= 90 && fabs(lon1) <= 360 && fabs(lon2) <= 360)) { // std::cout << " Cannot calculate distance, invalid lat/lon: (" << lat1 << "," << lon1 << ") (" << lat2 << "," << lon2 << ")"; // std::cout << '\n'; } if(lat1 == lat2 && lon1 == lon2) return 0; double lat1r = deg2rad(lat1); double lat2r = deg2rad(lat2); double lon1r = deg2rad(lon1); double lon2r = deg2rad(lon2); double radiusEarth = 6.378137e6; double ratio = cos(lat1r)*cos(lon1r)*cos(lat2r)*cos(lon2r) + cos(lat1r)*sin(lon1r)*cos(lat2r)*sin(lon2r) + sin(lat1r)*sin(lat2r); double dist = acos(ratio)*radiusEarth; return (float) dist; } } float titanlib::KDTree::calc_distance_fast(float lat1, float lon1, float lat2, float lon2, CoordinateType type) { if(type == titanlib::Cartesian) { float dx = lon1 - lon2; float dy = lat1 - lat2; return sqrt(dx * dx + dy * dy); } else if(type == titanlib::Geodetic){ double lat1r = deg2rad(lat1); double lat2r = deg2rad(lat2); double lon1r = deg2rad(lon1); double lon2r = deg2rad(lon2); float dx2 = pow(cos((lat1r+lat2r)/2),2)*(lon1r-lon2r)*(lon1r-lon2r); float dy2 = (lat1r-lat2r)*(lat1r-lat2r); return titanlib::radius_earth*sqrt(dx2+dy2); } else { throw std::runtime_error("Unknown coordinate type"); } } float titanlib::KDTree::calc_distance_fast(const Point& p1, const Point& p2) { assert(p1.type == p2.type); return calc_distance_fast(p1.lat, p1.lon, p2.lat, p2.lon, p1.type); } float titanlib::KDTree::calc_distance(float x0, float y0, float z0, float x1, float y1, float z1) { return sqrt((x0 - x1)*(x0 - x1) + (y0 - y1)*(y0 - y1) + (z0 - z1)*(z0 - z1)); } float titanlib::KDTree::deg2rad(float deg) { return (deg * M_PI / 180); } float titanlib::KDTree::rad2deg(float rad) { return (rad * 180 / M_PI); } vec titanlib::KDTree::get_lats() const { return mLats; } vec titanlib::KDTree::get_lons() const { return mLons; } int titanlib::KDTree::size() const { return mLats.size(); } CoordinateType titanlib::KDTree::get_coordinate_type() const { return mType; } titanlib::KDTree& titanlib::KDTree::operator=(titanlib::KDTree other) { std::swap(mLats, other.mLats); std::swap(mLons, other.mLons); std::swap(mTree, other.mTree); std::swap(mType, other.mType); return *this; } titanlib::KDTree::KDTree(const titanlib::KDTree& other) { mLats = other.mLats; mLons = other.mLons; mTree = other.mTree; mType = other.mType; } titanlib::KDTree::within_radius::within_radius(point p, float radius) { this->p = p; this->radius = radius; } bool titanlib::KDTree::within_radius::operator()(value const& v) const { float x0 = v.first.get<0>(); float y0 = v.first.get<1>(); float z0 = v.first.get<2>(); float x1 = p.get<0>(); float y1 = p.get<1>(); float z1 = p.get<2>(); return titanlib::KDTree::calc_distance(x0, y0, z0, x1, y1, z1) <= radius; } titanlib::KDTree::is_not_equal::is_not_equal(point p) { this->p = p; } bool titanlib::KDTree::is_not_equal::operator()(value const& v) const { float x0 = v.first.get<0>(); float y0 = v.first.get<1>(); float z0 = v.first.get<2>(); return p.get<0>() != x0 || p.get<1>() != y0 || p.get<2>() != z0; }
9,009
C++
.cpp
242
31.834711
193
0.614936
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,782
duplicate_check.cpp
metno_titanlib/src/duplicate_check.cpp
#include "titanlib.h" #include <vector> #include <iostream> using namespace titanlib; ivec titanlib::duplicate_check(const Points& points, float radius, float vertical_range) { const vec& lats = points.get_lats(); const vec& lons = points.get_lons(); const vec& elevs = points.get_elevs(); ivec keep; ivec checked(points.size(), 0); // Which points have been checked keep.reserve(points.size()); bool do_elevation_check = titanlib::is_valid(vertical_range); if(do_elevation_check) { for(int i = 0; i < points.size(); i++) { if(!titanlib::is_valid(elevs[i])) checked[i] = 1; } } // TODO: Can this be parallelized? Looks difficult... for(int i = 0; i < points.size(); i++) { if(checked[i] == 1) continue; ivec indices = points.get_neighbours(lats[i], lons[i], radius, true); const int num = indices.size(); checked[i] = 1; keep.push_back(i); if(num > 1) { // Count how many are within the elevation range if(do_elevation_check) { for(int j = 0; j < indices.size(); j++) { float curr_elev = elevs[indices[j]]; if(!titanlib::is_valid(curr_elev)) checked[indices[j]] = 1; else if(titanlib::is_valid(curr_elev) && (fabs(elevs[i] - curr_elev) <= vertical_range)) checked[indices[j]] = 1; } } else { for(int j = 0; j < num; j++) { checked[indices[j]] = 1; } } } } ivec flags(points.size(), 1); for(int i = 0; i < keep.size(); i++) { flags[keep[i]] = 0; } return flags; }
1,805
C++
.cpp
50
26.26
108
0.515152
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,783
sct.cpp
metno_titanlib/src/sct.cpp
#include <vector> #include <math.h> #include "titanlib.h" #include <assert.h> #include <iostream> #include <numeric> #include <exception> #include <gsl/gsl_multimin.h> #include <gsl/gsl_linalg.h> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/vector_proxy.hpp> #include <boost/numeric/ublas/triangular.hpp> #include <boost/numeric/ublas/lu.hpp> #include <boost/numeric/ublas/io.hpp> #include <boost/numeric/ublas/matrix.hpp> using namespace titanlib; // helpers void remove_flagged(ivec& indices, vec& distances, const ivec& flags); // start SCT // ivec titanlib::sct(const Points& points, const vec& values, // determine if we have too many or too few observations // (too many means we can reduce the distance, too few mean isolation problem and cannot flag?) int num_min, int num_max, // first find everything close to the point that we are testing (maxdist) float inner_radius, float outer_radius, int num_iterations, int num_min_prof, float min_elev_diff, float min_horizontal_scale, float vertical_scale, const vec& pos, const vec& neg, const vec& eps2, vec& prob_gross_error, vec& rep, const ivec& obs_to_check) { const vec& lats = points.get_lats(); const vec& lons = points.get_lons(); const vec& elevs = points.get_elevs(); const int s = values.size(); if(lats.size() != s) throw std::runtime_error("Lats does not have same size as values"); if(lons.size() != s) throw std::runtime_error("Lons does not have same size as values"); if(elevs.size() != s) throw std::runtime_error("Elevs does not have same size as values"); if(pos.size() != s) throw std::runtime_error("Pos does not have same size as values"); if(neg.size() != s || eps2.size() != s) throw std::runtime_error("Neg does not have same size as values"); if(eps2.size() != s) throw std::runtime_error("Eps2 does not have same size as values"); if(obs_to_check.size() > 0 && obs_to_check.size() != s) throw std::invalid_argument("obs_to_check must empty or have the same size as values"); if(num_min < 2) throw std::invalid_argument("num_min must be > 1"); if(num_max < num_min) throw std::invalid_argument("num_max must be > num_min"); if(num_iterations < 1) throw std::invalid_argument("num_iterations must be >= 1"); if(min_elev_diff <= 0) throw std::invalid_argument("min_elev_diff must be > 0"); if(min_horizontal_scale <= 0) throw std::invalid_argument("min_horizontal_scale must be > 0"); if(vertical_scale <= 0) throw std::invalid_argument("vertical_scale must be > 0"); if(inner_radius < 0) throw std::invalid_argument("inner_radius must be >= 0"); if(outer_radius < inner_radius) throw std::invalid_argument("outer_radius must be >= inner_radius"); for(int i = 0; i < eps2.size(); i++) { if(eps2[i] <= 0) throw std::invalid_argument("All eps2 values must be > 0"); if(pos[i] < 0) throw std::invalid_argument("All pos values must be >= 0"); if(neg[i] < 0) throw std::invalid_argument("All neg values must be >= 0"); } ivec flags(s, 0); prob_gross_error.clear(); prob_gross_error.resize(s, 0); rep.clear(); rep.resize(s, 0); titanlib::KDTree tree(lats, lons); // Flag stations without elevation for(int curr=0; curr < s; curr++) { if(!titanlib::is_valid(elevs[curr])) { flags[curr] = 1; } } for(int iteration = 0; iteration < num_iterations; iteration++) { double s_time0 = titanlib::clock(); int thrown_out = 0; // reset this number each loop (this is for breaking if we don't throw anything new out) ivec checked(s, 0); // Keep track of which observations have been checked int count_oi = 0; for(int curr=0; curr < s; curr++) { if(obs_to_check.size() == s && obs_to_check[curr] != 1) { checked[curr] = 1; continue; } // break out if station already flagged if(flags[curr] != 0) { checked[curr] = 1; continue; } if(checked[curr] > 0) { continue; } // get all neighbours that are close enough vec distances; ivec neighbour_indices = tree.get_neighbours_with_distance(lats[curr], lons[curr], outer_radius, distances, true); remove_flagged(neighbour_indices, distances, flags); if(neighbour_indices.size() > num_max) { int N = neighbour_indices.size(); std::vector<std::pair<float,int> > pairs(N); for(int i = 0; i < neighbour_indices.size(); i++) { pairs[i] = std::pair<float, int>(distances[i], neighbour_indices[i]); } std::sort(pairs.begin(), pairs.end(), titanlib::sort_pair_first<float,int>()); distances.clear(); neighbour_indices.clear(); distances.resize(num_max); neighbour_indices.resize(num_max); for(int i = 0; i < num_max; i++) { distances[i] = pairs[i].first; neighbour_indices[i] = pairs[i].second; } } if(neighbour_indices.size() < num_min) { checked[curr] = 1; // flag as isolated? continue; // go to next station, skip this one } // call SCT with this box vec lons_box = titanlib::subset(lons, neighbour_indices); vec elevs_box = titanlib::subset(elevs, neighbour_indices); vec lats_box = titanlib::subset(lats, neighbour_indices); vec values_box = titanlib::subset(values, neighbour_indices); vec eps2_box = titanlib::subset(eps2, neighbour_indices); int s_box = neighbour_indices.size(); // the thing to flag is at "curr", ano not included in the box // Compute the background vec vp; if(num_min_prof >= 0) { vp = titanlib::background(elevs_box, values_box, num_min_prof, min_elev_diff, titanlib::MV, titanlib::MV, titanlib::VerticalProfile, vec(), ivec(), false); } else { double meanT = std::accumulate(values_box.begin(), values_box.end(), 0.0) / values_box.size(); vp.resize(s_box, titanlib::MV); for(int l = 0; l < s_box; l++) { vp[l] = meanT; } } boost::numeric::ublas::matrix<float> disth(s_box, s_box); boost::numeric::ublas::matrix<float> distz(s_box, s_box); boost::numeric::ublas::vector<float> Dh(s_box); for(int i=0; i < s_box; i++) { vec Dh_vector(s_box); for(int j=0; j < s_box; j++) { disth(i, j) = titanlib::calc_distance(lats_box[i], lons_box[i], lats_box[j], lons_box[j]); distz(i, j) = fabs(elevs_box[i] - elevs_box[j]); if(i != j) { if(i < j) Dh_vector[j - 1] = disth(i, j); else if(i > j) Dh_vector[j] = disth(i, j); } } Dh(i) = titanlib::compute_quantile(0.10, Dh_vector); } double Dh_mean = std::accumulate(std::begin(Dh), std::end(Dh), 0.0) / Dh.size(); if(Dh_mean < min_horizontal_scale) { Dh_mean = min_horizontal_scale; } boost::numeric::ublas::matrix<float> S(s_box,s_box); boost::numeric::ublas::matrix<float> Sinv(s_box,s_box); for(int i=0; i < s_box; i++) { for(int j=0; j < s_box; j++) { double value = std::exp(-.5 * std::pow((disth(i, j) / Dh_mean), 2) - .5 * std::pow((distz(i, j) / vertical_scale), 2)); if(i==j) { // weight the diagonal?? (0.5 default) value = value + eps2_box[i]; } S(i,j) = value; } } boost::numeric::ublas::vector<float> d(s_box); for(int i=0; i < s_box; i++) { d(i) = values_box[i] - vp[i]; // difference between actual temp and temperature from vertical profile } /* --------------------------------------------------- Beginning of real SCT ------------------------------------------------------*/ bool b = titanlib::invert_matrix(S, Sinv); if(b != true) { // TODO: flag differently or give an error??? continue; } // Unweight the diagonal for(int i=0; i < s_box; i++) { S(i,i) -= eps2_box[i]; } boost::numeric::ublas::vector<float> Zinv(s_box), Sinv_d(s_box), ares_temp(s_box), ares(s_box); for(int i=0; i<s_box; i++) { double acc = 0; for(int j=0; j<s_box; j++) { acc += Sinv(i,j)*d(j); } Sinv_d(i) = acc; } for(int i=0; i<s_box; i++) { double acc = 0; for(int j=0; j<s_box; j++) { acc += S(i,j)*Sinv_d(j); } ares_temp(i) = acc; } for(int i=0; i<s_box; i++) { Zinv(i) = (1/Sinv(i,i)); //Zinv<-1/diag(SRinv) ares(i) = ares_temp(i)-d(i); // ares<-crossprod(S,SRinv.d)-d[sel] } boost::numeric::ublas::vector<float> cvres(s_box); for(int i=0; i<s_box; i++) { cvres(i) = -1*Zinv(i) * Sinv_d(i); } double sig2o = 0; boost::numeric::ublas::vector<float> sig2o_temp(s_box), negAres_temp(s_box); for(int i=0; i<s_box; i++) { negAres_temp(i)=-1*ares(i); sig2o_temp(i) = d(i)*negAres_temp(i); sig2o += sig2o_temp(i); } sig2o = sig2o/s_box; if(sig2o < 0.01) { sig2o = 0.01; } // boost::numeric::ublas::vector<float> pog(s_box); // for(int i=0; i<s_box; i++) { // pog(i) = cvres(i)*ares(i) / sig2o; // } int ccount = 0; for(int i = 0; i < s_box; i++) { int index = neighbour_indices[i]; if(obs_to_check.size() == s && obs_to_check[index] != 1) { checked[curr] = 1; continue; } float dist = distances[i]; if(dist <= inner_radius) { float pog = cvres(i) * ares(i) / sig2o; assert(titanlib::is_valid(pog)); prob_gross_error[index] = std::max(pog, prob_gross_error[index]); if((cvres(i) < 0 && pog > pos[index]) || (cvres(i) >= 0 && pog > neg[index])) { flags[index] = 1; thrown_out++; } checked[index] = 1; ccount++; } } count_oi++; } if(thrown_out == 0) { if(iteration + 1 < num_iterations) { // std::cout << "Stopping early after " << iteration + 1<< " iterations" << std::endl; } break; } // std::cout << "Removing " << thrown_out << " Number of OI " << count_oi << std::endl; double e_time0 = titanlib::clock(); // std::cout << e_time0 - s_time0 << std::endl; } return flags; } // end SCT // //----------------------------------------------------------------------------// // HELPER FUNCTIONS void remove_flagged(ivec& indices, vec& distances, const ivec& flags) { ivec indices_new; vec distances_new; indices_new.reserve(indices.size()); distances_new.reserve(indices.size()); for(int i=0; i<indices.size(); i++) { if(flags[indices[i]] == 0 ) { indices_new.push_back(indices[i]); distances_new.push_back(distances[i]); } } indices = indices_new; distances = distances_new; }
12,665
C++
.cpp
293
31.262799
171
0.498622
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,784
buddy_event_check.cpp
metno_titanlib/src/buddy_event_check.cpp
#include <vector> #include <algorithm> #include <iostream> #define _USE_MATH_DEFINES #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics.hpp> #include <boost/accumulators/statistics/variance.hpp> #include <exception> #include "titanlib.h" using namespace titanlib; ivec titanlib::buddy_event_check(const Points& points, const vec& values, const vec& radius, const ivec& num_min, float event_threshold, float threshold, float max_elev_diff, float elev_gradient, int num_iterations, const ivec& obs_to_check) { bool debug = false; const int s = values.size(); // assert that the arrays we expect are of size s if(values.size() != s) { std::stringstream ss; ss << "Points (" << points.size() << ") and values (" << s << ") are not the same size"; throw std::invalid_argument(ss.str()); } if(radius.size() != s && radius.size() != 1) { std::stringstream ss; ss << "Radius (" << radius.size() << ") and values (" << s << ") are not the same size"; throw std::invalid_argument(ss.str()); } if(num_min.size() != s && num_min.size() != 1) { std::stringstream ss; ss << "'num_min' (" << num_min.size() << ") and values (" << s << ") are not the same size"; throw std::invalid_argument(ss.str()); } if(obs_to_check.size() != s && obs_to_check.size() != 1 && obs_to_check.size() !=0) { std::stringstream ss; ss << "'obs_to_check' (" << obs_to_check.size() << ") and values (" << s << ") are not the same size"; throw std::invalid_argument(ss.str()); } // Check that buddies min is more than 0 for(int i = 0; i < num_min.size(); i++) { if(num_min[i] <= 0) throw std::runtime_error("Buddies_min must be > 0"); } const vec& lats = points.get_lats(); const vec& lons = points.get_lons(); const vec& elevs = points.get_elevs(); // resize the flags and set them to 0 ivec flags(s, 0); for(int i = 0; i < num_min.size(); i++) { if(!titanlib::is_valid(values[i])) flags[i] = 1; } // if obs_to_check is empty then check all bool check_all = obs_to_check.size() != s; int num_removed_last_iteration = 0; for(int it = 0; it < num_iterations; it++) { ivec flags_prev = flags; #pragma omp parallel for for(int i = 0; i < values.size(); i++) { // is this one we are supposed to check? int b_i = (num_min.size() == s) ? i : 0; int d_i = (radius.size() == s) ? i : 0; if(flags_prev[i] != 0) continue; if(check_all || obs_to_check[i] == 1) { if(debug) { std::cout << "point: " << lats[i] << " " << lons[i] << " " << elevs[i]; std::cout << ", and min buddies: " << num_min[b_i]; std::cout << '\n'; } // get all neighbours that are close enough ivec neighbour_indices = points.get_neighbours(lats[i], lons[i], radius[d_i], false); int n_buddies = 0; std::vector<bool> buddy_events; // based on tree do have enough neighbours? if(neighbour_indices.size() >= num_min[b_i]) { // loop over everything that was near enough // count buddies and make list of values (adjusting for height diff if needed) for(int j = 0; j < neighbour_indices.size(); j++) { if(flags_prev[neighbour_indices[j]] != 0) continue; // don't use ones that differ too much in height (max_elev_diff) if(max_elev_diff > 0) { float elev_diff = fabs(elevs[neighbour_indices[j]] - elevs[i]); if(elev_diff <= max_elev_diff) { // correction for the elevation differences (add or subtract -0.0065 degC/m) // m difference from point in question float elev_diff = elevs[i] - elevs[neighbour_indices[j]]; //std::cout << "height diff: " << elev_diff; float adjusted_value = values[neighbour_indices[j]] + (elev_diff * elev_gradient); //std::cout << ", adjusted value: " << adjusted_value; //std::cout << '\n'; bool is_event = adjusted_value < event_threshold; buddy_events.push_back(is_event); n_buddies++; } else { if(debug) { std::cout << "too much height difference: " << elev_diff << '\n'; } } } // if max_elev_diff is negative then don't check elevation difference else { // can use this station int is_event = values[neighbour_indices[j]] < event_threshold; buddy_events.push_back(is_event); n_buddies++; } } } if(debug) { std::cout << "buddies: " << n_buddies << '\n'; } if(n_buddies >= num_min[b_i]) { // compute the average and standard deviation of the values int count_event = 0; for(int k = 0; k < buddy_events.size(); k++) { if(buddy_events[k] == 1) count_event++; } float fraction_event = float(count_event) / buddy_events.size(); bool is_event = values[i] < event_threshold; if(threshold < 1) { if(is_event && fraction_event <= threshold) flags[i] = 1; else if(!is_event && (1 - fraction_event) <= threshold) flags[i] = 1; } else { if(is_event && count_event <= threshold) flags[i] = 1; else if(!is_event && (buddy_events.size() - count_event <= threshold)) flags[i] = 1; } if(debug && flags[i] == 1) { std::cout << "value: " << values[i] << '\n'; std::cout << "is_event: " << is_event << '\n'; std::cout << "event_threshold: " << event_threshold << '\n'; std::cout << "threshold: " << threshold << '\n'; std::cout << "count: " << buddy_events.size() << '\n'; std::cout << "count_event: " << count_event << '\n'; std::cout << "fraction_event: " << fraction_event << '\n'; std::cout << "flag: " << flags[i] << '\n'; std::cout << '\n'; } } } } // Check if we need to stop early int num_removed = 0; for(int i = 0; i < s; i++) { if(flags[i] != 0) num_removed++; } int num_removed_curr_iteration = num_removed - num_removed_last_iteration; if(debug) { std::cout << "iteration, number of bad observations: " << it + 1 << ", " << num_removed_curr_iteration << '\n'; } if(num_removed_curr_iteration == 0) { if(debug) std::cout << "Stopping early after iteration " << it + 1 << std::endl; break; } num_removed_last_iteration = num_removed_curr_iteration; } return flags; }
8,222
C++
.cpp
173
31.601156
123
0.448649
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,785
fgt.cpp
metno_titanlib/src/fgt.cpp
#include <vector> #include <math.h> #include "titanlib.h" #include <assert.h> #include <iostream> #include <numeric> #include <exception> #include <gsl/gsl_multimin.h> #include <gsl/gsl_linalg.h> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/vector_proxy.hpp> #include <boost/numeric/ublas/triangular.hpp> #include <boost/numeric/ublas/lu.hpp> #include <boost/numeric/ublas/io.hpp> #include <boost/numeric/ublas/matrix.hpp> using namespace titanlib; //============================================================================= // FGT within the inner circle bool fgt_core( const vec& lats, const vec& lons, const vec& yo, const vec& yb, const vec& sigma_b, float minp, float maxp, const vec& mina, const vec& maxa, const vec& minv, const vec& maxv, const vec& tpos, const vec& tneg, const ivec& indices_global_test, const ivec& indices_outer_inner, const ivec& indices_outer_test, const ivec& indices_inner_test, bool debug, bool basic, float na, bool set_flag0, int& thrown_out, vec& scores, ivec& flags); //============================================================================= //+ First guess test ivec titanlib::fgt(const Points& points, const vec& values, const ivec& obs_to_check, const vec& background_values, const vec& background_uncertainties, BackgroundType background_elab_type, int num_min_outer, int num_max_outer, float inner_radius, float outer_radius, int num_iterations, int num_min_prof, float min_elev_diff, const vec& values_mina, const vec& values_maxa, const vec& values_minv, const vec& values_maxv, const vec& tpos, const vec& tneg, bool debug, bool basic, vec& scores) { /* -+-+ First guess test +-+- + Description: Flag observations that are (likely) affected by gross measurement errors (GE) based on neighbouring observations. Observations are affected by GEs if their values are (a) [not related to the actual atmospheric state] OR (b) [affected by such large representativeness errors (REs) that they are difficult to reconstruct using the neighbouring observations]. For simplicity, we will refer to observations affected by GE as bad observations, viceversa good observations are those not affected by GEs. FGT is a simplified SCT. + Algorithm: The big task of applying the FGT over the whole observational network is splitted into several smaller tasks. The FGT is applied many times in sequence. Each time, the FGT is applied over a small region centered on an observation location (i.e. the centroid observation). Based on the centroid, we define an inner circle and an outer circle. The outer circle is used to obtain a spatial trend of the observed variable over the region, the so-called background. There are many ways to compute such background values. In addition, the backgreund can be provided as an input vector, together with its uncertainty. The observations to test are those within the inner circle that have not been tested yet. See also the comments of the function "sct_core" for more details. The application of the sequence of FGTs over the whole observational network is repeated several times, until no GEs are found within the observations tested. The core of FGT is to test simultaneously some observations assuming (almost) all the neighbouring observations are good ones. As a consequence, bad observations can influence the results of some tests on neighbouring observations before being rejected. We apply special care to avoid "false positives" (good flagged as bad). For each FGT over a centroid, we flag as bad only the observation showing the worst result. In addition, an extra-loop is done over bad observations where only the good ones are considered. We may "save" bad observations. Analogously, to avoid "false negatives" (bad flagged as good), the last loop is done over the bad observations where only the good ones are considered. We may "save" bad observations during this last loop. (*) Notes on prior information (see also comments in sct_core): the user is expected to provide two different range of values, that inform about the desired tolerance level of the FGT. i. The range of admissible values (values_mina,values_maxa). One range for each observation. The observed value have to be within the corresponding range (e.g. observation=2, then OK if values_mina=0 & values_maxa=4; not OK if values_mina=10 & values_maxa=14). A background outside this range warns us about possible problems with the observation. a. The range of plausible values (value_minp,value_maxp) is derived from the range of admissible values and it is used to check the analyses and backgrounds. Outside this range the values do not make sense. ii. The range of valid values (values_minv,values_maxv). One range for each observation. The observed value must be inside this range. If the backgrounds in a region are all within this range, then we assume the corresponding observations are good ones. Examples: Temperature: 3 observed values(degC)=( 10, 15, 5). (values_mina,values_maxa) = observed values plus/minus 15 degC. (values_minv,values_maxv) = observed values plus/minus 1 degC. Precipitation: 3 observed values(mm)=( 0, 50, 1). (values_mina,values_maxa) = observed values plus/minus either 10 mm or 50% of the value. (values_minv,values_maxv) = observed values plus/minus either 1 mm or 10% of the value. (*) Notes on the data structures (see also comments in set_indices): we have defined a hierarchy of data structures global -> outer -> inner -> test global vectors are the input vectors. The other data structures refer to a specific iteration when a centroid observation has been identified. outer are the vectors of data on the outer circle, not yet flagged as bad. inner are the data on the inner circle, not yet flagged as bad. test data are the observations in the inner circle and still to test. We use the same counter variables for the data structures: g -> global; i,j -> outer; l -> inner; m -> test There are vectors of indices matching the different structures. For example, indices_outer_inner matches the outer and the inner vectors. indices_outer_inner is a vector of the dimension of the number of observations in the inner circle. The instruction i=indices_outer_inner[l] maps the l-th element of inner-type vectors as the i-th element of outer-type vectors. (*) Notes on the thresholds. Different thresholds can be used for different observations. The thresholds vectors have the same dimensions of the observations vectors (global). For each observation, two thresholds (tpos,tneg) have to be set by the user. tpos is the threshold used when the observed value is higher than the cv-analysis, otherwise tneg is used. + Pseudo-code: Loop over the number of iterations prescribed Loop over the p observations (observation index is "curr"). Decide if the observation is suitable for a centroid Define outer/inner cirles, observations to test and set all the vector of indices Check if the observation is isolated Compute the background If the deviations between observations and background is small enough that further steps are not needed and the observations to test are flagged as good ones FGT over the inner circle, either flag the worse observation as bad or flag all of them as good ones NOTE: observations can be flagged as good ones only after the first iteration (after rejecting the worst) Loop over the observations without QC flags (nor good neither bad) and use each of them as a centroid Loop over the bad observations and use each of them as a centroid + Returned values: scores. only for observations rejected by the FGT, z-score (See fgt_core) flags. -999 = not checked; 0 = passed (good); 1 = failed (bad); 11 = isolated (<2 inside inner); 12 = isolated (<num_min_outer inside outer) */ double s_time = titanlib::clock(); const vec& lats = points.get_lats(); const vec& lons = points.get_lons(); const vec& elevs = points.get_elevs(); const int p = values.size(); if( lats.size() != p || lons.size() != p || elevs.size() != p || values.size() != p || tpos.size() != p || tneg.size() != p || values_mina.size() != p || values_maxa.size() != p || values_minv.size() != p || values_maxv.size() != p) throw std::runtime_error("Dimension mismatch"); if(num_min_outer < 2) throw std::invalid_argument("num_min_outer must be > 1"); if(num_max_outer < num_min_outer) throw std::invalid_argument("num_max_outer must be > num_min_outer"); if(num_iterations < 1) throw std::invalid_argument("num_iterations must be >= 1"); if(min_elev_diff <= 0) throw std::invalid_argument("min_elev_diff must be > 0"); if(inner_radius < 0) throw std::invalid_argument("inner_radius must be >= 0"); if(outer_radius < inner_radius) throw std::invalid_argument("outer_radius must be >= inner_radius"); if(background_elab_type == titanlib::VerticalProfile && num_min_prof<0) throw std::invalid_argument("num_min_prof must be >=0"); if(background_elab_type == titanlib::External && background_values.size() != p) throw std::runtime_error("Background vector dimension mismatch"); // initializations float na = -999.; // code for "Not Available". Any type of missing data ivec flags( p, na); ivec obs_test( p, 1); vec sigma_b( p, 1); bool set_all_good = false; scores.clear(); scores.resize( p, na); if (obs_to_check.size() == p) { for(int g=0; g < p; g++) obs_test[g] = obs_to_check[g]; } if (background_uncertainties.size() == p) { for(int g=0; g < p; g++) sigma_b[g] = background_uncertainties[g]; } /* plausible values are inferred from admissible values note: a range check should be performed before doing the FGT. The FGT can mistake obvious large errors for good observations if they happen to be close enough that they support each other */ float value_minp = values_mina[0]; float value_maxp = values_maxa[0]; for(int g=1; g < p; g++) { if ( values_mina[g] < value_minp) value_minp = values_mina[g]; if ( values_maxa[g] > value_maxp) value_maxp = values_maxa[g]; } if(debug) std::cout << "=============================================== " << p << std::endl; if(debug) std::cout << "Number of observations to test is " << p << std::endl; if(debug) std::cout << "Min and max acceptable values are " << value_minp << " " << value_maxp << std::endl; // KDtree has to do with fast computation of distances titanlib::KDTree tree(lats, lons); // if(debug) { std::cout << "g lats lons obs:" << std::endl; for(int g=0; g < p; g++) { std::cout << g << " " << lats[g] << " " << lons[g] << " " << values[g] << std::endl; } } // FGT iterations for(int iteration = 0; iteration < num_iterations; iteration++) { if(debug) std::cout << " +++++ Iteration " << iteration << " ++++++++++++++++" << std::endl; double s_time0 = titanlib::clock(); // reset this number each loop (this is for breaking if we don't throw anything new out) int thrown_out = 0; // diagnostic. count the number of times the test is performed int count_tests = 0; // loop over observations for(int curr=0; curr < p; curr++) { if(debug) std::cout << "===> curr " << curr << " ===============" << std::endl; // -~- Can the observation be used as a centroid for the definition of inner and outer circles? // jump to next if observation not to be checked or already checked if(obs_test[curr] != 1 || flags[curr] >= 0) { if(debug) std::cout << "..observation not suitable as a centroid " << curr << std::endl; continue; } // -~- Define outer/inner circles and which are the observations to test // get all neighbours that are close enough (inside outer circle) vec distances; ivec indices_global_outer_guess = tree.get_neighbours_with_distance(lats[curr], lons[curr], outer_radius, distances, true); if(indices_global_outer_guess.size() > num_max_outer) { int N = indices_global_outer_guess.size(); std::vector<std::pair<float,int> > pairs(N); for(int i = 0; i < indices_global_outer_guess.size(); i++) { pairs[i] = std::pair<float, int>(distances[i], indices_global_outer_guess[i]); } std::sort(pairs.begin(), pairs.end(), titanlib::sort_pair_first<float,int>()); distances.clear(); indices_global_outer_guess.clear(); distances.resize(num_max_outer); indices_global_outer_guess.resize(num_max_outer); for(int i = 0; i < num_max_outer; i++) { distances[i] = pairs[i].first; indices_global_outer_guess[i] = pairs[i].second; } } if(debug) { int p_dist = distances.size(); std::cout << "p_dist " << p_dist << std::endl; } // set all the indices linking the different levels ivec indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test; bool res = titanlib::set_indices(indices_global_outer_guess, obs_test, flags, distances, inner_radius, -1, indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test); int p_outer = indices_global_outer.size(); int p_inner = indices_outer_inner.size(); int p_test = indices_global_test.size(); if(debug) std::cout << "p_outer inner test " << p_outer << " " << p_inner << " " << "" << p_test << std::endl; // -~- Check if there are enough observations in the outer/inner circles if(p_outer < num_min_outer) { flags[curr] = 12; if(debug) std::cout << "@@isolated (outer) " << curr << std::endl; continue; } if( p_inner < 2) { flags[curr] = 11; if(debug) std::cout << "@@isolated (inner) " << curr << std::endl; continue; } // -~- Vectors on the outer circle vec lons_outer = titanlib::subset(lons, indices_global_outer); vec elevs_outer = titanlib::subset(elevs, indices_global_outer); vec lats_outer = titanlib::subset(lats, indices_global_outer); vec sigmab_outer = titanlib::subset(sigma_b, indices_global_outer); vec values_outer = titanlib::subset(values, indices_global_outer); vec tpos_outer = titanlib::subset(tpos, indices_global_outer); vec tneg_outer = titanlib::subset(tneg, indices_global_outer); vec mina_outer = titanlib::subset(values_mina, indices_global_outer); vec minv_outer = titanlib::subset(values_minv, indices_global_outer); vec maxa_outer = titanlib::subset(values_maxa, indices_global_outer); vec maxv_outer = titanlib::subset(values_maxv, indices_global_outer); // Debug for indices if(debug) { ivec flags_outer; flags_outer.resize( p_outer, na); for(int i=0; i < p_outer; i++) { int g = indices_global_outer[i]; flags_outer[i] = flags[g]; } std::cout << "curr lats lons obs:" << std::endl; std::cout << curr << " " << lats[curr] << " " << lons[curr] << " " << values[curr] << std::endl; std::cout << "indices_global_outer - i g lats lons obs:" << std::endl; for(int i=0; i<p_outer; i++) { int g = indices_global_outer[i]; std::cout << std::setprecision(6) << i << " " << g << " " << lats[g] << " " << lons[g] << " " << values[g] << " " << flags[g] << std::endl; } std::cout << "outer - i lats lons obs:" << std::endl; for(int i=0; i<p_outer; i++) { std::cout << std::setprecision(6) << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_outer_inner - l i lats lons obs:" << std::endl; for(int l=0; l<p_inner; l++) { int i = indices_outer_inner[l]; std::cout << std::setprecision(6) << l << " " << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_outer_test - l m lats lons obs:" << std::endl; for(int m=0; m<p_test; m++) { int i = indices_outer_test[m]; std::cout << std::setprecision(6) << m << " " << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_inner_test - l m lats lons obs:" << std::endl; for(int m=0; m<p_test; m++) { int l = indices_inner_test[m]; int i = indices_outer_inner[l]; std::cout << std::setprecision(6) << m << " " << l << " " << lats_outer[i] << " " << lons_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } } // -~- Compute the background vec bvalues_outer = titanlib::background(elevs_outer, values_outer, num_min_prof, min_elev_diff, value_minp, value_maxp, background_elab_type, background_values, indices_global_outer, debug); if(debug) std::cout << "... background ok ..." << std::endl; // -~- If deviations between backgrounds and observations are small then flag = 0 /* if observations and background are almost identical (within the range of valid estimates), then take a shortcut and flag = 0 for all observations in the inner circle */ bool small_innov = true; for(int m=0; m<p_test; m++) { int j = indices_outer_test[m]; if(bvalues_outer[j] < minv_outer[j] || bvalues_outer[j] > maxv_outer[j]) small_innov = false; } if (small_innov) { for(int m=0; m<p_test; m++) { int g = indices_global_test[m]; flags[g] = 0; if (debug) std::cout << " small_innov - index " << g << std::endl; } continue; } // -~- FGT on a selection of observations to test in the inner circle bool set_flag0 = iteration > 0; res = fgt_core( lats_outer, lons_outer, values_outer, bvalues_outer, sigmab_outer, value_minp, value_maxp, mina_outer, maxa_outer, minv_outer, maxv_outer, tpos_outer, tneg_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test, debug, basic, na, set_flag0, thrown_out, scores, flags); // thrown_out is reset every new iteration // problems during the matrix inversion if ( !res) { flags[curr] = 100; if(debug) std::cout << " oi - flags=100 - index " << curr << std::endl; continue; } count_tests++; // one more tests } // end loop over observations std::cout << "FGT loop - Removing " << thrown_out << " observations. Number of tests " << count_tests << std::endl; double e_time0 = titanlib::clock(); std::cout << e_time0 - s_time0 << " secs" << std::endl; if(thrown_out == 0) { if ( iteration == 0) set_all_good = true; if(iteration + 1 < num_iterations) std::cout << "Stopping early after " << iteration + 1<< " iterations" << std::endl; break; } } // end of FGT iterations /* enter if the first iteration has been completed without flagging any bad observation The loop flags all the observations as good ones */ if ( set_all_good) { int count_zero = 0; for(int curr=0; curr < p; curr++) { if ( flags[curr] == na && obs_test[curr] == 1) { flags[curr] = 0; count_zero++; } } if(debug) std::cout << "Remaining " << count_zero << " observations set to \"good\" " << std::endl; } /* check on observations missing QC flags */ if(debug) std::cout << " +++++ check on observations missing QC flags ++++++++++++++++" << std::endl; double s_time0 = titanlib::clock(); // reset this number each loop (this is for breaking if we don't throw anything new out) int thrown_out = 0; // diagnostic. count the number of times the test is performed int count_tests = 0; // loop over observations for(int curr=0; curr < p; curr++) { if(debug) std::cout << "===> curr " << curr << " ===============" << std::endl; // -~- Can the observation be used as a centroid for the definition of inner and outer circles? if(obs_test[curr] != 1 || flags[curr] >= 0) { if(debug) std::cout << "..skip " << curr << std::endl; continue; } // -~- Define outer/inner circles and which are the observations to test // get all neighbours that are close enough (inside outer circle) vec distances; ivec indices_global_outer_guess = tree.get_neighbours_with_distance(lats[curr], lons[curr], outer_radius, distances, true); if(indices_global_outer_guess.size() > num_max_outer) { int N = indices_global_outer_guess.size(); std::vector<std::pair<float,int> > pairs(N); for(int i = 0; i < indices_global_outer_guess.size(); i++) { pairs[i] = std::pair<float, int>(distances[i], indices_global_outer_guess[i]); } std::sort(pairs.begin(), pairs.end(), titanlib::sort_pair_first<float,int>()); distances.clear(); indices_global_outer_guess.clear(); distances.resize(num_max_outer); indices_global_outer_guess.resize(num_max_outer); for(int i = 0; i < num_max_outer; i++) { distances[i] = pairs[i].first; indices_global_outer_guess[i] = pairs[i].second; } } // set all the indices linking the different levels // note that the only observation to test is curr ivec indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test; bool res = titanlib::set_indices( indices_global_outer_guess, obs_test, flags, distances, inner_radius, curr, indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test); int p_outer = indices_global_outer.size(); int p_inner = indices_outer_inner.size(); int p_test = indices_global_test.size(); if(debug) std::cout << "p_outer inner test " << p_outer << " " << p_inner << " " << p_test << std::endl; // -~- Check if there are enough observations in the outer/inner circles if(p_outer < num_min_outer) { flags[curr] = 12; if(debug) std::cout << "@@isolated (outer) " << curr << std::endl; continue; } if( p_inner < 2) { flags[curr] = 11; if(debug) std::cout << "@@isolated (inner) " << curr << std::endl; continue; } // -~- Vectors on the outer circle vec lons_outer = titanlib::subset(lons, indices_global_outer); vec elevs_outer = titanlib::subset(elevs, indices_global_outer); vec lats_outer = titanlib::subset(lats, indices_global_outer); vec sigmab_outer = titanlib::subset(sigma_b, indices_global_outer); vec values_outer = titanlib::subset(values, indices_global_outer); vec tpos_outer = titanlib::subset(tpos, indices_global_outer); vec tneg_outer = titanlib::subset(tneg, indices_global_outer); vec mina_outer = titanlib::subset(values_mina, indices_global_outer); vec minv_outer = titanlib::subset(values_minv, indices_global_outer); vec maxa_outer = titanlib::subset(values_maxa, indices_global_outer); vec maxv_outer = titanlib::subset(values_maxv, indices_global_outer); // -~- Compute the background vec bvalues_outer = titanlib::background(elevs_outer, values_outer, num_min_prof, min_elev_diff, value_minp, value_maxp, background_elab_type, background_values, indices_global_outer, debug); if(debug) std::cout << "... background ok ..." << std::endl; // -~- If deviations between backgrounds and observations are small then flag = 0 /* if observations and background are almost identical (within the range of valid estimates), then take a shortcut and flag = 0 for all observations in the inner circle */ int j = indices_outer_test[0]; if(bvalues_outer[j] > minv_outer[j] && bvalues_outer[j] < maxv_outer[j]) { int g = indices_global_test[0]; flags[g] = 0; if (debug) std::cout << " small_innov - index " << g << std::endl; continue; } // -~- FGT on a selection of observations to test in the inner circle res = fgt_core( lats_outer, lons_outer, values_outer, bvalues_outer, sigmab_outer, value_minp, value_maxp, mina_outer, maxa_outer, minv_outer, maxv_outer, tpos_outer, tneg_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test, debug, basic, na, true, thrown_out, scores, flags); // problems during the matrix inversion if ( !res) { flags[curr] = 100; if(debug) std::cout << " oi - flags=100 - index " << curr << std::endl; continue; } count_tests++; // one more tests } // end loop over observations std::cout << "QC missing - Removing " << thrown_out << " observations. Number of tests " << count_tests << std::endl; double e_time0 = titanlib::clock(); std::cout << e_time0 - s_time0 << " secs" << std::endl; /* final check on the bad observations it may happen that a good observation is flagged as a bad one because of the order the FGT has been done and the uncertainty made in the estimation of the background (remember that bad observations may have been used to get the background). This final check is made only on bad observations and uses only good observations. */ if(debug) std::cout << " +++++ final check on the bad observations ++++++++++++++++" << std::endl; s_time0 = titanlib::clock(); // reset this number each loop (this is for breaking if we don't throw anything new out) thrown_out = 0; // diagnostic. count the number of times the test is performed count_tests = 0; // loop over observations for(int curr=0; curr < p; curr++) { if(debug) std::cout << "===> curr " << curr << " ===============" << std::endl; // -~- Can the observation be used as a centroid for the definition of inner and outer circles? if(obs_test[curr] != 1 || flags[curr] != 1 || values[curr] < value_minp || values[curr] > value_maxp) { if(debug) std::cout << "..skip " << curr << std::endl; continue; } // -~- Define outer/inner circles and which are the observations to test // get all neighbours that are close enough (inside outer circle) vec distances; ivec indices_global_outer_guess = tree.get_neighbours_with_distance(lats[curr], lons[curr], outer_radius, distances, true); if(indices_global_outer_guess.size() > num_max_outer) { int N = indices_global_outer_guess.size(); std::vector<std::pair<float,int> > pairs(N); for(int i = 0; i < indices_global_outer_guess.size(); i++) { pairs[i] = std::pair<float, int>(distances[i], indices_global_outer_guess[i]); } std::sort(pairs.begin(), pairs.end(), titanlib::sort_pair_first<float,int>()); distances.clear(); indices_global_outer_guess.clear(); distances.resize(num_max_outer); indices_global_outer_guess.resize(num_max_outer); for(int i = 0; i < num_max_outer; i++) { distances[i] = pairs[i].first; indices_global_outer_guess[i] = pairs[i].second; } } // set all the indices linking the different levels ivec indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test; bool res = titanlib::set_indices(indices_global_outer_guess, obs_test, flags, distances, inner_radius, curr, indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test); int p_outer = indices_global_outer.size(); int p_inner = indices_outer_inner.size(); int p_test = indices_global_test.size(); if(debug) std::cout << "p_outer inner test " << p_outer << " " << p_inner << " " << p_test << std::endl; // -~- Decide if there are enough observations in the outer/inner circles if(p_outer < num_min_outer) { flags[curr] = 12; if(debug) std::cout << "@@isolated (outer) " << curr << std::endl; continue; } if( p_inner < 2) { flags[curr] = 11; if(debug) std::cout << "@@isolated (inner) " << curr << std::endl; continue; } // -~- Set vectors on the outer circle vec lons_outer = titanlib::subset(lons, indices_global_outer); vec elevs_outer = titanlib::subset(elevs, indices_global_outer); vec lats_outer = titanlib::subset(lats, indices_global_outer); vec sigmab_outer = titanlib::subset(sigma_b, indices_global_outer); vec values_outer = titanlib::subset(values, indices_global_outer); vec tpos_outer = titanlib::subset(tpos, indices_global_outer); vec tneg_outer = titanlib::subset(tneg, indices_global_outer); vec mina_outer = titanlib::subset(values_mina, indices_global_outer); vec minv_outer = titanlib::subset(values_minv, indices_global_outer); vec maxa_outer = titanlib::subset(values_maxa, indices_global_outer); vec maxv_outer = titanlib::subset(values_maxv, indices_global_outer); // Debug for indices if(debug) { ivec flags_outer; flags_outer.resize( p_outer, na); for(int i=0; i < p_outer; i++) { int g = indices_global_outer[i]; flags_outer[i] = flags[g]; } std::cout << "curr lats lons obs:" << std::endl; std::cout << curr << " " << lats[curr] << " " << lons[curr] << " " << values[curr] << std::endl; std::cout << "indices_global_outer - i g lats lons obs:" << std::endl; for(int i=0; i<p_outer; i++) { int g = indices_global_outer[i]; std::cout << std::setprecision(6) << i << " " << g << " " << lats[g] << " " << lons[g] << " " << values[g] << " " << flags[g] << std::endl; } std::cout << "outer - i lats lons obs:" << std::endl; for(int i=0; i<p_outer; i++) { std::cout << std::setprecision(6) << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_outer_inner - l i lats lons obs:" << std::endl; for(int l=0; l<p_inner; l++) { int i = indices_outer_inner[l]; std::cout << std::setprecision(6) << l << " " << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_outer_test - l m lats lons obs:" << std::endl; for(int m=0; m<p_test; m++) { int i = indices_outer_test[m]; std::cout << std::setprecision(6) << m << " " << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_inner_test - l m lats lons obs:" << std::endl; for(int m=0; m<p_test; m++) { int l = indices_inner_test[m]; int i = indices_outer_inner[l]; std::cout << std::setprecision(6) << m << " " << l << " " << lats_outer[i] << " " << lons_outer[i] << " " << values_outer[i] << " " << flags_outer[i] << std::endl; } } // -~- Compute the background vec bvalues_outer = titanlib::background(elevs_outer, values_outer, num_min_prof, min_elev_diff, value_minp, value_maxp, background_elab_type, background_values, indices_global_outer, debug); if(debug) { int j = indices_outer_test[0]; for(int i=0; i < p_outer; i++) { std::cout << std::setprecision(6) << "values backg minv maxv " << values_outer[i] << " " << bvalues_outer[i] << " " << minv_outer[i] << " " << maxv_outer[i] << " " << std::endl; } std::cout << "j " << j << std::endl; } if(debug) std::cout << "... background ok ..." << std::endl; // -~- If deviations between backgrounds and observations are small then flag = 0 /* if observations and background are almost identical (within the range of valid estimates), then take a shortcut and flag = 0 for all observations in the inner circle */ int j = indices_outer_test[0]; if(bvalues_outer[j] > minv_outer[j] && bvalues_outer[j] < maxv_outer[j]) { int g = indices_global_test[0]; flags[g] = 0; if (debug) std::cout << " small_innov - index " << g << std::endl; continue; } // -~- FGT within the inner circle // note that the only observation to test is curr res = fgt_core( lats_outer, lons_outer, values_outer, bvalues_outer, sigmab_outer, value_minp, value_maxp, mina_outer, maxa_outer, minv_outer, maxv_outer, tpos_outer, tneg_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test, debug, basic, na, true, thrown_out, scores, flags); // problems during the matrix inversion if ( !res) { flags[curr] = 100; if(debug) std::cout << " oi - flags=100 - index " << curr << std::endl; continue; } count_tests++; // one more tests } // end loop over observations std::cout << "Re-check bad obs - Removing " << thrown_out << " observations. Number of tests" << count_tests << std::endl; e_time0 = titanlib::clock(); std::cout << e_time0 - s_time0 << " secs" << std::endl; // if(debug) { int count_bad = 0; int count_good = 0; int count_missing = 0; int count_iso_inner = 0; int count_iso_outer = 0; int count_fail_matinv = 0; int count_impossible = 0; // loop over observations for(int curr=0; curr < p; curr++) { if( flags[curr] == 1) { count_bad++; } else if( flags[curr] == 0) { count_good++; } else if ( flags[curr] == na) { count_missing++; } else if( flags[curr] == 11) { count_iso_inner++; } else if( flags[curr] == 12) { count_iso_outer++; } else if( flags[curr] == 100) { count_fail_matinv++; } else { count_impossible++; } } std::cout << std::setprecision(3) << "summary - # TOT good bad missing isolated(inner) isolated(outer): " << p << " " << count_good << " " << count_bad << " " << count_missing << " " << count_iso_inner << " " << count_iso_outer << std::endl; if(count_fail_matinv > 0) std::cout << std::setprecision(3) << "!!!! failure in matrix inversion: " << count_fail_matinv << std::endl; if(count_impossible > 0) std::cout << std::setprecision(3) << "!!!! unknown flag: " << count_impossible << std::endl; } // std::cout << ">> Total Time " << e_time0 - s_time << "secs" << std::endl; // return flags; } // end FGT // //============================================================================= //----------------------------------------------------------------------------// // FGT WITHIN THE INNER CIRCLE // Smallets unit for the first-guess test bool fgt_core( const vec& lats, const vec& lons, const vec& yo, const vec& yb, const vec& sigma_b, float minp, float maxp, const vec& mina, const vec& maxa, const vec& minv, const vec& maxv, const vec& tpos, const vec& tneg, const ivec& indices_global_test, const ivec& indices_outer_inner, const ivec& indices_outer_test, const ivec& indices_inner_test, bool debug, bool basic, float na, bool set_flag0, int& thrown_out, vec& scores, ivec& flags) { /*----------------------------------------------------------------------------- First guess test for a selection of observations within the inner circle. The inner circle is defined with respect to a centroid observation. Each observation to test is compared against an estimated value (first guess) obtained considering the neighbouring observations. FGT scores: chi = abs( observation - background) / uncertainty of the background The background uncertainty is optional, when not provided it is set to 1. basic mode: z = chi advanced (non basic) mode: z = (chi - mu) / (sigma + sigma_mu) mu = median( chi(*)) sigma = inter-quartile range of chi(*) sigma_mu = sigma / sqrt(n(*)) (*) statistics based on the n observations that are within the inner circle and with a background within the range of admissible values. FGT fails when: z > tpos, yo >= yb z > tneg, yo < yb Our prior knowledge includes the definition of two confidence levels for the background: - valid values, range [minv,maxv] background is so close that it validates the observation - admissible values, range [mina,maxa] if background is outside this range, then the observation is bad Note that the statistics defining the spread used in the FGT is based on deviations between observations and estimates that lie within the range of admissible values only. Decision tree: ALL observations are set to bad when: the backgrounds all lie outside the range of admissible values ONE observation is deemed as bad when: fails the FGT with the largest z-score AND background is outside the range of valid values ALL observations are set to good when: the user allows the procedure to flag them as good ones (set_flag0 is true) AND the backgrounds all lie within the range of valid values OR none of the observations fail the FGT test Output values: flags, global vector. return updated quality control flag values (1 = bad, 0 = good) scores, global vector. return updated scores. Note that only for the case of a single bad observation we store the z-score thrown_out, integer. update the number of observations flagged as bad ones -----------------------------------------------------------------------------*/ using namespace boost::numeric::ublas; // init // int p_outer = yo.size(); int p_inner = indices_outer_inner.size(); int p_test = indices_global_test.size(); // obtain chi = sqrt( analysis_residual * cvanalysis_residual) // two chi vectors are obtained: // 1. chi_inner, chi for all observations in the inner circle // 2. chi_stat, chi values used to extract summary stastics // observations in the inner circle AND yav has an admissible value vec chi_stat; vec chi_stat_alt; chi_stat.reserve(p_inner); chi_stat_alt.reserve(p_inner); boost::numeric::ublas::vector<float> chi_inner(p_inner); boost::numeric::ublas::vector<float> chi_inner_alt(p_inner); if(debug) std::cout << "collect statistics - i l lon lat yo yb sigma_b chi chi_alt" << std::endl; for(int l=0; l<p_inner; l++) { int i = indices_outer_inner[l]; chi_inner(l) = fabs( yo[i] - yb[i]) / sigma_b[i]; chi_inner_alt(l) = maxv[i] - minv[i]; if ( yb[i] >= mina[i] && yb[i] <= maxa[i]) { chi_stat.push_back(chi_inner(l)); chi_stat_alt.push_back(chi_inner_alt(l)); } if(debug) std::cout << std::setprecision(6) << i << " " << l << " " << lons[i] << " " << lats[i] << " " << yo[i] << " " << yb[i] << " " << sigma_b[i] << " " << chi_inner(l) << " " << chi_inner_alt(l) << std::endl; } // chi_stat is empty (yav all outside the range of admissible values), set all flags to 1 if(chi_stat.size() == 0) { for(int m=0; m<p_test; m++) { int g = indices_global_test[m]; flags[g] = 1; thrown_out++; if(debug) std::cout << std::setprecision(3) << "chi_stat empty - flag as bad " << g << std::endl; } return true; } // chi summary statistics float mu=0., sigma=0., sigma_mu=0.; if (!basic) { mu = titanlib::compute_quantile( 0.5, chi_stat); sigma = titanlib::compute_quantile( 0.75, chi_stat) - titanlib::compute_quantile( 0.25, chi_stat); float sigma_alt = titanlib::compute_quantile( 0.75, chi_stat_alt) - titanlib::compute_quantile( 0.25, chi_stat_alt); if (sigma_alt > sigma) sigma = sigma_alt; if(sigma == 0) { if(debug) std::cout << "sigma = 0, not possible to perform the spatial check " << std::endl; return true; } sigma_mu = sigma / std::sqrt( chi_stat.size()); if(debug) { std::cout << " chi_stat, dim = " << chi_stat.size() << std::endl; for(int l=0; l<chi_stat.size(); l++) std::cout << std::setprecision(6) << chi_stat[l] << std::endl; std::cout << std::setprecision(6) << " mu sigma sigma_mu " << mu << " " << sigma << " " << sigma_mu << std::endl; } } // z = ( chi - mu ) / ( sigma + sigma_mu ) float zmx = -10000; int mmx = -1; if(debug) std::cout << "z_test - i l lons lats yo yb chi z " << std::endl; for(int m=0; m<p_test; m++) { int i = indices_outer_test[m]; int l = indices_inner_test[m]; float z; if (basic) { z = chi_inner(l); } else { z = (chi_inner(l) - mu) / (sigma + sigma_mu); } if (z > zmx && (yb[i] < minv[i] || yb[i] > maxv[i])) { zmx = z; mmx = m; } if(debug) std::cout << std::setprecision(6) << i << " " << l << " " << lons[i] << " " << lats[i] << " " << yo[i] << " " << yb[i] << " " << chi_inner(l) << " " << z << std::endl; } // Decision making float thr = 0; int i = 0; int l = 0; if ( mmx >= 0) { i = indices_outer_test[mmx]; l = indices_inner_test[mmx]; // set the threshold thr = tneg[i]; if ( (yo[i] - yb[i]) >= 0) thr = tpos[i]; } // if the largest z is larger than the threshold, then flag IT as bad ... if ( zmx > thr) { int g = indices_global_test[mmx]; scores[g] = zmx; flags[g] = 1; thrown_out++; if(debug) std::cout << std::setprecision(6) << "FGT failed - flag as bad - index yo yb chi z " << g << " " << yo[i] << " " << yb[i] << " " << chi_inner(l) << " " << zmx << std::endl; // ... BUT if the largest z is smaller than the threshold (and we are confindet in flagging), then flag ALL as good } else if (set_flag0) { for(int m=0; m<p_test; m++) { int g = indices_global_test[m]; flags[g] = 0; if(debug) std::cout << "all set to good - g " << g << std::endl; } } // normal exit return true; }
45,705
C++
.cpp
767
49.112125
448
0.582029
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,786
lag_reduction_filter.cpp
metno_titanlib/src/lag_reduction_filter.cpp
#include "titanlib.h" using namespace titanlib; vec titanlib::lag_reduction_filter(const vec& times, const vec& values, float a, float b, float k1, float k2, int n) { vec result(times.size()); result[0] = values[0]; for(int i = 1; i < times.size(); i++) { float curr = result[i - 1]; float f0 = values[i - 1]; float f1 = values[i]; float prev = curr; float time_diff = times[i] - times[i - 1]; float deriv1 = (f1 - f0) / time_diff; float deriv2 = 0; // # (f1 - f0) - (f0 - fm1); float dt = 1.0 / n; for(int ti = 0; ti < n; ti++) { float t = (ti + 1) * dt; float fi = f0 + t * (f1 - f0); float F0 = 1.0 / (a*k1 + b*k2) * (deriv2 + (k1 + k2) * deriv1 + k1 * k2 * (fi - curr)); fi = f0 + (t+dt) * (f1 - f0); float F1 = 1.0 / (a*k1 + b*k2) * (deriv2 + (k1 + k2) * deriv1 + k1 * k2 * (fi - curr)); curr = prev + dt / 2 * (F0 + F1); prev = curr; } result[i] = curr; } return result; }
1,074
C++
.cpp
27
31.555556
118
0.471264
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,787
dataset.cpp
metno_titanlib/src/dataset.cpp
#include <iostream> #include <vector> #include "titanlib.h" using namespace titanlib; titanlib::Dataset::Dataset(Points points, vec ivalues) { if(points.size() != ivalues.size()) { std::stringstream ss; ss << "Points (" << points.size() << ") have a different size than values (" << ivalues.size() <<")"; throw std::invalid_argument(ss.str()); } this->points = points; values = ivalues; flags.resize(points.size(), 0); } // NOTE: There are two ways to deal with 'indicies', which depends on the kind of quality control // function: // Scenario 1: The test for a specific station does not depend on other stations. In this case, we // only want to run the test on stations in indices and that are not already flagged. // Run subset_valid on all arrays and then use merge_simple to merge flags // Scenario 2: The test for a specific station does depend on other stations. In this case, we // want to run the test on all non-flagged stations (even those not in indices) and then // only merge in those specified by indices. Run get_flagged* functions on all arrays, // and use the merge function to merge flags. void titanlib::Dataset::range_check(const vec& min, const vec& max, const ivec& indices) { vec v1 = subset_valid(values, indices); vec v2 = subset_valid(min, indices); vec v3 = subset_valid(max, indices); ivec new_flags = titanlib::range_check(v1, v2, v3); merge_simple(new_flags, subset_valid(indices)); } void titanlib::Dataset::range_check_climatology(int unixtime, const vec& pos, const vec& neg, const ivec& indices) { ivec new_flags = titanlib::range_check_climatology(subset_valid(points, indices), subset_valid(values, indices), unixtime, pos, neg); merge_simple(new_flags, subset_valid(indices)); } void titanlib::Dataset::sct(int num_min, int num_max, float inner_radius, float outer_radius, int num_iterations, int num_min_prof, float min_elev_diff, float min_horizontal_scale, float vertical_scale, const vec& t2pos, const vec& t2neg, const vec& eps2, vec& prob_gross_error, vec& rep, const ivec& indices) { // Only keep flags that are not flagged ivec new_flags = titanlib::sct(get_unflagged_points(), get_unflagged(values), num_min, num_max, inner_radius, outer_radius, num_iterations, num_min_prof, min_elev_diff, min_horizontal_scale , vertical_scale, get_unflagged(t2pos), get_unflagged(t2neg), get_unflagged(eps2), prob_gross_error, rep); merge(new_flags, indices); } void titanlib::Dataset::sct_dual(const vec& event_thresholds, ConditionType condition, int num_min, int num_max, float inner_radius, float outer_radius, int num_iterations, float min_horizontal_scale, float max_horizontal_scale, int kth_closest_obs_horizontal_scale, float vertical_scale, const vec& test_thresholds, bool debug, const ivec& obs_to_check, const ivec& indices){ // Only keep flags that are not flagged ivec new_flags = titanlib::sct_dual(get_unflagged_points(), get_unflagged(values), get_unflagged(obs_to_check), get_unflagged(event_thresholds), condition, num_min, num_max, inner_radius, outer_radius, num_iterations, min_horizontal_scale, max_horizontal_scale, kth_closest_obs_horizontal_scale, vertical_scale, get_unflagged(test_thresholds), debug); merge(new_flags, indices); } void titanlib::Dataset::buddy_check(const vec& radius, const ivec& num_min, float threshold, float max_elev_diff, float elev_gradient, float min_std, int num_iterations, const ivec& obs_to_check, const ivec& indices) { ivec new_flags = titanlib::buddy_check(get_unflagged_points(), get_unflagged(values), get_unflagged(radius), get_unflagged(num_min), threshold, max_elev_diff, elev_gradient, min_std, num_iterations, get_unflagged(obs_to_check)); merge(new_flags, indices); } void titanlib::Dataset::buddy_event_check(const vec& radius, const ivec& num_min, float event_threshold, float threshold, float max_elev_diff, float elev_gradient, int num_iterations, const ivec& obs_to_check, const ivec& indices) { ivec new_flags = titanlib::buddy_event_check(get_unflagged_points(), get_unflagged(values), get_unflagged(radius), get_unflagged(num_min), event_threshold, threshold, max_elev_diff, elev_gradient, num_iterations, get_unflagged(obs_to_check)); merge(new_flags, indices); } void titanlib::Dataset::isolation_check(int num_min, float radius, float vertical_radius, const ivec& indices) { ivec new_flags = titanlib::isolation_check(get_unflagged_points(), num_min, radius, vertical_radius); merge(new_flags, indices); } void titanlib::Dataset::isolation_check(const ivec& num_min, const vec& radius, const vec& vertical_radius, const ivec& indices) { ivec new_flags = titanlib::isolation_check(get_unflagged_points(), get_unflagged(num_min), get_unflagged(radius), get_unflagged(vertical_radius)); merge(new_flags, indices); } void titanlib::Dataset::duplicate_check(float radius, float vertical_range, const ivec& indices) { ivec new_flags = titanlib::duplicate_check(get_unflagged_points(), radius, vertical_range); merge(new_flags, indices); } void titanlib::Dataset::dem_check(const vec& dem, float max_elev_diff) { const vec& elevs = points.get_elevs(); for(int i = 0; i < points.size(); i++) { float elev_diff = fabs(elevs[i] - dem[i]); if(elev_diff > max_elev_diff) { flags[i] = 1; } } } void titanlib::Dataset::external_check(const ivec& flags) { if(flags.size() != this->flags.size()) throw std::invalid_argument("External flags different size than dataset flags"); for(int i = 0; i < this->flags.size(); i++) { if(flags[i] > 0) { this->flags[i] = 1; } } } void titanlib::Dataset::metadata_check(bool check_lat, bool check_lon, bool check_elev, bool check_laf, const ivec& indices) { ivec new_flags = titanlib::metadata_check(get_unflagged_points(), check_lat, check_lon, check_elev, check_laf); merge_simple(new_flags, subset_valid(indices)); } void titanlib::Dataset::merge(const ivec& new_flags, ivec indices) { if(indices.size() == 1 && indices[0] == -1) { indices.clear(); indices.resize(flags.size()); for(int i = 0; i < flags.size(); i++) indices[i] = i; } ivec flag_indices = get_unflagged_indices(); // These are the indices corresponding to each flag ivec indices0; // These are indices we want to update flags for indices0.reserve(indices.size()); for(int i = 0; i < indices.size(); i++) { if(flags[indices[i]] == 0) indices0.push_back(indices[i]); } assert(new_flags.size() >= indices0.size()); for(int i = 0; i < indices0.size(); i++) { int index = indices0[i]; if(index >= flags.size() || index < 0) throw std::runtime_error("One or more indices are invalid"); for(int j = 0; j < flag_indices.size(); j++) { if(flag_indices[j] == index) flags[index] = new_flags[j]; } } } void titanlib::Dataset::merge_simple(const ivec& new_flags, ivec indices) { if(indices.size() == 1 && indices[0] == -1) { flags = new_flags; return; } assert(new_flags.size() == indices.size()); for(int i = 0; i < indices.size(); i++) { int index = indices[i]; if(index >= flags.size() || index < 0) throw std::runtime_error("One or more indices are invalid"); flags[index] = new_flags[i]; } } ivec titanlib::Dataset::subset_valid(const ivec& indices) { if(indices.size() == 0) return ivec(); ivec indices0 = indices; if(indices.size() == 1 && indices[0] == -1) { indices0.clear(); indices0.resize(flags.size()); for(int i = 0; i < flags.size(); i++) indices0[i] = i; } ivec output_indices; output_indices.reserve(indices0.size()); for(int i = 0; i < indices0.size(); i++) { int index = indices0[i]; if(flags[index] == 0) { output_indices.push_back(index); } } return output_indices; } ivec titanlib::Dataset::get_unflagged_indices() { ivec indices; indices.reserve(flags.size()); for(int i = 0; i < flags.size(); i++) { if(flags[i] == 0) { indices.push_back(i); } } return indices; } Points titanlib::Dataset::get_unflagged_points() { ivec indices = get_unflagged_indices(); vec ilats = points.get_lats(); vec ilons = points.get_lons(); vec ielevs = points.get_elevs(); vec ilafs = points.get_lafs(); vec lats(indices.size()); vec lons(indices.size()); vec elevs(indices.size()); vec lafs(indices.size()); for(int i = 0; i < indices.size(); i++) { int index = indices[i]; assert(index < ilats.size()); assert(index < ilons.size()); assert(index < ielevs.size()); assert(index < ilafs.size()); lats[i] = ilats[index]; lons[i] = ilons[index]; elevs[i] = ielevs[index]; lafs[i] = ilafs[index]; } return Points(lats, lons, elevs, lafs); } Points titanlib::Dataset::subset_valid(const Points& input, const ivec& indices) { if(indices.size() == 0) return Points(vec(), vec(), vec(), vec()); ivec indices0 = indices; if(indices.size() == 1 && indices[0] == -1) { indices0.clear(); indices0.resize(flags.size()); for(int i = 0; i < flags.size(); i++) indices0[i] = i; } int size = indices0.size(); vec ilats = input.get_lats(); vec ilons = input.get_lons(); vec ielevs = input.get_elevs(); vec ilafs = input.get_lafs(); vec lats; vec lons; vec elevs; vec lafs; lats.reserve(size); lons.reserve(size); elevs.reserve(size); lafs.reserve(size); for(int i=0; i < size; i++) { int index = indices0[i]; assert(index < flags.size()); if(flags[index] == 0) { lats.push_back(ilats[index]); lons.push_back(ilons[index]); elevs.push_back(ielevs[index]); lafs.push_back(ilafs[index]); } } return Points(lats, lons, elevs, lafs); } vec titanlib::Dataset::get_values() const { return values; } ivec titanlib::Dataset::get_flags() const { return flags; } Points titanlib::Dataset::get_points() const { return points; } void titanlib::Dataset::set_values(vec ivalues) { values = ivalues; } void titanlib::Dataset::set_flags(ivec ivalues) { flags = ivalues; } void titanlib::Dataset::set_points(Points ipoints) { points = ipoints; }
11,329
C++
.cpp
254
37.043307
300
0.619198
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,788
metadata_check.cpp
metno_titanlib/src/metadata_check.cpp
#include "titanlib.h" using namespace titanlib; ivec titanlib::metadata_check(const Points& points, bool check_lat, bool check_lon, bool check_elev, bool check_laf) { const int s = points.size(); const vec& lats = points.get_lats(); const vec& lons = points.get_lons(); const vec& elevs = points.get_elevs(); const vec& lafs = points.get_lafs(); ivec flags(s, 0); #pragma omp parallel for for(int i = 0; i < s; i++) { if(check_lat && !titanlib::is_valid(lats[i])) flags[i] = 1; if(check_lon && !titanlib::is_valid(lons[i])) flags[i] = 1; if(check_elev && !titanlib::is_valid(elevs[i])) flags[i] = 1; if(check_laf && !titanlib::is_valid(lafs[i])) flags[i] = 1; } return flags; }
802
C++
.cpp
22
29.818182
118
0.583763
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,789
points.cpp
metno_titanlib/src/points.cpp
#include "titanlib.h" using namespace titanlib; titanlib::Points::Points() { // TODO: Deal with the empty case. Can't really find nearest neighbours then } titanlib::Points::Points(vec lats, vec lons, vec elevs, vec lafs, CoordinateType type) { int N = lats.size(); if(lons.size() != N) throw std::invalid_argument("Cannot create points with unequal lat and lon sizes"); if(elevs.size() != 0 && elevs.size() != N) throw std::invalid_argument("'elevs' must either be size 0 or the same size at lats/lons"); if(lafs.size() != 0 && lafs.size() != N) throw std::invalid_argument("'lafs' must either be size 0 or the same size at lats/lons"); mLats = lats; mLons = lons; mElevs = elevs; mLafs = lafs; KDTree tree = KDTree(lats, lons, type); mTree = tree; if(mElevs.size() != N) { mElevs.clear(); mElevs.resize(N, titanlib::MV); } if(mLafs.size() != N) { mLafs.clear(); mLafs.resize(N, titanlib::MV); } } titanlib::Points::Points(KDTree tree, vec elevs, vec lafs) { mElevs = elevs; mLafs = lafs; mTree = tree; mLats = tree.get_lats(); mLons = tree.get_lons(); } int titanlib::Points::get_num_neighbours(float lat, float lon, float radius, bool include_match) const { return mTree.get_num_neighbours(lat, lon, radius, include_match); } ivec titanlib::Points::get_neighbours_with_distance(float lat, float lon, float radius, vec& distances, bool include_match) const { return mTree.get_neighbours_with_distance(lat, lon, radius, distances, include_match); } ivec titanlib::Points::get_neighbours(float lat, float lon, float radius, bool include_match) const { return mTree.get_neighbours(lat, lon, radius, include_match); } ivec titanlib::Points::get_closest_neighbours(float lat, float lon, int num, bool include_match) const { return mTree.get_closest_neighbours(lat, lon, num, include_match); } int titanlib::Points::get_nearest_neighbour(float lat, float lon, bool include_match) const { ivec I = get_closest_neighbours(lat, lon, 1, include_match); if(I.size() > 0) return I[0]; else return -1; } vec titanlib::Points::get_lats() const { return mLats; } vec titanlib::Points::get_lons() const { return mLons; } vec titanlib::Points::get_elevs() const { return mElevs; } vec titanlib::Points::get_lafs() const { return mLafs; } int titanlib::Points::size() const { return mLats.size(); } titanlib::Points& titanlib::Points::operator=(titanlib::Points other) { std::swap(mLats, other.mLats); std::swap(mLons, other.mLons); std::swap(mElevs, other.mElevs); std::swap(mLafs, other.mLafs); std::swap(mTree, other.mTree); return *this; } titanlib::Points::Points(const titanlib::Points& other) { mLats = other.mLats; mLons = other.mLons; mElevs = other.mElevs; mLafs = other.mLafs; mTree = KDTree(mLats, mLons, mTree.get_coordinate_type()); } CoordinateType titanlib::Points::get_coordinate_type() const { return mTree.get_coordinate_type(); }
3,089
C++
.cpp
87
31.574713
131
0.680134
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,790
sct_dual.cpp
metno_titanlib/src/sct_dual.cpp
#include <vector> #include <math.h> #include "titanlib.h" #include <assert.h> #include <iostream> #include <numeric> #include <exception> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/vector_proxy.hpp> #include <boost/numeric/ublas/triangular.hpp> #include <boost/numeric/ublas/lu.hpp> #include <boost/numeric/ublas/io.hpp> #include <boost/numeric/ublas/matrix.hpp> using namespace titanlib; // SCT_dual within the inner circle bool sct_dual_core( const vec& lats, const vec& lons, const vec& elevs, const vec& w, const vec& t, float Dh_min, float Dh_max, int kth_close, float Dz, const vec& eps2, const ivec& indices_global_test, const ivec& indices_outer_inner, const ivec& indices_outer_test, const ivec& indices_inner_test, bool debug, float na, bool set_flag0, int& thrown_out, ivec& flags); //============================================================================= //+ SCT_dual - Spatial Consistency Test for dichotomous (yes/no) variables ivec titanlib::sct_dual( const Points& points, const vec& values, const ivec& obs_to_check, const vec& event_thresholds, ConditionType condition, int num_min_outer, int num_max_outer, float inner_radius, float outer_radius, int num_iterations, float min_horizontal_scale, float max_horizontal_scale, int kth_closest_obs_horizontal_scale, float vertical_scale, const vec& test_thresholds, bool debug) { /* -+-+ Spatial Consistency Test for dichotomous (yes/no) variables +-+- + Description: Flag observations that are (likely) affected by gross measurement errors (GE) based on neighbouring observations. The observations are transformed into dichotomous predictions of the type, "yes, an event happened", or "no, an event did not happen". The term "dual" is related to the fact that observations are divided into two classes. Observations are affected by GEs if their values are (a) [not related to the actual atmospheric state] OR (b) [affected by such large representativeness errors (REs) that they are difficult to reconstruct using the neighbouring observations]. For simplicity, we will refer to observations affected by GE as bad observations, viceversa good observations are those not affected by GEs. + Reference for some concepts, such as SCT and Integral Data Influence (IDI): Lussana, C., Uboldi, F. and Salvati, M.R. (2010), A spatial consistency test for surface observations from mesoscale meteorological networks. Q.J.R. Meteorol. Soc., 136: 1075-1088. doi:10.1002/qj.622 (Reference Abbreviation: LUS10) See also the wiki-pages https://github.com/metno/titanlib/wiki/Spatial-consistency-test + Algorithm: The big task of applying the SCT_dual over the whole observational network is splitted into several smaller tasks. The observations are divided into the two classes w=1) "yes, an event happened", or w=0) "no, an event did not happen" The SCT_dual is applied many times in sequence. Each time, the SCT_dual is applied over a small region centered on an observation location (i.e. the centroid observation). Based on the centroid, we define an inner circle and an outer circle. The outer circle is used to provide the boundary conditions. The observations to test are those within the inner circle that have not been tested yet. The quality of those observations is determined by comparing their classes against the leave-one-out predicted classes considering all observations within the outer circle. See also the comments of the function "sct_dual_core" for more details. The application of the sequence of SCT_duals over the whole observational network is repeated several times, until no GEs are found within the observations tested. In fact, the core of SCT_dual is to test a single observation against an independent estimate that is obtained assuming all the neighbouring observations are good ones. As a consequence, a bad observation can influence the results of some tests on neighbouring observations before being rejected. We apply special care to avoid "false positives" (good flagged as bad). For each SCT_dual over a centroid, we flag as bad only the observation showing the worst result. In addition, an extra-loop is done over the bad observations where only the good ones are considered. We may "save" bad observations. Analogously, to avoid "false negatives" (bad flagged as good), the last loop is done over the bad observations where only the good ones are considered. We may "save" bad observations during this last loop. (*) Notes on the data structures (see also comments in set_indices): we have defined a hierarchy of data structures global -> outer -> inner -> test global vectors are the input vectors. The other data structures refer to a specific iteration when a centroid observation has been identified. outer are the vectors of data on the outer circle, not yet flagged as bad. inner are the data on the inner circle, not yet flagged as bad. test data are the observations in the inner circle and still to test. We use the same counter variables for the data structures: g -> global; i,j -> outer; l -> inner; m -> test There are vectors of indices matching the different structures. For example, indices_outer_inner matches the outer and the inner vectors. indices_outer_inner is a vector of the dimension of the number of observations in the inner circle. The instruction i=indices_outer_inner[l] maps the l-th element of inner-type vectors as the i-th element of outer-type vectors. (*) Notes on event_thresholds. Different thresholds can be used for different observations. The thresholds vectors have the same dimensions of the observations vectors (global). + Pseudo-code: Loop over the number of iterations prescribed Loop over the p observations (observation index is "curr"). Decide if the observation is suitable for a centroid Define outer/inner cirles, observations to test and set all the vector of indices Check if the observation is isolated If all the observations in the outer circle belong to the same class, then further steps are not needed and the observations to test are flagged as good ones SCT_dual over the inner circle, either flag the worse observation as bad or flag all of them as good ones NOTE: observations can be flagged as good ones only after the first iteration (after rejecting the worst) Loop over the observations without QC flags (nor good neither bad) and use each of them as a centroid Loop over the bad observations and use each of them as a centroid + Returned values: flags. -999 = not checked; 0 = passed (good); 1 = failed (bad); 11 = isolated (<2 inside inner); 12 = isolated (<num_min_outer inside outer) */ double s_time = titanlib::clock(); const vec& lats = points.get_lats(); const vec& lons = points.get_lons(); const vec& elevs = points.get_elevs(); const int p = values.size(); if( lats.size() != p || lons.size() != p || elevs.size() != p || values.size() != p) throw std::runtime_error("Dimension mismatch"); if(num_min_outer < 2) throw std::invalid_argument("num_min_outer must be > 1"); if(num_max_outer < num_min_outer) throw std::invalid_argument("num_max_outer must be > num_min_outer"); if(num_iterations < 1) throw std::invalid_argument("num_iterations must be >= 1"); if(min_horizontal_scale <= 0) throw std::invalid_argument("min_horizontal_scale must be > 0"); if(kth_closest_obs_horizontal_scale <= 0) throw std::invalid_argument("kth_closest_obs_horizontal_scale must be > 0"); if(vertical_scale <= 0) throw std::invalid_argument("vertical_scale must be > 0"); if(inner_radius < 0) throw std::invalid_argument("inner_radius must be >= 0"); if(outer_radius < inner_radius) throw std::invalid_argument("outer_radius must be >= inner_radius"); // initializations float na = -999.; // code for "Not Available". Any type of missing data int flag_not_tested_inner; int flag_not_tested_outer; ivec flags( p, na); ivec obs_test( p, 1); vec w( p, 0); vec eps2( p, 0.1); vec r( p, na); vec t( p, na); bool set_all_good = false; bool accept_not_tested = true; if(accept_not_tested){ std::cout << "Set flags for values that could not be tested as good " << p << std::endl; flag_not_tested_inner = 0; flag_not_tested_outer = 0; } else{ std::cout << "Set flags for values that could not be tested due to lack of points in the inner/outer radius to 11/12." << p << std::endl; flag_not_tested_inner = 11; flag_not_tested_outer = 12; } if (obs_to_check.size() == p) { for(int g=0; g<p; g++) obs_test[g] = obs_to_check[g]; } if (event_thresholds.size() == p) { for(int g=0; g<p; g++) r[g] = event_thresholds[g]; } else { for(int g=0; g<p; g++) r[g] = event_thresholds[0]; } if (test_thresholds.size() == p) { for(int g=0; g<p; g++) t[g] = test_thresholds[g]; } else { for(int g=0; g<p; g++) t[g] = test_thresholds[0]; } for(int g=0; g<p; g++) { if ( condition == titanlib::Eq) { if ( values[g] == r[g]) w[g] = 1; } else if ( condition == titanlib::Geq) { if ( values[g] >= r[g]) w[g] = 1; } else if ( condition == titanlib::Gt) { if ( values[g] > r[g]) w[g] = 1; } else if ( condition == titanlib::Leq) { if ( values[g] <= r[g]) w[g] = 1; } else if ( condition == titanlib::Lt) { if ( values[g] < r[g]) w[g] = 1; } } if(debug) std::cout << "==================DEBUG MODE ============================= " << std::endl; if(debug) std::cout << "Number of observations to test is " << p << std::endl; // KDtree has to do with fast computation of distances titanlib::KDTree tree(lats, lons); // if(debug) { std::cout << "g lats lons elevs obs:" << std::endl; for(int g=0; g < p; g++) { std::cout << g << " " << lats[g] << " " << lons[g] << " " << elevs[g] << " " << values[g] << std::endl; } } // SCT_dual iterations for(int iteration = 0; iteration < num_iterations; iteration++) { if(debug) std::cout << " +++++ Iteration " << iteration << " ++++++++++++++++" << std::endl; double s_time0 = titanlib::clock(); // reset this number each loop (this is for breaking if we don't throw anything new out) int thrown_out = 0; // diagnostic. count the number of times OI is performed int count_oi = 0; // loop over observations for(int curr=0; curr < p; curr++) { if(debug) std::cout << "===> curr " << curr << " ===============" << std::endl; // -~- Can the observation be used as a centroid for the definition of inner and outer circles? // jump to next if observation not to be checked or already checked if(obs_test[curr] != 1 || flags[curr] >= 0) { if(debug) std::cout << "..observation not suitable as a centroid " << curr << std::endl; continue; } // -~- Define outer/inner circles and which are the observations to test // get all neighbours that are close enough (inside outer circle) vec distances; ivec indices_global_outer_guess = tree.get_neighbours_with_distance(lats[curr], lons[curr], outer_radius, distances, true); if(indices_global_outer_guess.size() > num_max_outer) { int N = indices_global_outer_guess.size(); std::vector<std::pair<float,int> > pairs(N); for(int i = 0; i < indices_global_outer_guess.size(); i++) { pairs[i] = std::pair<float, int>(distances[i], indices_global_outer_guess[i]); } std::sort(pairs.begin(), pairs.end(), titanlib::sort_pair_first<float,int>()); distances.clear(); indices_global_outer_guess.clear(); distances.resize(num_max_outer); indices_global_outer_guess.resize(num_max_outer); for(int i = 0; i < num_max_outer; i++) { distances[i] = pairs[i].first; indices_global_outer_guess[i] = pairs[i].second; } } if(debug) { int p_dist = distances.size(); std::cout << "p_dist " << p_dist << std::endl; } // set all the indices linking the different levels ivec indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test; bool res = titanlib::set_indices( indices_global_outer_guess, obs_test, flags, distances, inner_radius, -1, indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test); int p_outer = indices_global_outer.size(); int p_inner = indices_outer_inner.size(); int p_test = indices_global_test.size(); if(debug) std::cout << "p_outer inner test " << p_outer << " " << p_inner << " " << "" << p_test << std::endl; // -~- Check if there are enough observations in the outer/inner circles if(p_outer < num_min_outer) { flags[curr] = flag_not_tested_outer; if(debug) { std::cout << "@@isolated (outer) " << curr << std::endl; } continue; } // if( p_inner < 2) { // flags[curr] = flag_not_tested_inner; // if(debug) std::cout << "@@isolated (inner) " << curr << std::endl; // continue; // } // -~- Vectors on the outer circle vec lons_outer = titanlib::subset( lons, indices_global_outer); vec elevs_outer = titanlib::subset( elevs, indices_global_outer); vec lats_outer = titanlib::subset( lats, indices_global_outer); vec eps2_outer = titanlib::subset( eps2, indices_global_outer); vec w_outer = titanlib::subset( w, indices_global_outer); vec t_outer = titanlib::subset( t, indices_global_outer); // Debug for indices if(debug) { ivec flags_outer; flags_outer.resize( p_outer, na); for(int i=0; i < p_outer; i++) { int g = indices_global_outer[i]; flags_outer[i] = flags[g]; } std::cout << "curr lats lons elevs obs:" << std::endl; std::cout << curr << " " << lats[curr] << " " << lons[curr] << " " << elevs[curr] << " " << values[curr] << std::endl; std::cout << "indices_global_outer - i g lats lons elevs obs w flags:" << std::endl; for(int i=0; i<p_outer; i++) { int g = indices_global_outer[i]; std::cout << std::setprecision(6) << i << " " << g << " " << lats[g] << " " << lons[g] << " " << elevs[g] << " " << values[g] << " " << w[g] << " " << flags[g] << std::endl; } std::cout << "outer - i lats lons elevs obs flags:" << std::endl; for(int i=0; i<p_outer; i++) { std::cout << std::setprecision(6) << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << w_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_outer_inner - l i lats lons elevs obs flags:" << std::endl; for(int l=0; l<p_inner; l++) { int i = indices_outer_inner[l]; std::cout << std::setprecision(6) << l << " " << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << w_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_outer_test - l m lats lons elevs obs flags:" << std::endl; for(int m=0; m<p_test; m++) { int i = indices_outer_test[m]; std::cout << std::setprecision(6) << m << " " << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << w_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_inner_test - l m lats lons elevs obs flags:" << std::endl; for(int m=0; m<p_test; m++) { int l = indices_inner_test[m]; int i = indices_outer_inner[l]; std::cout << std::setprecision(6) << m << " " << l << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << w_outer[i] << " " << flags_outer[i] << std::endl; } } // -~- If all observations in the outer circle belongs to the same class then all are good int p_outer_w1 = 0; for(int i=0; i<p_outer; i++) if ( w_outer[i] == 1) p_outer_w1++; if ( p_outer_w1 == p_outer || p_outer_w1 == 0) { for(int m=0; m<p_test; m++) { int g = indices_global_test[m]; flags[g] = 0; if (debug) std::cout << " shortcut - outer circle has all w=0 or all w=1 - index " << g << std::endl; } continue; } // -~- SCT_dual on a selection of observations to test in the inner circle bool set_flag0 = iteration > 0; res = sct_dual_core( lats_outer, lons_outer, elevs_outer, w_outer, t_outer, min_horizontal_scale, max_horizontal_scale, kth_closest_obs_horizontal_scale, vertical_scale, eps2_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test, debug, na, set_flag0, thrown_out, flags); // thrown_out is reset every new iteration // problems during the matrix inversion if ( !res) { flags[curr] = 100; if(debug) std::cout << " oi - flags=100 - index " << curr << std::endl; continue; } count_oi++; // one more OI } // end loop over observations double e_time0 = titanlib::clock(); if (debug) std::cout << "SCT_dual loop - Removing " << thrown_out << " observations. Number of OI " << count_oi << " time=" << e_time0 - s_time0 << " secs" << std::endl; if(thrown_out == 0) { if ( iteration == 0) set_all_good = true; if(iteration + 1 < num_iterations) if (debug) std::cout << "Stopping early after " << iteration + 1<< " iterations" << std::endl; break; } } // end of SCT_dual iterations /* enter if the first iteration has been completed without flagging any bad observation The loop flags all the observations as good ones */ if ( set_all_good) { int count_zero = 0; for(int curr=0; curr < p; curr++) { if ( flags[curr] == na && obs_test[curr] == 1) { flags[curr] = 0; count_zero++; } } if(debug) std::cout << "Remaining " << count_zero << " observations set to \"good\" " << std::endl; } /* check on observations missing QC flags */ if(debug) std::cout << " +++++ check on observations missing QC flags ++++++++++++++++" << std::endl; double s_time0 = titanlib::clock(); // reset this number each loop (this is for breaking if we don't throw anything new out) int thrown_out = 0; // diagnostic. count the number of times OI is performed int count_oi = 0; // loop over observations for(int curr=0; curr < p; curr++) { if(debug) std::cout << "===> curr " << curr << " ===============" << std::endl; // -~- Can the observation be used as a centroid for the definition of inner and outer circles? if(obs_test[curr] != 1 || flags[curr] >= 0) { if(debug) std::cout << "..skip " << curr << std::endl; continue; } // -~- Define outer/inner circles and which are the observations to test // get all neighbours that are close enough (inside outer circle) vec distances; ivec indices_global_outer_guess = tree.get_neighbours_with_distance(lats[curr], lons[curr], outer_radius, distances, true); if(indices_global_outer_guess.size() > num_max_outer) { int N = indices_global_outer_guess.size(); std::vector<std::pair<float,int> > pairs(N); for(int i = 0; i < indices_global_outer_guess.size(); i++) { pairs[i] = std::pair<float, int>(distances[i], indices_global_outer_guess[i]); } std::sort(pairs.begin(), pairs.end(), titanlib::sort_pair_first<float,int>()); distances.clear(); indices_global_outer_guess.clear(); distances.resize(num_max_outer); indices_global_outer_guess.resize(num_max_outer); for(int i = 0; i < num_max_outer; i++) { distances[i] = pairs[i].first; indices_global_outer_guess[i] = pairs[i].second; } } // set all the indices linking the different levels // note that the only observation to test is curr ivec indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test; bool res = titanlib::set_indices( indices_global_outer_guess, obs_test, flags, distances, inner_radius, curr, indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test); int p_outer = indices_global_outer.size(); int p_inner = indices_outer_inner.size(); int p_test = indices_global_test.size(); if(debug) std::cout << "p_outer inner test " << p_outer << " " << p_inner << " " << p_test << std::endl; // -~- Check if there are enough observations in the outer/inner circles if(p_outer < num_min_outer) { flags[curr] = flag_not_tested_outer; if(debug){ std::cout << "@@isolated (outer) " << curr << std::endl; } continue; } // if( p_inner < 2) { // flags[curr] = flag_not_tested_inner; // if(debug) std::cout << "@@isolated (inner) " << curr << std::endl; // continue; // } // -~- Vectors on the outer circle vec lons_outer = titanlib::subset( lons, indices_global_outer); vec elevs_outer = titanlib::subset( elevs, indices_global_outer); vec lats_outer = titanlib::subset( lats, indices_global_outer); vec eps2_outer = titanlib::subset( eps2, indices_global_outer); vec w_outer = titanlib::subset( w, indices_global_outer); vec t_outer = titanlib::subset( t, indices_global_outer); // -~- If all observations in the outer circle belongs to the same class then all are good int p_outer_w1 = 0; for(int i=0; i<p_outer; i++) if ( w_outer[i] == 1) p_outer_w1++; if ( p_outer_w1 == p_outer || p_outer_w1 == 0) { int g = indices_global_test[0]; flags[g] = 0; if (debug) std::cout << " shortcut - outer circle has all w=0 or all w=1 - index " << g << std::endl; continue; } // -~- SCT_dual on a selection of observations to test in the inner circle res = sct_dual_core( lats_outer, lons_outer, elevs_outer, w_outer, t_outer, min_horizontal_scale, max_horizontal_scale, kth_closest_obs_horizontal_scale, vertical_scale, eps2_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test, debug, na, true, thrown_out, flags); // problems during the matrix inversion if ( !res) { flags[curr] = 100; if(debug) std::cout << " oi - flags=100 - index " << curr << std::endl; continue; } count_oi++; // one more OI } // end loop over observations double e_time0 = titanlib::clock(); if (debug) std::cout << "QC missing - Removing " << thrown_out << " observations. Number of OI " << count_oi << " time=" << e_time0 - s_time0 << " secs" << std::endl; /* final check on the bad observations it may happen that a good observation is flagged as a bad one because of the order the SCT_dual has been done and the uncertainty made in the estimation of the background (remember that bad observations may have been used to get the background). This final check is made only on bad observations and uses only good observations. */ if(debug) std::cout << " +++++ final check on the bad observations ++++++++++++++++" << std::endl; s_time0 = titanlib::clock(); // reset this number each loop (this is for breaking if we don't throw anything new out) thrown_out = 0; // diagnostic. count the number of times OI is performed count_oi = 0; // loop over observations for(int curr=0; curr < p; curr++) { if(debug) std::cout << "===> curr " << curr << " ===============" << std::endl; // -~- Can the observation be used as a centroid for the definition of inner and outer circles? if(obs_test[curr] != 1 || flags[curr] != 1) { if(debug) std::cout << "..skip " << curr << std::endl; continue; } // -~- Define outer/inner circles and which are the observations to test // get all neighbours that are close enough (inside outer circle) vec distances; ivec indices_global_outer_guess = tree.get_neighbours_with_distance(lats[curr], lons[curr], outer_radius, distances, true); if(indices_global_outer_guess.size() > num_max_outer) { int N = indices_global_outer_guess.size(); std::vector<std::pair<float,int> > pairs(N); for(int i = 0; i < indices_global_outer_guess.size(); i++) { pairs[i] = std::pair<float, int>(distances[i], indices_global_outer_guess[i]); } std::sort(pairs.begin(), pairs.end(), titanlib::sort_pair_first<float,int>()); distances.clear(); indices_global_outer_guess.clear(); distances.resize(num_max_outer); indices_global_outer_guess.resize(num_max_outer); for(int i = 0; i < num_max_outer; i++) { distances[i] = pairs[i].first; indices_global_outer_guess[i] = pairs[i].second; } } // set all the indices linking the different levels ivec indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test; bool res = titanlib::set_indices( indices_global_outer_guess, obs_test, flags, distances, inner_radius, curr, indices_global_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test); int p_outer = indices_global_outer.size(); int p_inner = indices_outer_inner.size(); int p_test = indices_global_test.size(); if(debug) std::cout << "p_outer inner test " << p_outer << " " << p_inner << " " << p_test << std::endl; // -~- Decide if there are enough observations in the outer/inner circles if(p_outer < num_min_outer) { flags[curr] = flag_not_tested_outer; if(debug){ std::cout << "@@isolated (outer) " << curr << std::endl; } continue; } // if( p_inner < 2) { // flags[curr] = 11; // if(debug) std::cout << "@@isolated (inner) " << curr << std::endl; // continue; // } // -~- Set vectors on the outer circle vec lons_outer = titanlib::subset( lons, indices_global_outer); vec elevs_outer = titanlib::subset( elevs, indices_global_outer); vec lats_outer = titanlib::subset( lats, indices_global_outer); vec eps2_outer = titanlib::subset( eps2, indices_global_outer); vec w_outer = titanlib::subset( w, indices_global_outer); vec t_outer = titanlib::subset( t, indices_global_outer); // Debug for indices if(debug) { ivec flags_outer; flags_outer.resize( p_outer, na); for(int i=0; i < p_outer; i++) { int g = indices_global_outer[i]; flags_outer[i] = flags[g]; } std::cout << "curr lats lons elevs obs:" << std::endl; std::cout << curr << " " << lats[curr] << " " << lons[curr] << " " << elevs[curr] << " " << values[curr] << std::endl; std::cout << "indices_global_outer - i g lats lons elevs obs w flags:" << std::endl; for(int i=0; i<p_outer; i++) { int g = indices_global_outer[i]; std::cout << std::setprecision(6) << i << " " << g << " " << lats[g] << " " << lons[g] << " " << elevs[g] << " " << values[g] << " " << w[g] << " " << flags[g] << std::endl; } std::cout << "outer - i lats lons elevs obs flags:" << std::endl; for(int i=0; i<p_outer; i++) { std::cout << std::setprecision(6) << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << w_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_outer_inner - l i lats lons elevs obs flags:" << std::endl; for(int l=0; l<p_inner; l++) { int i = indices_outer_inner[l]; std::cout << std::setprecision(6) << l << " " << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << w_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_outer_test - l m lats lons elevs obs flag:" << std::endl; for(int m=0; m<p_test; m++) { int i = indices_outer_test[m]; std::cout << std::setprecision(6) << m << " " << i << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << w_outer[i] << " " << flags_outer[i] << std::endl; } std::cout << "indices_inner_test - l m lats lons elevs obs flags:" << std::endl; for(int m=0; m<p_test; m++) { int l = indices_inner_test[m]; int i = indices_outer_inner[l]; std::cout << std::setprecision(6) << m << " " << l << " " << lats_outer[i] << " " << lons_outer[i] << " " << elevs_outer[i] << " " << w_outer[i] << " " << flags_outer[i] << std::endl; } } // -~- If all observations in the outer circle belongs to the same class then all are good int p_outer_w1 = 0; for(int i=0; i<p_outer; i++) if ( w_outer[i] == 1) p_outer_w1++; if ( p_outer_w1 == p_outer || p_outer_w1 == 0) { int g = indices_global_test[0]; flags[g] = 0; if (debug) std::cout << " shortcut - outer circle has all w=0 or all w=1 - index " << g << std::endl; continue; } // -~- SCT_dual within the inner circle // note that the only observation to test is curr res = sct_dual_core( lats_outer, lons_outer, elevs_outer, w_outer, t_outer, min_horizontal_scale, max_horizontal_scale, kth_closest_obs_horizontal_scale, vertical_scale, eps2_outer, indices_global_test, indices_outer_inner, indices_outer_test, indices_inner_test, debug, na, true, thrown_out, flags); // problems during the matrix inversion if ( !res) { flags[curr] = 100; if(debug) std::cout << " oi - flags=100 - index " << curr << std::endl; continue; } count_oi++; // one more OI } // end loop over observations e_time0 = titanlib::clock(); if (debug) std::cout << "Re-check bad obs - Removing " << thrown_out << " observations. Number of OI " << count_oi << "time = " << e_time0 - s_time0 << " secs" << std::endl; // if(debug) { int count_bad = 0; int count_good = 0; int count_missing = 0; int count_iso_inner = 0; int count_iso_outer = 0; int count_fail_matinv = 0; int count_impossible = 0; // loop over observations for(int curr=0; curr < p; curr++) { if( flags[curr] == 1) { count_bad++; } else if( flags[curr] == 0) { count_good++; } else if ( flags[curr] == na) { count_missing++; } else if( accept_not_tested && (flags[curr] == flag_not_tested_inner)) { count_iso_inner++; } else if( accept_not_tested && (flags[curr] == flag_not_tested_outer)) { count_iso_outer++; } else if( flags[curr] == 100) { count_fail_matinv++; } else { count_impossible++; } } if(accept_not_tested) std::cout << std::setprecision(3) << "summary - # TOT good bad missing: " << p << " " << count_good << " " << count_bad << " " << count_missing << std::endl; else std::cout << std::setprecision(3) << "summary - # TOT good bad missing isolated(inner) isolated(outer): " << p << " " << count_good << " " << count_bad << " " << count_missing << " " << count_iso_inner << " " << count_iso_outer << std::endl; if(count_fail_matinv > 0) std::cout << std::setprecision(3) << "!!!! failure in matrix inversion: " << count_fail_matinv << std::endl; if(count_impossible > 0) std::cout << std::setprecision(3) << "!!!! unknown flag: " << count_impossible << std::endl; } // if(debug) std::cout << ">> Total Time " << e_time0 - s_time << "secs" << std::endl; // return flags; } // end SCT_dual // //----------------------------------------------------------------------------// // SCT dual WITHIN THE INNER CIRCLE // Smallets SCT_dual unit bool sct_dual_core( const vec& lats, const vec& lons, const vec& elevs, const vec& w, const vec& t, float Dh_min, float Dh_max, int kth_close, float Dz, const vec& eps2, const ivec& indices_global_test, const ivec& indices_outer_inner, const ivec& indices_outer_test, const ivec& indices_inner_test, bool debug, float na, bool set_flag0, int& thrown_out, ivec& flags) { /*----------------------------------------------------------------------------- Spatial consistency test for dichotomous (yes/no) variables to test within the inner circle, considering all the observations in the outer circle. The inner and outer circles are defined with respect to a centroid observation. Each observation to test is divided into "yes, the event happened" or "no, the event did not happen" (w vector: yes=1, no=0) In the outer circle, there are two sub-networks of observations. The yes-network (w1) and the no-network (w0). We assume that information is distributed in space through correlation functions, analougously to what happen for statistical interpolation with error correlation matrices. At each observation location, the leave-one-out integral data influence (idiv) is obtained for each of the two sub-networks. The two values w1_idiv and w0_idiv are then obtained. The larger of those two values corresponds to the best guess between "yes" and "no" derived by the neighbours, which is also a guess that is independent from the actual observation. If there is a mismatch between the actual obtained w value and the best guess, then we have a canditate bad observation. Note that when computing a best guess we assume all buddies are good ones. Then, a bad buddy may cause a good observation to be misjudged as bad. For this reason we allow for the rejection of just one bad observation at a time. We reject the one where the mismatch between actual value and best guess is the worst. To quantify the mismatches, we use the relative information content of w1_idiv with respect to w0_idiv (and viceversa I(0wrt1)): I(1wrt0) = w1_idiv * log( w1_idiv / w0_idiv) (see e.g. page 12 of Tarantola's Book "Inverse problem theory" (2005).) which is equivalent to defining the distance between w1_idiv and w0_idiv not through difference but in a more complicated way. Note than I(...) is called "z" in the code. If no mismatches are found, then all observations are good ones. In areas of transition between "yes" and "no" regions, a good observation can be mistaken for a bad one. For this reason, the user is allowed to set a threshold "t" for the relative information content and an observation is flagged as bad only if the relative information content I is larger than the threshold. Note that if both w1_idiv and w0_idiv are small numbers (close to zero), then we are dealing with an observation that is rather distant from its buddies. The distance is specified with respect to the metric defined by the correlation functions. In this case, better to leave the judgment suspended and consider the observation good. A small measure of optimism in ignorance is fashionable these days, we can't help but adapt. Output values: flags, global vector. return updated quality control flag values (1 = bad, 0 = good) thrown_out, integer. update the number of observations flagged as bad ones -----------------------------------------------------------------------------*/ using namespace boost::numeric::ublas; // init int p_outer = w.size(); int p_test = indices_global_test.size(); /* observations where leave-one-out IDIs are both small are difficult to judge because they do not have close-enough buddies we skip them. This is the threshold */ float w_idiv_min = 0.45; /* two more indices ... w0[i] = na when w[i] = 1; w0[i] = j for the j-th element of w where w = 0 ... w1[i] = na when w[i] = 0; w1[i] = k for the k-th element of w where w = 1 */ ivec indices_outer_w0( p_outer, na); ivec indices_outer_w1( p_outer, na); int j0=0; int j1=0; for(int i=0; i < p_outer; i++) { if ( w[i] == 0) { indices_outer_w0[i] = j0; j0++; } if ( w[i] == 1) { indices_outer_w1[i] = j1; j1++; } } int p_outer_w0 = j0; int p_outer_w1 = j1; if (debug) { std::cout << " p_outer_w0 p_outer_w1 = " << p_outer_w0 << " " << p_outer_w1 << std::endl; for(int i=0; i < p_outer; i++) { std::cout << " i indices_outer_w0 indices_outer_w1 " << indices_outer_w0[i] << " " << indices_outer_w1[i] << std::endl; } } /* Compute Dh. The location-dependent horizontal de-correlation lenght scale used for the background error correlation matrix */ boost::numeric::ublas::matrix<float> disth(p_outer, p_outer); boost::numeric::ublas::matrix<float> distz(p_outer, p_outer); boost::numeric::ublas::vector<float> Dh(p_outer); // boost::numeric::ublas::matrix<float> disth_w0(p_outer_w0, p_outer_w0); // boost::numeric::ublas::matrix<float> distz_w0(p_outer_w0, p_outer_w0); // boost::numeric::ublas::matrix<float> disth_w1(p_outer_w1, p_outer_w1); // boost::numeric::ublas::matrix<float> distz_w1(p_outer_w1, p_outer_w1); for(int i=0; i < p_outer; i++) { vec Dh_vector(p_outer); // int i0 = indices_outer_w0[i]; // int i1 = indices_outer_w1[i]; int k = 0; for(int j=i; j < p_outer; j++) { // int j0 = indices_outer_w0[j]; // int j1 = indices_outer_w1[j]; disth(i, j) = titanlib::calc_distance( lats[i], lons[i], lats[j], lons[j]); distz(i, j) = fabs( elevs[i] - elevs[j]); // if ( i1 != na && j1 != na) { // disth_w1(i1, j1) = disth(i, j); // distz_w1(i1, j1) = distz(i, j); // } else if ( i0 != na && j0 != na) { // disth_w0(i0, j0) = disth(i, j); // distz_w0(i0, j0) = distz(i, j); // } if(i != j) { disth(j, i) = disth(i, j); distz(j, i) = distz(i, j); // if ( i1 != na && j1 != na) { // disth_w1(j1, i1) = disth(i, j); // distz_w1(j1, i1) = distz(i, j); // } else if ( i0 != na && j0 != na) { // disth_w0(j0, i0) = disth(i, j); // distz_w0(j0, i0) = distz(i, j); // } Dh_vector[k] = disth(i, j); k++; } } for(int j=0; j <= i; j++) { Dh_vector[k] = disth(i, j); k++; } // find distance to the k-th closest observations Dh(i) = titanlib::find_k_closest(Dh_vector, kth_close); if(debug) std::cout << "i Dh " << i << " " << Dh(i) << std::endl; } float Dh_mean = std::accumulate(std::begin(Dh), std::end(Dh), 0.0) / Dh.size(); if(Dh_mean < Dh_min) { if(debug) std::cout << "Dh_mean (<min_horizontal_scale) " << Dh_mean << std::endl; Dh_mean = Dh_min; } if(Dh_mean > Dh_max) { if(debug) std::cout << "Dh_mean (>max_horizontal_scale) " << Dh_mean << std::endl; Dh_mean = Dh_max; } if(debug) std::cout << "Dh_mean " << Dh_mean << std::endl; if(debug) std::cout << "Dz " << Dz << std::endl; /* Compute S + eps2*I and store it in S S_w1 made by only points where w = 1 S_w0 made by only points where w = 0 */ boost::numeric::ublas::matrix<float> S(p_outer,p_outer); boost::numeric::ublas::matrix<float> S_w0(p_outer_w0,p_outer_w0); boost::numeric::ublas::matrix<float> S_w1(p_outer_w1,p_outer_w1); boost::numeric::ublas::matrix<float> Sinv_w0(p_outer_w0,p_outer_w0); boost::numeric::ublas::matrix<float> Sinv_w1(p_outer_w1,p_outer_w1); for(int i=0; i < p_outer; i++) { int i0 = indices_outer_w0[i]; int i1 = indices_outer_w1[i]; for(int j=i; j < p_outer; j++) { int j0 = indices_outer_w0[j]; int j1 = indices_outer_w1[j]; float value = std::exp(-.5 * std::pow((disth(i, j) / Dh_mean), 2) - .5 * std::pow((distz(i, j) / Dz), 2)); if(i==j) { // weight the diagonal, this also ensure an invertible matrix value = value + eps2[i]; } else { S(j, i) = value; } S(i, j) = value; if ( i1 != na && j1 != na) { S_w1(i1, j1) = value; if ( i1 != j1) S_w1(j1, i1) = value; } else if ( i0 != na && j0 != na) { S_w0(i0, j0) = value; if ( i0 != j0) S_w0(j0, i0) = value; } } } // Invert S matrices bool b = invert_matrix( S_w0, Sinv_w0); if( !b) return( false); b = invert_matrix( S_w1, Sinv_w1); if( !b) return( false); // Definitions boost::numeric::ublas::vector<float> Sinv_d_w0(p_outer_w0); boost::numeric::ublas::vector<float> Sinv_d_w1(p_outer_w1); // re-obtains S and sum-up the rows of the Inv(S_w) matrices for(int i=0; i<p_outer; i++) { S(i,i) -= eps2[i]; int i0 = indices_outer_w0[i]; int i1 = indices_outer_w1[i]; if ( i1 != na) { float acc = 0; for(int j1=0; j1<p_outer_w1; j1++) acc += Sinv_w1(i1,j1); Sinv_d_w1(i1) = acc; } else { float acc = 0; for(int j0=0; j0<p_outer_w0; j0++) acc += Sinv_w0(i0,j0); Sinv_d_w0(i0) = acc; } } // Run the real check over the observations to test float zmx = na; int mmx = na; if(debug) std::cout << "z_test - i lon lat w w1_idiv w0_idiv" << std::endl; for(int m=0; m<p_test; m++) { int i = indices_outer_test[m]; int i0 = indices_outer_w0[i]; int i1 = indices_outer_w1[i]; // compute leave-one-out IDIs, one considering w=0 only and the other with w=1 only float w0_idiv = 0; float w1_idiv = 0; for(int j=0; j<p_outer; j++){ int j0 = indices_outer_w0[j]; int j1 = indices_outer_w1[j]; if ( i1 != na && j0 != na) { w0_idiv += S(i, j) * Sinv_d_w0(j0); } else if ( i0 != na && j1 != na) { w1_idiv += S(i, j) * Sinv_d_w1(j1); } } if ( i1 != na) { w1_idiv = 1. - Sinv_d_w1(i1) / Sinv_w1(i1, i1); // if (w1_idiv < w_idiv_min) w1_idiv = w_idiv_min; if (w1_idiv <= 0) w1_idiv = 0.001; } else { w0_idiv = 1. - Sinv_d_w0(i0) / Sinv_w0(i0, i0); // if (w0_idiv < w_idiv_min) w0_idiv = w_idiv_min; if (w0_idiv <= 0) w0_idiv = 0.001; } float z = na; float z0wrt1 = w0_idiv * log( w0_idiv / w1_idiv); float z1wrt0 = w1_idiv * log( w1_idiv / w0_idiv); // verify that the observation has buddies nearby if ( w1_idiv >= w_idiv_min || w0_idiv >= w_idiv_min) { // candidate bad if w=1 but the neighbours consider more likely w=0 if ( w[i] == 1 && w0_idiv > w1_idiv && z0wrt1 > t[i]) { z = z0wrt1; // candidate bad if w=0 but the neighbours consider more likely w=1 } else if ( w[i] == 0 && w1_idiv > w0_idiv && z1wrt0 > t[i]) { z = z1wrt0; } // real bad is the observation with larger z if ( z != na) { if ( zmx == na) { zmx = z; mmx = m; } else if ( z > zmx ) { zmx = z; mmx = m; } } } if(debug) std::cout << i << " " << w[i] << " " << lons[i] << " " << lats[i] << " " << w1_idiv << " " << w0_idiv << " " << z1wrt0 << " " << z0wrt1 << " " << z << " " << zmx << " " << mmx << std::endl; } // Take a decision if ( mmx != na) { // flag just the worse z int g = indices_global_test[mmx]; int i = indices_outer_test[mmx]; flags[g] = 1; thrown_out++; if(debug) std::cout << std::setprecision(6) << "SCT_dual failed - flag as bad - index w z " << g << " " << w[i] << " " << zmx << std::endl; // ... BUT if no mismatch between obtained and expected w's occur, then flag ALL as good } else if (set_flag0) { for(int m=0; m<p_test; m++) { int g = indices_global_test[m]; flags[g] = 0; if(debug) std::cout << "all set to good - g " << g << std::endl; } } // normal exit return true; }
47,964
C++
.cpp
858
45.815851
582
0.560179
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,791
range_check.cpp
metno_titanlib/src/range_check.cpp
#include <vector> #include <math.h> #include "titanlib.h" #include <assert.h> #include <iostream> #include <exception> #include <boost/date_time/gregorian/gregorian_types.hpp> using namespace titanlib; double mean_temp(float lat, int unixtime); double interpolate(int i1, int i2, float lat, float latitudes[], double numbers[]); std::pair<int,int> find_between(float lat, float latitudes[], int len); ivec titanlib::range_check(const vec& values, const vec& min, const vec& max) { // loop over all the lats/lons/elevs + value // either min/max has length 1 or is the same length as the other vecs const int s = values.size(); // assert that the max and min are either both size 1 or the size of values if( (min.size() != s && min.size() != 1) || (max.size() != s && max.size() != 1) ) { std::stringstream ss; ss << "Range check: Min (" << min.size() << ")/max(" << max.size() << ") arrays must either be length 1 or the same length as values (" << s << ")"; throw std::runtime_error(ss.str()); } ivec flags(s, 0); for(int i = 0; i < s; i++) { // leave the index to 0 if its the same max/min applied to everything // else same as loop int min_i = (min.size() == s) ? i : 0; int max_i = (max.size() == s) ? i : 0; // loop over the vectors and set the flags (0 = ok and 1 = bad) if(!titanlib::is_valid(values[i]) || values[i] < min[min_i] || values[i] > max[max_i]) { flags[i] = 1; } } return flags; } ivec titanlib::range_check_climatology(const Points& points, const vec& values, int unixtime, const vec& pos, const vec& neg) { // loop over all the lats/lons/elevs + value // either min/max has length 1 or is the same length as the other vecs const int s = points.size(); const vec& lats = points.get_lats(); const vec& lons = points.get_lons(); const vec& elevs = points.get_elevs(); if( lons.size() != s || elevs.size() != s || values.size() != s ) { throw std::runtime_error("Dimension mismatch"); } if( (pos.size() != s && pos.size() != 1) || (neg.size() != s && neg.size() != 1) ) { throw std::runtime_error("Dimension mismatch"); } ivec flags(s, 0); for(int i = 0; i < s; i++) { // leave the index to 0 if its the same max/min applied to everything // else same as loop int pos_i = (pos.size() == s) ? i : 0; int neg_i = (neg.size() == s) ? i : 0; // get best guess mean temp double t = mean_temp(lats[i], unixtime); std::cout << "mean t: " << t << "\n"; double mean_pos = t + pos[pos_i]; double mean_neg = t + neg[neg_i]; // loop over the vectors and set the flags (0 = ok and 1 = bad) if(!titanlib::is_valid(values[i]) || values[i] < mean_neg || values[i] > mean_pos) { flags[i] = 1; } } return flags; } double mean_temp(float lat, int unixtime) { // do some math to check if the value makes sense based on the lat/long //http://www-das.uwyo.edu/~geerts/cwx/notes/chap16/geo_clim.html float mean_latitudes[] = {90,60,50,45,40,30,15,0,-15,-30,-35,-40,-45,-60,-90}; double mean_temp[] = {-15,5,10,15,20,25,30,30,25,21,20,15,10,0,-25}; // find what two points are closest? std::pair<int,int> p = find_between(lat, mean_latitudes, 15); //std::cout << " pair: " << latitudes[p.first] << " "; //std::cout << latitudes[p.second] << "\n"; double mt = interpolate(p.first, p.second, lat, mean_latitudes, mean_temp); // factor in season??? //https://www.physics.byu.edu/faculty/christensen/physics%20137/Figures/Temperature/Effects%20of%20Latitude%20on%20Annual%20Temperature%20Range.htm float latitudes_var[] = {90,75,60,45,30,15,0,-15,-30,-45,-60,-75,90}; double seasonal_variation[] = {40,32,30,23,13,3,0,4,7,6,11,26,31}; // find what two points are closest? std::pair<int,int> p2 = find_between(lat, latitudes_var, 13); double sv = interpolate(p2.first, p2.second, lat, latitudes_var, seasonal_variation); boost::gregorian::date epoch(1970,1,1); boost::gregorian::date_duration diff(unixtime/86400); boost::gregorian::date newDate = epoch + diff; int date = newDate.year() * 10000 + newDate.month() * 100 + newDate.day(); //std::cout << date << "\n"; int m = newDate.month(); //std::cout << "month: " << m << "\n"; // given this month, adjust the mt based on sv if(m == 1) { // coldest return mt + (sv/2)*-1; } if(m == 12 || m == 2) { // second coldest return mt + (sv/2)*-0.6; } if(m == 11 || m == 3) { return mt + (sv/2)*-0.3; } //if(m == 10 || m == 4) { // average??? // return mt + (sv/2)*0.6; //} if(m == 5 || m == 9) { return mt + (sv/2)*0.3; } if(m == 6 || m == 8) { // second warmest return mt + (sv/2)*0.6; } if(m == 7) { // warmest return mt + (sv/2)*1; } return mt; } double interpolate(int i1, int i2, float lat, float latitudes[], double numbers[]) { // calculate percentage between the 2 and get mean temp based on this float diff = latitudes[i1] - lat; float space = latitudes[i1] - latitudes[i2]; float percent = diff/space; //std::cout << " lat: " << lat; //std::cout << " percent: " << percent; //std::cout << "\n"; float temp_diff = numbers[i2] - numbers[i1]; //std::cout << " diff: "; //std::cout << temp_diff; //std::cout << "\n"; double mt = numbers[i1] + (temp_diff*percent); //std::cout << "interpolated num: " << mt << "\n"; return mt; } std::pair<int,int> find_between(float lat, float latitudes[], int len) { std::pair<float,float> p = std::make_pair(0,0); assert(lat <= 90); assert(lat >= -90); for(int i = 0; i < len; i++) { if(lat > latitudes[i]) { // then that means we are between this and the previous p = std::make_pair(i-1,i); break; } } return p; }
6,140
C++
.cpp
148
35.418919
156
0.572939
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,792
swig.cpp
metno_titanlib/src/swig.cpp
#include "titanlib.h" #include <iostream> using namespace titanlib; float* titanlib::test_array(float* v, int n) { int count = 0; for(int i = 0; i < n; i++) count++; return v; } void titanlib::test_not_implemented_exception() { throw titanlib::not_implemented_exception(); }
302
C++
.cpp
12
21.916667
49
0.666667
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,793
titanlib.h
metno_titanlib/include/titanlib.h
#ifndef TITANLIB_H #define TITANLIB_H #include <iostream> #include <vector> #include <assert.h> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/index/rtree.hpp> #include <boost/numeric/ublas/matrix.hpp> #ifdef _OPENMP #include <omp.h> #endif #define TITANLIB_VERSION "0.3.4.dev3" #define __version__ TITANLIB_VERSION namespace titanlib { /** ************************************** * @name Short-hand notation for vectors of different dimensions sizes * ***************************************/ /**@{*/ // Preferred vector types typedef std::vector<int> ivec; typedef std::vector<float> vec; typedef std::vector<double> dvec; typedef std::vector<vec> vec2; /**@}*/ /** ************************************** * @name Constants * Functions that assimilate observations onto a gridded background * ***************************************/ /**@{*/ /** Missing value indicator */ static const float MV = NAN; /** Missing value indicator in gridpp command-line tool */ static const float MV_CML = -999; /** Mathematical constant pi */ static const float pi = 3.14159265; /** Radius of the earth [m] */ static const double radius_earth = 6.378137e6; /**@}*/ /** Types of coordinates for position of points */ enum CoordinateType { Geodetic = 0, /**< Latitude and longitude */ Cartesian = 1, /**< X and Y */ }; enum BackgroundType { VerticalProfile = 0, VerticalProfileTheilSen = 1, MeanOuterCircle = 2, MedianOuterCircle = 3, External = 4, }; enum ConditionType { Eq = 0, Gt = 1, Geq = 2, Lt = 3, Leq = 4, }; class Points; /** **************************************** * @name Spatial checks * Checks that consider the spatial properties of observations * *****************************************/ /**@{*/ /** Spatial Consistency Test * @param num_min_prof Minimum number of observations to compute vertical profile * @param inner_radius Radius for flagging [m] * @param outer_radius Radius for computing OI and background [m] * @param min_elev_diff Minimum elevation difference to compute vertical profile [m] * @param min_horizontal_scale Minimum horizontal decorrelation length [m] * @param vertical_scale Vertical decorrelation length [m] * @param pos Positive deviation allowed * @param neg Negative deviation allowed * @param eps2 * @param prob_gross_error Probability of gross error for each observation * @param rep Coefficient of representativity * @param obs_to_check Observations that will be checked (since can pass in observations that will not be checked). 1=check the corresponding observation * @return flags */ ivec sct(const Points& points, const vec& values, int num_min, int num_max, float inner_radius, float outer_radius, int num_iterations, int num_min_prof, float min_elev_diff, float min_horizontal_scale, float vertical_scale, const vec& pos, const vec& neg, const vec& eps2, vec& prob_gross_error, vec& rep, const ivec& obs_to_check=ivec()); /** Spatial Consistency Test (SCT) - resistant to outliers * @param points Input points * @param values observed values to check (and/or to use) * @param obs_to_check Observations that will be checked (since can pass in observations that will not be checked). 1=check the corresponding observation * @param background_values external background value (not used if background_elab_type!=external) * @param background_elab_type one of: VerticalProfile, VerticalProfileTheilSen, MeanOuterCircle, MedianOuterCircle, External * @param num_min_outer Minimum number of observations inside the outer circle to compute SCT * @param num_max_outer Maximum number of observations inside the outer circle used * @param num_min_prof Minimum number of observations to compute vertical profile * @param inner_radius Radius for flagging [m] * @param outer_radius Radius for computing OI and background [m] * @param num_iterations Number of SCT iterations * @param min_elev_diff Minimum elevation difference to compute vertical profile [m] * @param min_horizontal_scale Minimum horizontal decorrelation length [m] * @param max_horizontal_scale Maximum horizontal decorrelation length [m] * @param kth_closest_obs_horizontal_scale Number of closest observations to consider in the adaptive estimation of the horizontal decorrelation length * @param vertical_scale Vertical decorrelation length [m] * @param value_mina Minimum admissible value * @param value_maxa Maximum admissible value * @param value_minv Minimum valid value * @param value_maxv Maximum valid value * @param eps2 ratio between observation and background error variances * @param tpos SCT-score threshold. Positive deviation allowed * @param tneg SCT-score threshold. Negative deviation allowed * @param debug Verbose output * @param basic Which SCT-score should be used? Basic or more advanced, which takes into account the local variability. Boolean: true=basic; false=advanced * @param scores SCT-score. The higher the score, the more likely is the presence of a gross measurement error * @return flags */ ivec sct_resistant( const Points& points, const vec& values, const ivec& obs_to_check, const vec& background_values, BackgroundType background_elab_type, int num_min_outer, int num_max_outer, float inner_radius, float outer_radius, int num_iterations, int num_min_prof, float min_elev_diff, float min_horizontal_scale, float max_horizontal_scale, int kth_closest_obs_horizontal_scale, float vertical_scale, const vec& value_mina, const vec& value_maxa, const vec& value_minv, const vec& value_maxv, const vec& eps2, const vec& tpos, const vec& tneg, bool debug, bool basic, vec& scores); /** Spatial Consistency Test for dichotomous (yes/no) variables * @param points Input points * @param values observed values to check (and/or to use) * @param obs_to_check Observations that will be checked (since can pass in observations that will not be checked). 1=check the corresponding observation * @param event_thresholds event thresholds (not used if background_elab_type!=external) * @param condition one of: Eq, Gt, Geq, Lt, Leq * @param num_min_outer Minimum number of observations inside the outer circle to compute SCT * @param num_max_outer Maximum number of observations inside the outer circle used * @param inner_radius Radius for flagging [m] * @param outer_radius Radius for computing OI and background [m] * @param num_iterations Number of SCT iterations * @param min_horizontal_scale Minimum horizontal decorrelation length [m] * @param max_horizontal_scale Maximum horizontal decorrelation length [m] * @param kth_closest_obs_horizontal_scale Number of closest observations to consider in the adaptive estimation of the horizontal decorrelation length * @param vertical_scale Vertical decorrelation length [m] * @param test_thresholds observation-dependent trhesholds used in the SCT dual tests. The threshold is for the relative information content and it should tipically be a number between 0-1 * @param debug Verbose output * @return flags */ ivec sct_dual( const Points& points, const vec& values, const ivec& obs_to_check, const vec& event_thresholds, ConditionType condition, int num_min_outer, int num_max_outer, float inner_radius, float outer_radius, int num_iterations, float min_horizontal_scale, float max_horizontal_scale, int kth_closest_obs_horizontal_scale, float vertical_scale, const vec& test_thresholds, bool debug); /** First Guess Test (FGT) - simplified (without OI) SCT * @param points Input points * @param values observed values to check (and/or to use) * @param obs_to_check Observations that will be checked (since can pass in observations that will not be checked). 1=check the corresponding observation * @param background_values external background value (not used if background_elab_type!=external) * @param background_uncertainties uncertainty of the external background value (not used if background_elab_type!=external, optional when background_elab_type=external) * @param background_elab_type one of: vertical_profile, vertical_profile_Theil_Sen, mean_outer_circle, external * @param num_min_outer Minimum number of observations inside the outer circle to compute FGT * @param num_max_outer Maximum number of observations inside the outer circle used * @param num_min_prof Minimum number of observations to compute vertical profile * @param inner_radius Radius for flagging [m] * @param outer_radius Radius for computing OI and background [m] * @param num_iterations Number of FGT iterations * @param min_elev_diff Minimum elevation difference to compute vertical profile [m] * @param value_mina Minimum admissible value * @param value_maxa Maximum admissible value * @param value_minv Minimum valid value * @param value_maxv Maximum valid value * @param tpos FGT-score threshold. Positive deviation allowed * @param tneg FGT-score threshold. Negative deviation allowed * @param debug Verbose output * @param basic Which SCT-score should be used? Basic or more advanced, which takes into account the local variability. Boolean: true=basic; false=advanced * @param scores FGT-score. The higher the score, the more likely is the presence of a gross measurement error * @return flags */ ivec fgt( const Points& points, const vec& values, const ivec& obs_to_check, const vec& background_values, const vec& background_uncertainties, BackgroundType background_elab_type, int num_min_outer, int num_max_outer, float inner_radius, float outer_radius, int num_iterations, int num_min_prof, float min_elev_diff, const vec& value_mina, const vec& value_maxa, const vec& value_minv, const vec& value_maxv, const vec& tpos, const vec& tneg, bool debug, bool basic, vec& scores); /** Range check. Checks observation is within the ranges given * @param values vector of observations * @param min min allowed value * @param max max allowed value * @param flags vector of return flags */ ivec range_check(const vec& values, const vec& min, const vec& max); ivec range_check_climatology(const Points& points, const vec& values, int unixtime, const vec& pos, const vec& neg); /** Buddy check. Compares a station to all its neighbours within a certain distance * @param values vector of observation values * @param radius search radius [m] * @param num_min the minimum number of buddies a station can have * @param threshold the threshold for flagging a station * @param max_elev_diff the maximum difference in elevation for a buddy (if negative will not check for heigh difference) * @param elev_gradient linear elevation gradient with height. For temperature, use something like -0.0065. * @param min_std * @param num_iterations * @param obs_to_check the observations that will be checked (since can pass in observations that will not be checked) * @param flags vector of return flags */ ivec buddy_check(const Points& points, const vec& values, const vec& radius, const ivec& num_min, float threshold, float max_elev_diff, float elev_gradient, float min_std, int num_iterations, const ivec& obs_to_check = ivec()); ivec buddy_event_check(const Points& points, const vec& values, const vec& radius, const ivec& num_min, float event_threshold, float threshold, float max_elev_diff, float elev_gradient, int num_iterations, const ivec& obs_to_check = ivec()); /** Isolation check. Checks that a station is not located alone * @param num_min required number of observations * @param radius search radius [m] * @param vertical_radius Vertical search radius [m] * @param flags vector of return flags */ ivec isolation_check(const Points& points, int num_min, float radius, float vertical_radius=MV); /** Isolation check, vectorized version. * @param num_min required number of observations * @param radius search radius [m] * @param vertical_radius Vertical search radius [m]. Use empty array to disable. * @param flags vector of return flags */ ivec isolation_check(const Points& points, const ivec& num_min, const vec& radius, const vec& vertical_radius=vec()); /** Duplicate check. Checks Flags duplicate stations. Keeps the first one when duplicates. * @param radius Stations within this radius are considered duplicates [m] * @param vertical_range Stations must also be within this vertical range to be considered duplicates [m]. Disable if MV. */ ivec duplicate_check(const Points& points, float radius, float vertical_range=titanlib::MV); ivec metadata_check(const Points& points, bool check_lat=true, bool check_lon=true, bool check_elev=true, bool check_laf=true); /** **************************************** * @name Timeserie methods * Functions that operate on timeseries of observations * *****************************************/ /**@{*/ /** Method by McCarthy 1973 * https://doi.org/10.1175/1520-0450(1973)012%3C0211:AMFCAT%3E2.0.CO;2 */ vec lag_reduction_filter(const vec& times, const vec& values, float a=0.5, float b=0.5, float k1=0.25, float k2=0.25, int n=10); /** **************************************** * @name OpenMP settings * Functions that configure OpenMP * *****************************************/ /**@{*/ /** Set the number of OpenMP threads to use. Overwrides OMP_NUM_THREAD env variable. */ void set_omp_threads(int num); /** Get the number of OpenMP threads currently set */ int get_omp_threads(); /** Sets the number of OpenMP threads to 1 if OMP_NUM_THREADS undefined */ void initialize_omp(); /** **************************************** * @name Utilities * Helper functions * *****************************************/ /**@{*/ /** * @return Titanlib version */ std::string version(); /** * @return The current UTC time (in seconds since 1970-01-01 00:00:00Z) */ double clock(); bool is_valid(float value); /** Compute a vertical profile based on input data * @param elevs vector of input elevations [m] * @param oelevs vector of output elevatios [m] * @param values observation vector [degrees C] * @param num_min_prof minimum number of observations needed to do a full profile * @param min_elev_diff use no elevation profile if elevation difference among stations is less than this [m] * @param debug If true, print debug messages */ vec compute_vertical_profile(const vec& elevs, const vec& oelevs, const vec& values, int num_min_prof, double min_elev_diff, bool debug=false); vec compute_vertical_profile_Theil_Sen(const vec& elevs, const vec& oelevs, const vec& values, int num_min_prof, double min_elev_diff, bool debug); /** Convert lat/lons to 3D cartesian coordinates with the centre of the earth as the origin * @param lats vector of latitudes [deg] * @param lons vector of longitudes [deg] * @param x_coords vector of x-coordinates [m] * @param y_coords vector of y-coordinates [m] * @param z_coords vector of z-coordinates [m] */ bool convert_coordinates(const vec& lats, const vec& lons, vec& x_coords, vec& y_coords, vec& z_coords); /** Same as above, but convert a single lat/lon to 3D cartesian coordinates * @param lat latitude [deg] * @param lon longitude [deg] * @param x_coord x-coordinate [m] * @param y_coord y-coordinate [m] * @param z_coord z-coordinate [m] */ bool convert_coordinates(float lat, float lon, float& x_coord, float& y_coord, float& z_coord); vec interpolate_to_points(const vec2& input_lats, const vec2& input_lons, const vec2& input_values, const vec& output_lats, const vec& output_lons); float deg2rad(float deg); float calc_distance(float lat1, float lon1, float lat2, float lon2); float calc_distance(float x0, float y0, float z0, float x1, float y1, float z1); float compute_quantile(double quantile, const vec& array); float find_k_closest(const vec& array, int k); template <class T> T subset(const T& array, const ivec& indices) { if(array.size() == 0) return array; if(indices.size() == 0) { return array; } T new_array(indices.size()); for(int i = 0; i < indices.size(); i++) { new_array[i] = array[indices[i]]; } return new_array; } Points subset(const Points& input, const ivec& indices); template <class T> void unsubset(const T& array, T& orig_array, const ivec& indices) { orig_array.clear(); orig_array.resize(indices.size()); assert(array.size() == indices.size()); for(int i = 0; i < indices.size(); i++) { orig_array[indices[i]] = array[i]; } } /** Background (first guess) calculations at observation locations * @param background_type background elaboration type * @param elevs elevations (m above mean sea level) * @param values observed values * @param num_min_prof minimum number of observations needed to compute a vertical profile different from the pseudo-adiabatic lapse rate (-0.0065 degC/m) * @param min_elev_diff when computing vertical profiles, the elevation difference between the 95th percentile and 5th percentile must be greater than this parameter. Otherwise use the pseudo-adiabatic lapse rate * @param value_minp minimum plausible value * @param value_maxp maximum plausible value * @param external_background_values external background values (used when background_elab_type=external) * @param indices_global_outer vector of positions of matches of (vector with the observations belonging to the outer circle) in the (global vector) (dimension is the number of observations in the outer circle) * @param debug verbose mode (true / false) */ vec background(const vec& elevs, const vec& values, int num_min_prof, float min_elev_diff, float value_minp, float value_maxp, BackgroundType background_type, const vec& external_background_values, const ivec& indices_global_outer, bool debug); bool invert_matrix (const boost::numeric::ublas::matrix<float>& input, boost::numeric::ublas::matrix<float>& inverse); bool set_indices( const ivec& indices_global_outer_guess, const ivec& obs_test, const ivec& dqcflags, const vec& dist_outer_guess, float inner_radius, int test_just_this, ivec& indices_global_outer, ivec& indices_global_test, ivec& indices_outer_inner, ivec& indices_outer_test, ivec& indices_inner_test); template<class T1, class T2> struct sort_pair_first { bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) { return left.first < right.first; }; }; /**@}*/ /** **************************************** * @name SWIG testing functions * Functions for testing the SWIG interface. Not useful for any other purpose. * *****************************************/ /**@{*/ /** Required for SWIG only */ float* test_array(float* v, int n); void test_not_implemented_exception(); /**@}*/ // ivec nearest_neighbours(const vec& lats, const vec& lons, float radius, float lat, float lon); // bool prioritize(const vec& values, const ivec& priority, float distance, ivec& flags); class Point { public: /** Constructor * @param lat: Latitude coordinate * @param lon: Longitude coordinate * @param elev: Elevation * @param laf: Land area fraction (between 0 and 1) * @param type: Coordinate type for lat and lon */ Point(float lat, float lon, float elev=MV, float laf=MV, CoordinateType type=Geodetic); float lat; float lon; float elev; float laf; CoordinateType type; }; class KDTree { public: KDTree(vec lats, vec lons, CoordinateType type=Geodetic); KDTree& operator=(KDTree other); KDTree(const KDTree& other); KDTree(CoordinateType type=Geodetic) {mType=type;}; /** Find single nearest points * @param lat Latitude of lookup-point * @param lon Longitude of lookup-point * */ int get_nearest_neighbour(float lat, float lon, bool include_match=true) const; /** Find all points with a radius * @param lat Latitude of lookup-point * @param lon Longitude of lookup-point * @param radius Lookup radius [m] * */ ivec get_neighbours(float lat, float lon, float radius, bool include_match=true) const; /** Find all points with a radius * @param lat Latitude of lookup-point * @param lon Longitude of lookup-point * @param radius Lookup radius [m] * @param distances Vector to store separation distances [m] * */ ivec get_neighbours_with_distance(float lat, float lon, float radius, vec& distances, bool include_match=true) const; /** Find the number of points within a radius * @param lat Latitude of lookup-point * @param lon Longitude of lookup-point * @param radius Lookup radius [m] * */ int get_num_neighbours(float lat, float lon, float radius, bool include_match=true) const; /** Find a set of nearest points * @param lat Latitude of lookup-point * @param lon Longitude of lookup-point * @param num Number of points to find * */ ivec get_closest_neighbours(float lat, float lon, int num, bool include_match=true) const; /** Convert lat/lons to 3D cartesian coordinates with the centre of the earth as the origin * @param lats vector of latitudes [deg] * @param lons vector of longitudes [deg] * @param x_coords vector of x-coordinates [m] * @param y_coords vector of y-coordinates [m] * @param z_coords vector of z-coordinates [m] * */ bool convert_coordinates(const vec& lats, const vec& lons, vec& x_coords, vec& y_coords, vec& z_coords) const; /** Same as above, but convert a single lat/lon to 3D cartesian coordinates * @param lat latitude [deg] * @param lon longitude [deg] * @param x_coord x-coordinate [m] * @param y_coord y-coordinate [m] * @param z_coord z-coordinate [m] * */ bool convert_coordinates(float lat, float lon, float& x_coord, float& y_coord, float& z_coord) const; static float deg2rad(float deg); static float rad2deg(float deg); static float calc_distance(float lat1, float lon1, float lat2, float lon2, CoordinateType type=Geodetic); static float calc_distance(float x0, float y0, float z0, float x1, float y1, float z1); static float calc_distance_fast(float lat1, float lon1, float lat2, float lon2, CoordinateType type=Geodetic); static float calc_distance_fast(const Point& p1, const Point& p2); vec get_lats() const; vec get_lons() const; int size() const; CoordinateType get_coordinate_type() const; protected: typedef boost::geometry::model::point<float, 3, boost::geometry::cs::cartesian> point; typedef std::pair<point, unsigned> value; typedef boost::geometry::model::box<point> box; boost::geometry::index::rtree< value, boost::geometry::index::quadratic<16> > mTree; vec mLats; vec mLons; CoordinateType mType; struct within_radius { public: within_radius(point p, float radius); bool operator()(value const& v) const; private: float radius; point p; }; struct is_not_equal { public: is_not_equal(point p); bool operator()(value const& v) const; private: point p; }; }; class Points { public: Points(); /** Initialize a new grid * @param lats: vector of latitudes [degrees] * @param lons: vector of longitudes [degrees] * @param elevs: vector of elevations [m] * @param lafs: vector of land area fractions [1] * @param type: Coordinate type */ Points(vec lats, vec lons, vec elevs=vec(), vec lafs=vec(), CoordinateType type=Geodetic); Points(KDTree tree, vec elevs=vec(), vec lafs=vec()); Points& operator=(Points other); Points(const Points& other); // Returns -1 if there are no neighbours int get_nearest_neighbour(float lat, float lon, bool include_match=true) const; ivec get_neighbours(float lat, float lon, float radius, bool include_match=true) const; ivec get_neighbours_with_distance(float lat, float lon, float radius, vec& distances, bool include_match=true) const; int get_num_neighbours(float lat, float lon, float radius, bool include_match=true) const; ivec get_closest_neighbours(float lat, float lon, int num, bool include_match=true) const; vec get_lats() const; vec get_lons() const; vec get_elevs() const; vec get_lafs() const; int size() const; CoordinateType get_coordinate_type() const; private: KDTree mTree; vec mLats; vec mLons; vec mElevs; vec mLafs; }; /** Represents point and their observed values */ class Dataset { public: Dataset(Points points, vec ivalues); /** Perform the range check on the dataset * @param indices Only perform the test on these indices. Use ivec(1, -1) to indicate all stations */ void range_check(const vec& min, const vec& max, const ivec& indices=ivec(1, -1)); void range_check_climatology(int unixtime, const vec& pos, const vec& neg, const ivec& indices=ivec(1, -1)); void sct(int num_min, int num_max, float inner_radius, float outer_radius, int num_iterations, int num_min_prof, float min_elev_diff, float min_horizontal_scale, float vertical_scale, const vec& t2pos, const vec& t2neg, const vec& eps2, vec& prob_gross_error, vec& rep, const ivec& indices=ivec(1, -1)); void sct_dual(const vec& event_thresholds, ConditionType condition, int num_min, int num_max, float inner_radius, float outer_radius, int num_iterations, float min_horizontal_scale, float max_horizontal_scale, int kth_closest_obs_horizontal_scale, float vertical_scale, const vec& test_thresholds, bool debug, const ivec& obs_to_check=ivec(), const ivec& indices=ivec(1, -1)); void buddy_check(const vec& radius, const ivec& num_min, float threshold, float max_elev_diff, float elev_gradient, float min_std, int num_iterations, const ivec& obs_to_check=ivec(), const ivec& indices=ivec(1, -1)); void buddy_event_check(const vec& radius, const ivec& num_min, float event_threshold, float threshold, float max_elev_diff, float elev_gradient, int num_iterations, const ivec& obs_to_check=ivec(), const ivec& indices=ivec(1, -1)); void isolation_check(int num_min, float radius, float vertical_radius=MV, const ivec& indices=ivec(1, -1)); void isolation_check(const ivec& num_min, const vec& radius, const vec& vertical_radius=vec(), const ivec& indices=ivec(1, -1)); void duplicate_check(float radius, float vertical_range=titanlib::MV, const ivec& indices=ivec(1, -1)); void dem_check(const vec& dem, float max_elev_diff); void external_check(const ivec& flags); void metadata_check(bool check_lat=true, bool check_lon=true, bool check_elev=true, bool check_laf=true, const ivec& indices=ivec(1, -1)); Points get_points() const; vec get_values() const; ivec get_flags() const; void set_values(vec ivalues); void set_flags(ivec ivalues); void set_points(Points ipoints); Points points; vec values; ivec flags; private: /* Get a subset of array where flags=0 and for indices. This function is different than * titanlib::subset in that it takes into account flags. * @param array Vector of values * @param indices Vector of indices * @return Vector of values */ template <class T> T subset_valid(const T& array, const ivec& indices=ivec(1, -1)) { if(array.size() != 1 && array.size() != flags.size()) { std::stringstream ss; ss << "Array (" << array.size() << ") must be either size 1 or the same as dataset size (" << flags.size() << ")"; throw std::invalid_argument(ss.str()); } if(indices.size() == 0) return T(); ivec indices0 = indices; if(indices.size() == 1 && indices[0] == -1) { // Use all indices indices0.clear(); indices0.resize(flags.size()); for(int i = 0; i < flags.size(); i++) indices0[i] = i; } T new_array; new_array.reserve(indices0.size()); for(int i = 0; i < indices0.size(); i++) { int index = indices0[i]; if(flags[index] == 0) { if(array.size() == 1) // Array is broadcast new_array.push_back(array[0]); else { assert(index < array.size()); new_array.push_back(array[index]); } } } return new_array; } /* Same as T subset_valid, except for Points */ Points subset_valid(const Points& input, const ivec& indices=ivec(1, -1)); ivec get_unflagged_indices(); // Create a vector with results, but only for locations that have not been flagged // To broadcase the values to point, use a singleton array // An empty array will return an empty array template <class T> T get_unflagged(const T& array) { if(array.size() == 0) return array; if(array.size() > 1 && array.size() < flags.size()) { throw std::invalid_argument("Array is shorter than flags"); } ivec indices = get_unflagged_indices(); T output(indices.size()); for(int i = 0; i < indices.size(); i++) { if(array.size() > 1) { int index = indices[i]; assert(index < array.size()); output[i] = array[index]; } else output[i] = array[0]; } return output; } Points get_unflagged_points(); /* Same as T subset_valid, except the subsetted indices are returned */ ivec subset_valid(const ivec& indices); /* Merge the flags into the objects flags. If existing flags are 1 but new_flags are * 0, the existing flags are not updated. * @param new_flags Vector of new flags * @param indices The location indices that flags are valid for */ void merge_simple(const ivec& new_flags, ivec indices); /* Merge new flags into the object's flags. If existing flags are 1 but new_flags are * 0, the existing flags are not updated. * @param new_flags Vector of new flags * @param indices The location indices that flags are valid for */ void merge(const ivec& new_flags, ivec indices); }; class not_implemented_exception: public std::logic_error { public: not_implemented_exception() : std::logic_error("Function not yet implemented") { }; }; } #endif
35,843
C++
.h
685
40.943066
309
0.598079
metno/titanlib
30
8
5
LGPL-3.0
9/20/2024, 10:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,794
main.cpp
codearxiv_PCReconstruct/main.cpp
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "GLWidget.h" #include "MainWindow.h" #include "constants.h" #include <Eigen/Dense> #include <QApplication> #include <QDesktopWidget> #include <QSurfaceFormat> #include <QCommandLineParser> #include <QCommandLineOption> #include <QTextBlock> #include <QTextCursor> #include <cstdlib> #include <iostream> void out_of_mem_handler(); int main(int argc, char *argv[]) { srand(2); std::set_new_handler(out_of_mem_handler); Eigen::initParallel(); qRegisterMetaType<size_t>("size_t"); qRegisterMetaType<QTextBlock>("QTextBlock"); qRegisterMetaType<QTextCursor>("QTextCursor"); qRegisterMetaType<SparseApprox>("SparseApprox"); QCoreApplication::setApplicationName("PCReconstruct"); QCoreApplication::setOrganizationName("Peter Beben"); QCoreApplication::setApplicationVersion(QT_VERSION_STR); QCoreApplication::addLibraryPath("./"); QApplication app(argc, argv); QCommandLineParser parser; parser.setApplicationDescription(QCoreApplication::applicationName()); parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption multipleSampleOption("multisample", "Multisampling"); parser.addOption(multipleSampleOption); QCommandLineOption coreProfileOption("coreprofile", "Use core profile"); parser.addOption(coreProfileOption); QCommandLineOption transparentOption("transparent", "Transparent window"); parser.addOption(transparentOption); parser.process(app); QSurfaceFormat fmt; fmt.setDepthBufferSize(24); if (parser.isSet(multipleSampleOption)) fmt.setSamples(4); if (parser.isSet(coreProfileOption)) { fmt.setVersion(3, 2); fmt.setProfile(QSurfaceFormat::CoreProfile); } QSurfaceFormat::setDefaultFormat(fmt); MainWindow mainWindow; GLWidget::setTransparent(parser.isSet(transparentOption)); if (GLWidget::isTransparent()) { mainWindow.setAttribute(Qt::WA_TranslucentBackground); mainWindow.setAttribute(Qt::WA_NoSystemBackground, false); } mainWindow.resize(mainWindow.sizeHint()); // int desktopArea = QApplication::desktop()->width() * // QApplication::desktop()->height(); // int widgetArea = mainWindow.width() * mainWindow.height(); // if (((float)widgetArea / (float)desktopArea) < 0.75f) // mainWindow.show(); // else // mainWindow.showMaximized(); mainWindow.showMaximized(); return app.exec(); } void out_of_mem_handler() { std::cerr << "Unable to allocate memory.\n"; std::abort(); }
2,583
C++
.cpp
72
32.763889
76
0.761597
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,795
MainWindow.cpp
codearxiv_PCReconstruct/MainWindow.cpp
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "MainWindow.h" #include "Window.h" #include "MessageLogger.h" #include "RandomSurfDialog.h" #include "BoundBoxDialog.h" #include "NormalsDialog.h" #include "DecimateDialog.h" #include "SparsifyDialog.h" #include "ReconstructDialog.h" #include "OptionsDialog.h" #include "constants.h" #include <pcl/io/pcd_io.h> //#include <pcl/io/ply_io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <QApplication> #include <QCoreApplication> #include <QToolBar> #include <QDockWidget> #include <QPlainTextEdit> #include <QScrollBar> #include <QFileDialog> #include <QMenuBar> #include <QMenu> #include <QMessageBox> #include <QMainWindow> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { if (objectName().isEmpty()) setObjectName(QString::fromUtf8("MainWindow")); resize(1204, 640); setWindowTitle(QCoreApplication::translate("MainWindow", "PCReconstruct", nullptr)); //------ // Add docks QDockWidget *dock = new QDockWidget("Log Window", this); dock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); logText = new QPlainTextEdit; logText->setReadOnly(true); dock->setWidget(logText); addDockWidget(Qt::RightDockWidgetArea, dock); //------ // Add actions QMenu *fileMenu = menuBar()->addMenu("&File"); QMenu *editMenu = menuBar()->addMenu("&Edit"); QMenu *viewMenu = menuBar()->addMenu("&View"); QMenu *toolsMenu = menuBar()->addMenu("&Tools"); QMenu *helpMenu = menuBar()->addMenu("&Help"); QToolBar *fileToolBar = addToolBar("File"); const QIcon openIcon = QIcon::fromTheme("document-open", QIcon(":/images/open.png")); QAction *openAct = new QAction(openIcon, "&Open...", this); openAct->setShortcuts(QKeySequence::Open); openAct->setStatusTip("Open an existing PCD file"); connect(openAct, &QAction::triggered, this, &MainWindow::open); fileMenu->addAction(openAct); fileToolBar->addAction(openAct); const QIcon saveAsIcon = QIcon::fromTheme("document-save-as", QIcon(":/images/save.png")); QAction *saveAsAct = new QAction(saveAsIcon, "Save &As...", this); saveAsAct->setShortcuts(QKeySequence::SaveAs); saveAsAct->setStatusTip("Save PCD to disk"); connect(saveAsAct, &QAction::triggered, this, &MainWindow::saveAs); fileMenu->addAction(saveAsAct); fileToolBar->addAction(saveAsAct); const QIcon exitIcon = QIcon::fromTheme("application-exit"); QAction *exitAct = fileMenu->addAction(exitIcon, "E&xit", this, &QWidget::close); exitAct->setShortcuts(QKeySequence::Quit); exitAct->setStatusTip("Exit PCReconstruct"); QToolBar *editToolBar = addToolBar("Edit"); const QIcon undoIcon = QIcon::fromTheme("application-undo", QIcon(":/images/undo.png")); QAction *undoAct = new QAction(undoIcon, "&Undo", this); undoAct->setShortcuts(QKeySequence::Undo); undoAct->setStatusTip("Undo"); connect(undoAct, &QAction::triggered, this, &MainWindow::undo); editMenu->addAction(undoAct); editToolBar->addAction(undoAct); viewMenu->addAction(dock->toggleViewAction()); QAction *viewNormsAct = new QAction("&View normals", this); viewNormsAct->setStatusTip("View point cloud normals."); viewNormsAct->setCheckable(true); connect(viewNormsAct, &QAction::triggered, this, &MainWindow::viewGLNorms); viewMenu->addAction(viewNormsAct); QAction *randomSurfAct = new QAction("&Random surface", this); randomSurfAct->setStatusTip( "Sample a point cloud randomly from a random surface"); connect(randomSurfAct, &QAction::triggered, this, &MainWindow::setRandom); toolsMenu->addAction(randomSurfAct); QAction *boundBoxAct = new QAction("&Set bounding box", this); boundBoxAct->setStatusTip( "Set bounding box, inside which operations are performed"); connect(boundBoxAct, &QAction::triggered, this, &MainWindow::setBBox); toolsMenu->addAction(boundBoxAct); QAction *normalsAct = new QAction("&Approx. Normals", this); normalsAct->setStatusTip( "Approximate cloud surface normals"); connect(normalsAct, &QAction::triggered, this, &MainWindow::approxNorms); toolsMenu->addAction(normalsAct); QAction *decimateAct = new QAction("&Decimate", this); decimateAct->setStatusTip("Generate random holes in point cloud"); connect(decimateAct, &QAction::triggered, this, &MainWindow::decimate); toolsMenu->addAction(decimateAct); QAction *sparsifyAct = new QAction("&Sparsify", this); sparsifyAct->setStatusTip("Take a random subset of the point cloud"); connect(sparsifyAct, &QAction::triggered, this, &MainWindow::sparsify); toolsMenu->addAction(sparsifyAct); QAction *reconstructAct = new QAction("&Reconstruct", this); reconstructAct->setStatusTip("Reconstruct point cloud"); connect(reconstructAct, &QAction::triggered, this, &MainWindow::reconstruct); toolsMenu->addAction(reconstructAct); toolsMenu->addSeparator(); QAction *optionsAct = new QAction("&Options", this); optionsAct->setStatusTip("Change app settings."); connect(optionsAct, &QAction::triggered, this, &MainWindow::options); toolsMenu->addAction(optionsAct); QAction *aboutAct = helpMenu->addAction("&About", this, &MainWindow::about); aboutAct->setStatusTip("About"); QAction *aboutQtAct = helpMenu->addAction("About &Qt", qApp, &QApplication::aboutQt); aboutQtAct->setStatusTip("About Qt"); //------ // Central widget msgLogger = new MessageLogger(logText); centralWidget = new Window(this, msgLogger); centralWidget->setObjectName(QString::fromUtf8("centralWidget")); setCentralWidget(centralWidget); connect(msgLogger, &MessageLogger::logTextAppend, this, &MainWindow::appendLogText); connect(msgLogger, &MessageLogger::logTextInsert, this, &MainWindow::insertLogText); connect(this, &MainWindow::cloudChanged, centralWidget, &Window::setCloud); connect(this, &MainWindow::cloudQueried, centralWidget, &Window::getCloud); connect(this, &MainWindow::cloudUndo, centralWidget, &Window::undoCloud); connect(this, &MainWindow::cloudNormsViewGL, centralWidget, &Window::viewGLCloudNorms); connect(this, &MainWindow::cloudSetRandom, centralWidget, &Window::setRandomCloud); connect(this, &MainWindow::cloudSetBBox, centralWidget, &Window::setCloudBBox); connect(this, &MainWindow::cloudApproxNorms, centralWidget, &Window::approxCloudNorms); connect(this, &MainWindow::cloudDecimate, centralWidget, &Window::decimateCloud); connect(this, &MainWindow::cloudSparsify, centralWidget, &Window::sparsifyCloud); connect(this, &MainWindow::cloudReconstruct, centralWidget, &Window::reconstructCloud); connect(this, &MainWindow::pointSizeChanged, centralWidget, &Window::setPointSize); connect(this, &MainWindow::normScaleChanged, centralWidget, &Window::setNormScale); connect(centralWidget, &Window::bBoxFieldsChanged, this, &MainWindow::changeBBoxFields); //------ // Dialogs randomSurfDialog = new RandomSurfDialog(this); boundBoxDialog = new BoundBoxDialog(this); normalsDialog = new NormalsDialog(this); decimateDialog = new DecimateDialog(this); sparsifyDialog = new SparsifyDialog(this); reconstructDialog = new ReconstructDialog(this); optionsDialog = new OptionsDialog(this); //------ QMetaObject::connectSlotsByName(this); } //--------------------------------------------------------- void MainWindow::open() { // QString q_path = QFileDialog::getOpenFileName( // this, "Open File", "", "(*.pcd *.ply)" // ); QString q_path = QFileDialog::getOpenFileName( this, "Open File", "", "PCD (*.pcd)" ); std::string path = q_path.toStdString(); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); int success = 0; try{ // if( q_path.endsWith("pcd", Qt::CaseInsensitive) ){ success = pcl::io::loadPCDFile<pcl::PointXYZ>(path, *cloud); // } // else if( q_path.endsWith("ply", Qt::CaseInsensitive) ){ // success = pcl::io::loadPLYFile<pcl::PointXYZ>(path, *cloud); // if( success == -1 ){ // success = pcl::io::loadPolygonFilePLY<pcl::PointXYZ>(path, *cloud); // } // } // else{ // success = -1; // } } catch (...){ success = -1; } if (success == -1) { appendLogText("Couldn't read PCD file\n"); return; } else{ appendLogText("Opened: " + q_path + "\n"); } emit cloudChanged(cloud); } //--------------------------------------------------------- void MainWindow::saveAs() { QString q_pcdPath = QFileDialog::getSaveFileName( this, "Open File", "", "PCD (*.pcd)" ); std::string pcdPath = q_pcdPath.toStdString(); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); emit cloudQueried(cloud); int success = 0; try{ success = pcl::io::savePCDFile<pcl::PointXYZ>(pcdPath, *cloud); } catch (...){ success = -1; } if (success == -1) { //PCL_ERROR ("Couldn't save PCD file\n"); appendLogText("Couldn't save PCD file\n"); return; } else{ appendLogText("Saved: " + q_pcdPath + "\n"); } } //--------------------------------------------------------- void MainWindow::undo() { emit cloudUndo(); } //--------------------------------------------------------- void MainWindow::viewGLNorms(bool enabled) { emit cloudNormsViewGL(enabled); } //--------------------------------------------------------- void MainWindow::setRandom() { // Show the dialog as modal if(randomSurfDialog->exec() == QDialog::Accepted){ size_t nPoints; bool ok = randomSurfDialog->getFields(nPoints); if(!ok){ badInputMessageBox("All fields should be integers bigger than zero."); return; } emit cloudSetRandom(nPoints); } } //--------------------------------------------------------- void MainWindow::setBBox() { // Show the dialog as modal if(boundBoxDialog->exec() == QDialog::Accepted){ float minBBox[3], maxBBox[3]; bool ok = boundBoxDialog->getFields(minBBox, maxBBox); if(!ok){ badInputMessageBox( QString("All fields should be bigger than zero,\n") + QString("and min. extents less than max. extents.")); return; } emit cloudSetBBox(minBBox, maxBBox); } } //--------------------------------------------------------- void MainWindow::approxNorms() { // Show the dialog as modal if(normalsDialog->exec() == QDialog::Accepted){ int nIters; size_t kNN; bool ok = normalsDialog->getFields(nIters, kNN); if(!ok){ badInputMessageBox( QString("All fields should be bigger than zero.")); return; } emit cloudApproxNorms(nIters, kNN); } } //--------------------------------------------------------- void MainWindow::decimate() { // Show the dialog as modal if(decimateDialog->exec() == QDialog::Accepted){ size_t nHoles, kNN; bool ok = decimateDialog->getFields(nHoles, kNN); if(!ok){ badInputMessageBox("All fields should be integers bigger than zero."); return; } emit cloudDecimate(nHoles,kNN); } } //--------------------------------------------------------- void MainWindow::sparsify() { // Show the dialog as modal if(sparsifyDialog->exec() == QDialog::Accepted){ float percent; bool ok = sparsifyDialog->getFields(percent); if(!ok){ badInputMessageBox("Percent field should be between 0 and 100."); return; } emit cloudSparsify(percent); } } //--------------------------------------------------------- void MainWindow::reconstruct() { // Show the dialog as modal if(reconstructDialog->exec() == QDialog::Accepted){ int kSVDIters; size_t kNN, nfreq, natm, latm, maxNewPoints; float densify; bool looseBBox; SparseApprox method; int ok = reconstructDialog->getFields( kSVDIters, kNN, nfreq, densify, natm, latm, maxNewPoints, looseBBox, method); switch( ok ){ case -1: badInputMessageBox( "Number of iterations field must be bigger than zero."); break; case -2: badInputMessageBox( "Patch size field must be bigger than zero."); break; case -3: badInputMessageBox( "Frequency field must be bigger than zero."); break; case -4: badInputMessageBox( "Densification field must be bigger than zero."); break; case -5: badInputMessageBox( "Number of atoms field must be bigger than zero."); break; case -6: badInputMessageBox( QString("Sparsity constraint must be bigger than zero, ") + QString("and no bigger than the number of atoms field.") ); break; case -7: badInputMessageBox( "Max. new points field should be bigger than zero."); break; default: emit cloudReconstruct( kSVDIters, kNN, nfreq, densify, natm, latm, maxNewPoints, looseBBox, method); } } } //--------------------------------------------------------- void MainWindow::options() { // Show the dialog as modal if(optionsDialog->exec() == QDialog::Accepted){ float pointSize, normScale; bool ok = optionsDialog->getFields(pointSize, normScale); if(!ok){ badInputMessageBox("All field should be greater than zero."); return; } emit pointSizeChanged(pointSize); emit normScaleChanged(normScale); } } //--------------------------------------------------------- void MainWindow::about() { QMessageBox::about(this, "About", QString("PCReconstruct.\n") + QString("Copyright 2019 Piotr (Peter) Beben.\n") + QString("pdbcas@gmail.com\n")); } //--------------------------------------------------------- void MainWindow::badInputMessageBox(const QString& info) { QMessageBox msgBox; msgBox.setText("Invalid input."); msgBox.setInformativeText(info); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.setIcon(QMessageBox::Information); msgBox.exec(); } //--------------------------------------------------------- void MainWindow::changeBBoxFields(float minBBox[3], float maxBBox[3]) { boundBoxDialog->setFields(minBBox, maxBBox); } //--------------------------------------------------------- void MainWindow::appendLogText(const QString& text) { logText->appendPlainText(text); logText->verticalScrollBar()->setValue( logText->verticalScrollBar()->maximum()); } //--------------------------------------------------------- void MainWindow::insertLogText(const QString& text) { logText->undo(); logText->appendPlainText(text); logText->verticalScrollBar()->setValue( logText->verticalScrollBar()->maximum()); } //---------------------------------------------------------
15,305
C++
.cpp
426
31.138498
86
0.645875
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,796
BoundBox.cpp
codearxiv_PCReconstruct/BoundBox.cpp
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "BoundBox.h" #include "Cloud.h" #include "MessageLogger.h" #include "constants.h" #include <qopengl.h> #include <Eigen/Dense> #include <array> using Vector3f = Eigen::Vector3f; constexpr const std::array<GLuint, 24> BoundBox::m_elemGL; //--------------------------------------------------------- BoundBox::BoundBox(const float minBBox[3], const float maxBBox[3], MessageLogger* msgLogger) { m_msgLogger = msgLogger; set(minBBox, maxBBox); } //--------------------------------------------------------- BoundBox::BoundBox(const Cloud& cloud, MessageLogger* msgLogger) { m_msgLogger = msgLogger; set(cloud); } //--------------------------------------------------------- void BoundBox::set(const Cloud& cloud) { float minBBox[3] = {float_infinity, float_infinity, float_infinity}; float maxBBox[3] = {-float_infinity, -float_infinity, -float_infinity}; size_t numPoints = cloud.pointCount(); for(size_t i = 0; i < numPoints; ++i){ Vector3f v = cloud.point(i); for(int j=0; j<3; ++j) { minBBox[j] = std::min(v[j], minBBox[j]); maxBBox[j] = std::max(v[j], maxBBox[j]); } } set(minBBox, maxBBox); } //--------------------------------------------------------- void BoundBox::set(const float minBBox[3], const float maxBBox[3]) { for(int i=0; i<3; ++i) { m_minBBox[i] = minBBox[i]; m_maxBBox[i] = maxBBox[i]; } m_vertCount = 8; if( m_cloud != nullptr ) m_cloud->invalidateCT(); } //--------------------------------------------------------- void BoundBox::pad(float padX, float padY, float padZ) { float padding[3] = {padX, padY, padZ}; for(int j=0; j<3; ++j) { m_minBBox[j] -= padding[j]; m_maxBBox[j] += padding[j]; } if( m_cloud != nullptr ) m_cloud->invalidateCT(); } //--------------------------------------------------------- void BoundBox::rescale(float frac) { for(int j=0; j<3; ++j) { float padding = frac*(m_maxBBox[j] - m_minBBox[j]); m_minBBox[j] -= padding; m_maxBBox[j] += padding; } if( m_cloud != nullptr ) m_cloud->invalidateCT(); } //--------------------------------------------------------- void BoundBox::setParentCloud(Cloud *cloud) { m_cloud = cloud; if( m_cloud != nullptr ) m_cloud->invalidateCT(); } //--------------------------------------------------------- const GLfloat *BoundBox::vertGLData() { for(int i = 0, j = 0; i<m_vertCount; ++i){ for(int k = 0; k < 3; ++k){ m_vertGL[j+k] = (((i>>k)&1) == 0) ? m_minBBox[k] : m_maxBBox[k]; } m_vertGL[j+3] = 1.0f; m_vertGL[j+4] = 0.0f; m_vertGL[j+5] = 0.0f; j += 6; } return static_cast<const GLfloat*>(m_vertGL.data()); } //--------------------------------------------------------- void BoundBox::logMessageBBox() const { if(m_msgLogger != nullptr) { m_msgLogger->logMessage( QString("Bounding box minimum extent:\n") + QString("(") + QString::number(m_minBBox[0]) + QString(", ") + QString::number(m_minBBox[1]) + QString(", ") + QString::number(m_minBBox[2]) + QString(")\n") + QString("Bounding box maximum extent:\n") + QString("(") + QString::number(m_maxBBox[0]) + QString(", ") + QString::number(m_maxBBox[1]) + QString(", ") + QString::number(m_maxBBox[2]) + QString(")\n")); } } //---------------------------------------------------------
3,470
C++
.cpp
111
28.657658
72
0.520602
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,797
MessageLogger.cpp
codearxiv_PCReconstruct/MessageLogger.cpp
#include "MessageLogger.h" #include <QPlainTextEdit> #include <QRecursiveMutex> #include <QScrollBar> MessageLogger::MessageLogger(QObject *parent) : QObject(parent) { } MessageLogger::~MessageLogger() { } void MessageLogger::logMessage(const QString& text, bool append) { QMutexLocker locker(&m_recMutex); if( append ){ emit logTextAppend(text); ++m_lastPos; } else{ emit logTextInsert(text); } } void MessageLogger::logProgress( const QString& msgPrefix, size_t i, size_t n, int infreq, size_t& threshold, size_t& lastPos) { float percent = (100.0f*i)/n; if(percent >= threshold) { QMutexLocker locker(&m_recMutex); bool append = threshold > 0 ? (lastPos < m_lastPos) : true; logMessage(msgPrefix + ": " + QString::number(int(percent)) + "%...", append); threshold += infreq; lastPos = m_lastPos; } }
849
C++
.cpp
34
22.617647
71
0.719801
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,798
GLWidget.cpp
codearxiv_PCReconstruct/GLWidget.cpp
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /**************************************************************************** ** Peter Beben: heavily modified this file for the purpose of point ** cloud visualization in this project. ** Views ALL points in the point cloud without any pruning (so it ** must be small enough to fit into video memory!!). ****************************************************************************/ #include "GLWidget.h" #include "BoundBox.h" #include "Cloud.h" #include "CloudWorker.h" #include "MessageLogger.h" #include "constants.h" #include <Eigen/Core> #include <QMouseEvent> #include <QOpenGLShaderProgram> #include <QCoreApplication> #include <QDebug> #include <QThread> #include <QRecursiveMutex> #include <math.h> //#define SHOW_CLOUD_DBUG bool GLWidget::m_transparent = false; //--------------------------------------------------------- GLWidget::GLWidget(QWidget *parent, MessageLogger* msgLogger) : QOpenGLWidget(parent), m_msgLogger(msgLogger), m_vRot(0), m_program(0), m_rotVect(0.0f,0.0f,0.0f), m_movVect(0.0f,0.0f,0.0f), m_pointSize(5.0f), m_showCloudNorms(false), m_aspectRatio(1.0f), m_farPlane(100.0f), m_nearPlane(0.01f), m_modelSize(1.0f), m_cloudVbo(QOpenGLBuffer::VertexBuffer), m_cloudBBoxVbo(QOpenGLBuffer::VertexBuffer), m_cloudBBoxEbo(QOpenGLBuffer::IndexBuffer), m_cloudNormsVbo(QOpenGLBuffer::VertexBuffer), m_cloudDebugVbo(QOpenGLBuffer::VertexBuffer), m_cloud(msgLogger, parent), m_cloudBBox(msgLogger) { m_core = QSurfaceFormat::defaultFormat().profile() == QSurfaceFormat::CoreProfile; // --transparent causes the clear color to be transparent. Therefore, on systems that // support it, the widget will become transparent apart from the cloud. if (m_transparent) { QSurfaceFormat fmt = format(); fmt.setAlphaBufferSize(8); setFormat(fmt); } m_cloudThread = new QThread(this); m_cloudWorker = new CloudWorker(m_cloud); m_cloudWorker->moveToThread(m_cloudThread); connect(this, &GLWidget::cloudApproxNorms, m_cloudWorker, &CloudWorker::approxCloudNorms); connect(this, &GLWidget::cloudDecimate, m_cloudWorker, &CloudWorker::decimateCloud); connect(this, &GLWidget::cloudSparsify, m_cloudWorker, &CloudWorker::sparsifyCloud); connect(this, &GLWidget::cloudReconstruct, m_cloudWorker, &CloudWorker::reconstructCloud); connect(m_cloudWorker, &CloudWorker::finished, this, &GLWidget::updateCloud); connect(m_cloudThread, &QThread::finished, m_cloudWorker, &QObject::deleteLater); m_cloudThread->start(); } //--------------------------------------------------------- GLWidget::~GLWidget() { m_cloudThread->quit(); m_cloudThread->wait(); // delete m_cloudThread; delete m_cloudWorker; cleanup(); } //--------------------------------------------------------- QSize GLWidget::minimumSizeHint() const { return QSize(50, 50); } //--------------------------------------------------------- QSize GLWidget::sizeHint() const { return QSize(400, 400); } //--------------------------------------------------------- static void qNormalizeAngle(int &angle) { while (angle < 0) angle += 360 * 16; while (angle > 360 * 16) angle -= 360 * 16; } //--------------------------------------------------------- void GLWidget::setVectRotation(int angle, QVector3D v) { qNormalizeAngle(angle); m_vRot = angle; m_rotVect = v; m_movVect = QVector3D(0.0f,0.0f,0.0f); emit vectRotationChanged(angle, v); update(); } //--------------------------------------------------------- void GLWidget::setVectTranslation(QVector3D v) { m_vRot = 0.0f; m_rotVect = QVector3D(0.0f,0.0f,0.0f); m_movVect = v; emit vectTranslationChanged(v); update(); } //--------------------------------------------------------- void GLWidget::cleanup() { if (m_program == nullptr) return; makeCurrent(); m_cloudVbo.destroy(); m_cloudNormsVbo.destroy(); m_cloudBBoxVbo.destroy(); m_cloudDebugVbo.destroy(); delete m_program; m_program = 0; doneCurrent(); } //--------------------------------------------------------- static const char *vertexShaderSourceCore = "#version 150\n" "in vec4 vertex;\n" "in vec3 normal;\n" "out vec3 vert;\n" "out vec3 vertNormal;\n" "uniform mat4 projMatrix;\n" "uniform mat4 mvMatrix;\n" "uniform mat3 normalMatrix;\n" "uniform float pointSize;\n" "void main() {\n" " vert = vertex.xyz;\n" " vertNormal = normalMatrix * normal;\n" " gl_Position = projMatrix * mvMatrix * vertex;\n" " gl_PointSize = pointSize/(0.1+10.0*abs(gl_Position.z));\n" // " gl_PointSize = 50.0;\n" "}\n"; static const char *fragmentShaderSourceCore = "#version 150\n" "in highp vec3 vert;\n" "in highp vec3 vertNormal;\n" "out highp vec4 fragColor;\n" "uniform highp vec3 lightPos;\n" "uniform vec3 vertColor;\n" "void main() {\n" " highp vec3 L = normalize(lightPos - vert);\n" " highp float NL = max(abs(dot(normalize(vertNormal), L)), 0.0);\n" " highp vec3 color = vertColor;\n" " highp vec3 col = clamp(color * (0.3 + 0.8*NL), 0.0, 1.0);\n" // " highp vec3 col = color;\n" " fragColor = vec4(col, 1.0);\n" "}\n"; static const char *vertexShaderSource = "attribute vec4 vertex;\n" "attribute vec3 normal;\n" "varying vec3 vert;\n" "varying vec3 vertNormal;\n" "uniform mat4 projMatrix;\n" "uniform mat4 mvMatrix;\n" "uniform mat3 normalMatrix;\n" "uniform float pointSize;\n" "void main() {\n" " vert = vertex.xyz;\n" " vertNormal = normalMatrix * normal;\n" " gl_Position = projMatrix * mvMatrix * vertex;\n" " gl_PointSize = pointSize/(0.1+10.0*abs(gl_Position.z));\n" // " gl_PointSize = 500.0;\n" "}\n"; static const char *fragmentShaderSource = "varying highp vec3 vert;\n" "varying highp vec3 vertNormal;\n" "uniform highp vec3 lightPos;\n" "uniform highp vec3 vertColor;\n" "void main() {\n" " highp vec3 L = normalize(lightPos - vert);\n" " highp float NL = max(abs(dot(normalize(vertNormal), L)), 0.0);\n" " highp vec3 color = vertColor;\n" " highp vec3 col = clamp(color * (0.3 + 0.8*NL), 0.0, 1.0);\n" // " highp vec3 col = color;\n" " gl_FragColor = vec4(col, 1.0);\n" "}\n"; //--------------------------------------------------------- void GLWidget::initializeGL() { connect(context(), &QOpenGLContext::aboutToBeDestroyed, this, &GLWidget::cleanup); initializeOpenGLFunctions(); glClearColor(0, 0, 0, m_transparent ? 0 : 1); m_program = new QOpenGLShaderProgram; m_program->addShaderFromSourceCode( QOpenGLShader::Vertex, m_core ? vertexShaderSourceCore : vertexShaderSource); m_program->addShaderFromSourceCode( QOpenGLShader::Fragment, m_core ? fragmentShaderSourceCore : fragmentShaderSource); m_program->bindAttributeLocation("vertex", 0); m_program->bindAttributeLocation("normal", 1); m_program->link(); m_program->bind(); m_projMatrixLoc = m_program->uniformLocation("projMatrix"); m_mvMatrixLoc = m_program->uniformLocation("mvMatrix"); m_normalMatrixLoc = m_program->uniformLocation("normalMatrix"); m_lightPosLoc = m_program->uniformLocation("lightPos"); m_colorLoc = m_program->uniformLocation("vertColor"); m_pointSizeLoc = m_program->uniformLocation("pointSize"); m_cloudVao.create(); QOpenGLVertexArrayObject::Binder vaoBinderCloud(&m_cloudVao); setGLCloud(); m_cloudBBoxVao.create(); QOpenGLVertexArrayObject::Binder vaoBinderCloudBBox(&m_cloudBBoxVao); setGLBBox(m_cloudBBox, m_cloudBBoxVbo, m_cloudBBoxEbo); m_cloudNormsVao.create(); QOpenGLVertexArrayObject::Binder vaoBinderCloudNorms(&m_cloudNormsVao); setGLCloudNorms(1.0f); #ifdef SHOW_CLOUD_DBUG m_cloudDebugVao.create(); QOpenGLVertexArrayObject::Binder vaoBinderCloudDebug(&m_cloudDebugVao); setGLCloudDebug(); #endif setGLView(); m_program->setUniformValue(m_lightPosLoc, QVector3D(0, 0, 2*m_modelSize)); m_program->release(); } //--------------------------------------------------------- void GLWidget::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_PROGRAM_POINT_SIZE); m_world.rotate(-m_vRot / 8.0f, m_rotVect); m_camera.translate(-m_movVect / 2000.0f); m_program->bind(); m_program->setUniformValue(m_projMatrixLoc, m_proj); m_program->setUniformValue(m_mvMatrixLoc, m_camera * m_world.transposed()); QMatrix3x3 normalMatrix = m_world.normalMatrix(); m_program->setUniformValue(m_normalMatrixLoc, normalMatrix); m_program->setUniformValue(m_pointSizeLoc, m_pointSize); m_program->setUniformValue(m_lightPosLoc, QVector3D(0, 0, 2*m_modelSize)); size_t npoints = m_cloud.pointCount(); size_t npointsOrig = m_cloud.pointCountOrig(); size_t npointsNew = npoints - npointsOrig; m_program->setUniformValue(m_colorLoc, QVector3D(0.4f, 1.0f, 0.0f)); QOpenGLVertexArrayObject::Binder vaoBinder(&m_cloudVao); glDrawArrays(GL_POINTS, 0, npointsOrig); if( npointsNew > 0 ){ m_program->setUniformValue(m_colorLoc, QVector3D(1.0f, 0.2f, 1.0f)); glDrawArrays(GL_POINTS, npointsOrig-1, npointsNew); } m_program->setUniformValue(m_colorLoc, QVector3D(1.0f, 0.5f, 0.0f)); QOpenGLVertexArrayObject::Binder vaoBinder2(&m_cloudBBoxVao); int idxCount = (m_cloudBBox.vertCount()==0) ? 0 : 24; glDrawElements(GL_LINES, idxCount, GL_UNSIGNED_INT, 0); // glDrawElements(GL_LINES, idxCount, GL_UNSIGNED_INT, m_cloudBBox.elemGLData()); if( m_showCloudNorms ){ m_program->setUniformValue(m_colorLoc, QVector3D(1.0f, 0.0f, 1.0f)); QOpenGLVertexArrayObject::Binder vaoBinder3(&m_cloudNormsVao); glDrawArrays(GL_LINES, 0, 2*npoints); } #ifdef SHOW_CLOUD_DBUG m_program->setUniformValue(m_colorLoc, QVector3D(0.0f, 0.0f, 0.5f)); QOpenGLVertexArrayObject::Binder vaoBinder4(&m_cloudDebugVao); glDrawArrays(GL_LINES, 0, 2*m_cloud.debugCount()); #endif m_program->release(); } //--------------------------------------------------------- void GLWidget::resizeGL(int w, int h) { m_aspectRatio = float(w)/h; m_proj.setToIdentity(); m_proj.perspective(45.0f, m_aspectRatio, m_nearPlane, m_farPlane); } //--------------------------------------------------------- void GLWidget::setGLView() { m_rotVect = QVector3D(0.0f,0.0f,0.0f); m_movVect = QVector3D(0.0f,0.0f,0.0f); m_nearPlane = 1e-5*m_modelSize; m_farPlane = 100.0f*m_modelSize; m_proj.setToIdentity(); m_proj.perspective(45.0f, m_aspectRatio, m_nearPlane, m_farPlane); m_world.setToIdentity(); m_camera.setToIdentity(); m_camera.translate(0, 0, -m_modelSize); } //--------------------------------------------------------- void GLWidget::setGLCloud() { size_t npoints = m_cloud.pointCount(); makeCurrent(); // Setup our vertex buffer object for point cloud. m_cloudVbo.create(); m_cloudVbo.bind(); m_cloudVbo.allocate( m_cloud.vertGLData(), 6*npoints*sizeof(GLfloat)); // Store the vertex attribute bindings for the program. setupVertexAttribs(m_cloudVbo); } //--------------------------------------------------------- void GLWidget::setGLCloudNorms(float scale) { size_t npoints = m_cloud.pointCount(); makeCurrent(); m_cloudNormsVbo.create(); m_cloudNormsVbo.bind(); m_cloudNormsVbo.allocate( m_cloud.normGLData(scale), 12*npoints*sizeof(GLfloat)); setupVertexAttribs(m_cloudNormsVbo); } //--------------------------------------------------------- void GLWidget::setGLCloudDebug() { size_t ndebug = m_cloud.debugCount(); makeCurrent(); m_cloudDebugVbo.create(); m_cloudDebugVbo.bind(); m_cloudDebugVbo.allocate( m_cloud.debugGLData(), 12*ndebug*sizeof(GLfloat)); setupVertexAttribs(m_cloudDebugVbo); } //--------------------------------------------------------- void GLWidget::setGLBBox( BoundBox bBox, QOpenGLBuffer vbo, QOpenGLBuffer ebo) { makeCurrent(); vbo.create(); vbo.bind(); vbo.allocate(bBox.vertGLData(), 6*bBox.vertCount()*sizeof(GLfloat)); ebo.create(); ebo.bind(); int idxCount = (bBox.vertCount()==0) ? 0 : 24; ebo.allocate(bBox.elemGLData(), idxCount*sizeof(GLuint)); setupVertexAttribs(vbo); } //--------------------------------------------------------- void GLWidget::setupVertexAttribs(QOpenGLBuffer vbo) { vbo.bind(); QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions(); f->glEnableVertexAttribArray(0); f->glEnableVertexAttribArray(1); f->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6*sizeof(GLfloat), 0); f->glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), reinterpret_cast<void *>(3 * sizeof(GLfloat))); vbo.release(); } //--------------------------------------------------------- void GLWidget::mousePressEvent(QMouseEvent *event) { m_lastMousePos = event->pos(); //*** // if(event->buttons() & Qt::MidButton){ // setRandomCloud(35000); // } } //--------------------------------------------------------- void GLWidget::mouseMoveEvent(QMouseEvent *event) { int dx = event->x() - m_lastMousePos.x(); int dy = event->y() - m_lastMousePos.y(); bool leftButton = (event->buttons() & Qt::LeftButton); bool rightButton = (event->buttons() & Qt::RightButton); if ( leftButton && rightButton ) { float norm = frobeniusNorm4x4(m_camera); setVectTranslation(QVector3D(-norm*dx,norm*dy,0.0f)); } else if ( leftButton ) { int angle = abs(dx) + abs(dy); setVectRotation(angle, QVector3D(dy,dx,0.0f)); } else if ( rightButton ) { int angle = abs(dx) + abs(dy); setVectRotation(angle, QVector3D(dy,0.0f,-dx)); } m_lastMousePos = event->pos(); } //--------------------------------------------------------- void GLWidget::wheelEvent(QWheelEvent *event) { float norm = frobeniusNorm4x4(m_camera) + 1e-3; setVectTranslation(QVector3D(0.0f,0.0f,norm*event->delta())); } //--------------------------------------------------------- void GLWidget::setCloud(CloudPtr cloud) { QMutexLocker locker(&m_recMutex); m_cloud.fromPCL(cloud); updateCloud(true); setGLView(); } //--------------------------------------------------------- void GLWidget::setRandomCloud(size_t nPoints) { QMutexLocker locker(&m_recMutex); Eigen::VectorXf C = Eigen::VectorXf::Random(5); Eigen::VectorXf D = Eigen::VectorXf::Random(8); Eigen::VectorXf E = Eigen::VectorXf::Random(5); Eigen::VectorXf F = Eigen::VectorXf::Random(8); auto heightFun = [&C, &D, &E, &F](float xu, float xv){ float pu = 15*xu, pv = 15*xv; float height = C(0)*cos(D(0)*pu) + C(1)*cos(D(1)*pv) + C(2)*cos(D(2)*pu)*cos(D(3)*pu) + C(3)*cos(D(4)*pu)*cos(D(5)*pv) + C(4)*cos(D(6)*pv)*cos(D(7)*pv) + E(0)*sin(F(0)*pu) + E(1)*sin(F(1)*pv) + E(2)*sin(F(2)*pu)*sin(F(3)*pu) + E(3)*sin(F(4)*pu)*sin(F(5)*pv) + E(4)*sin(F(6)*pv)*sin(F(7)*pv); return 0.05f*height; }; Eigen::Vector3f norm(0.0f,1.0f,0.0f); m_cloud.fromRandomPlanePoints(norm, nPoints, heightFun); updateCloud(true); setGLView(); } //--------------------------------------------------------- void GLWidget::getCloud(CloudPtr& cloud) { QMutexLocker locker(&m_recMutex); m_cloud.toPCL(cloud); } //--------------------------------------------------------- void GLWidget::undoCloud() { QMutexLocker locker(&m_recMutex); m_cloud.restore(); updateCloud(false); } //--------------------------------------------------------- void GLWidget::setCloudBBox(float minBBox[3], float maxBBox[3]) { QMutexLocker locker(&m_recMutex); m_cloudBBox.set(minBBox, maxBBox); m_cloudBBox.logMessageBBox(); emit bBoxFieldsChanged(minBBox, maxBBox); m_cloud.setBoundBox(&m_cloudBBox); setGLBBox(m_cloudBBox, m_cloudBBoxVbo, m_cloudBBoxEbo); update(); } //--------------------------------------------------------- void GLWidget::viewGLCloudNorms(bool enabled) { m_showCloudNorms = enabled; update(); } //--------------------------------------------------------- void GLWidget::updateCloud(bool updateBBox) { QMutexLocker locker(&m_recMutex); if( updateBBox ){ float minBBox[3], maxBBox[3]; m_cloudBBox.set(m_cloud); m_cloudBBox.rescale(0.01f); m_cloudBBox.logMessageBBox(); m_cloudBBox.getExtents(minBBox, maxBBox); emit bBoxFieldsChanged(minBBox, maxBBox); m_cloud.setBoundBox(&m_cloudBBox); m_modelSize = m_cloudBBox.diagonalSize(); setGLBBox(m_cloudBBox, m_cloudBBoxVbo, m_cloudBBoxEbo); } setGLCloud(); setGLCloudNorms(1e-2*m_modelSize); #ifdef SHOW_CLOUD_DBUG setGLCloudDebug(); #endif update(); } //--------------------------------------------------------- float GLWidget::frobeniusNorm4x4(QMatrix4x4 M) { float normSq = M(0,0)*M(0,0) + M(1,0)*M(1,0) + M(2,0)*M(2,0) + M(3,0)*M(3,0) + M(0,1)*M(0,1) + M(1,1)*M(1,1) + M(2,1)*M(2,1) + M(3,1)*M(3,1) + M(0,2)*M(0,2) + M(1,2)*M(1,2) + M(2,2)*M(2,2) + M(3,2)*M(3,2) + M(0,3)*M(0,3) + M(1,3)*M(1,3) + M(2,3)*M(2,3) + M(3,3)*M(3,3); return sqrt(normSq); } //---------------------------------------------------------
19,952
C++
.cpp
554
32.472924
87
0.624909
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,799
CloudWorker.cpp
codearxiv_PCReconstruct/CloudWorker.cpp
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "CloudWorker.h" #include "Cloud.h" #include "constants.h" //------------------------------------------------------------------------- CloudWorker::CloudWorker(Cloud& cloud, QObject *parent) : QObject(parent) { m_cloud = &cloud; } //------------------------------------------------------------------------- CloudWorker::~CloudWorker() { } //------------------------------------------------------------------------- void CloudWorker::approxCloudNorms(int nIters, size_t kNN) { if(m_cloud->pointCount() == 0) return; m_cloud->approxCloudNorms(nIters, kNN); emit finished(false); } //------------------------------------------------------------------------- void CloudWorker::decimateCloud(size_t nHoles, size_t kNN) { if(m_cloud->pointCount() == 0) return; m_cloud->backup(); m_cloud->decimate(nHoles, kNN); emit finished(false); } //------------------------------------------------------------------------- void CloudWorker::sparsifyCloud(float percent) { if(m_cloud->pointCount() == 0) return; m_cloud->backup(); m_cloud->sparsify(percent); emit finished(false); } //------------------------------------------------------------------------- void CloudWorker::reconstructCloud( int kSVDIters, size_t kNN, size_t nfreq, float densify, size_t natm, size_t latm, size_t maxNewPoints, bool looseBBox, SparseApprox method) { if(m_cloud->pointCount() == 0) return; m_cloud->backup(); m_cloud->reconstruct( kSVDIters, kNN, nfreq, densify, natm, latm, maxNewPoints, looseBBox, method); emit finished(false); } //-------------------------------------------------------------------------
1,806
C++
.cpp
53
32.169811
75
0.489349
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,800
Window.cpp
codearxiv_PCReconstruct/Window.cpp
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "MainWindow.h" #include "Window.h" #include "GLWidget.h" #include "MessageLogger.h" #include <QVBoxLayout> #include <QHBoxLayout> #include <QKeyEvent> #include <QPushButton> #include <QDesktopWidget> #include <QApplication> #include <QMessageBox> #include <QMainWindow> Window::Window(QMainWindow *mw, MessageLogger* msgLogger) : mainWindow(mw), m_msgLogger(msgLogger) { glWidget = new GLWidget(this, msgLogger); QWidget *w = new QWidget; //QVBoxLayout *mainLayout = new QVBoxLayout; QHBoxLayout *container = new QHBoxLayout; //LogWindow *logWindow = new LogWindow; container->addWidget(glWidget); w->setLayout(container); //mainLayout->addWidget(w); //setLayout(mainLayout); setLayout(container); setWindowTitle("PCReconstruct"); connect(this, &Window::cloudChanged, glWidget, &GLWidget::setCloud); connect(this, &Window::cloudQueried, glWidget, &GLWidget::getCloud); connect(this, &Window::cloudUndo, glWidget, &GLWidget::undoCloud); connect(this, &Window::cloudNormsViewGL, glWidget, &GLWidget::viewGLCloudNorms); connect(this, &Window::cloudSetRandom, glWidget, &GLWidget::setRandomCloud); connect(this, &Window::cloudSetBBox, glWidget, &GLWidget::setCloudBBox); connect(this, &Window::cloudApproxNorms, glWidget, &GLWidget::approxCloudNorms); connect(this, &Window::cloudDecimate, glWidget, &GLWidget::decimateCloud); connect(this, &Window::cloudSparsify, glWidget, &GLWidget::sparsifyCloud); connect(this, &Window::cloudReconstruct, glWidget, &GLWidget::reconstructCloud); connect(this, &Window::pointSizeChanged, glWidget, &GLWidget::setPointSize); connect(this, &Window::normScaleChanged, glWidget, &GLWidget::setNormScale); connect(glWidget, &GLWidget::bBoxFieldsChanged, this, &Window::changeBBoxFields); } void Window::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Escape) close(); else QWidget::keyPressEvent(e); }
4,571
C++
.cpp
109
38.431193
78
0.7149
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,801
Cloud.cpp
codearxiv_PCReconstruct/Cloud.cpp
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "Cloud.h" #include "constants.h" #include "MessageLogger.h" #include "BoundBox.h" #include "cloud_normal.h" #include "cosine_transform.h" #include "rotations.h" #include "Plane.h" #include "MatchingPursuit.h" #include "OrthogonalPursuit.h" #include "ksvd_dct2D.h" #include "Cover_Tree.h" #include "CoverTreePoint.h" #include <Eigen/Core> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <qopengl.h> #include <QCoreApplication> #include <QRecursiveMutex> #include <omp.h> #include <queue> #include <numeric> #include <random> #include <iterator> #include <algorithm> #include <functional> #include <iostream> #include <ctime> using std::max; using std::min; using std::abs; using std::floor; using Eigen::Index; using Eigen::Vector2f; using Eigen::Vector3f; using Eigen::VectorXf; using Eigen::Matrix3f; using Eigen::MatrixXf; using Eigen::MatrixXi; using MapMtrxf = Eigen::Map<MatrixXf, ALIGNEDX>; using MapMtrxi = Eigen::Map<MatrixXi, ALIGNEDX>; template<typename T> using aligned = Eigen::aligned_allocator<T>; template<typename T> using vector = std::vector<T>; template<typename T> using queue = std::queue<T>; using vectorfa = std::vector<float, aligned<float>>; using vectoria = std::vector<int, aligned<int>>; typedef pcl::PointCloud<pcl::PointXYZ>::Ptr CloudPtr; //--------------------------------------------------------- Cloud::Cloud(MessageLogger* msgLogger, QObject *parent) : QObject(parent), m_CT(nullptr), m_msgLogger(msgLogger), m_bBox(nullptr) { m_cloud.reserve(2500); m_norms.reserve(2500); m_vertGL.reserve(2500 * 6); } //--------------------------------------------------------- Cloud::~Cloud() { delete m_CT; } //--------------------------------------------------------- const GLfloat* Cloud::vertGLData() { m_vertGL.resize(6 * m_cloud.size()); for(size_t i=0, j=0; i < m_cloud.size(); ++i){ m_vertGL[j] = m_cloud[i][0]; m_vertGL[j+1] = m_cloud[i][1]; m_vertGL[j+2] = m_cloud[i][2]; m_vertGL[j+3] = m_norms[i][0]; m_vertGL[j+4] = m_norms[i][1]; m_vertGL[j+5] = m_norms[i][2]; j += 6; } return static_cast<const GLfloat*>(m_vertGL.data()); } //--------------------------------------------------------- const GLfloat* Cloud::normGLData(float scale) { m_normGL.resize(12 * m_cloud.size()); for(size_t i=0, j=0; i < m_cloud.size(); ++i){ m_normGL[j] = m_cloud[i][0] - scale*m_norms[i][0]; m_normGL[j+1] = m_cloud[i][1] - scale*m_norms[i][1]; m_normGL[j+2] = m_cloud[i][2] - scale*m_norms[i][2]; m_normGL[j+3] = m_norms[i][0]; m_normGL[j+4] = m_norms[i][1]; m_normGL[j+5] = m_norms[i][2]; m_normGL[j+6] = m_cloud[i][0] + scale*m_norms[i][0]; m_normGL[j+7] = m_cloud[i][1] + scale*m_norms[i][1]; m_normGL[j+8] = m_cloud[i][2] + scale*m_norms[i][2]; m_normGL[j+9] = m_norms[i][0]; m_normGL[j+10] = m_norms[i][1]; m_normGL[j+11] = m_norms[i][2]; j += 12; } return static_cast<const GLfloat*>(m_normGL.data()); } //--------------------------------------------------------- const GLfloat* Cloud::debugGLData() { Vector3f norm(0.0f, 0.0f, 1.0f); m_debugGL.resize(12 * m_debug.size()); for(size_t i=0, j=0; i < m_debug.size(); ++i){ Vector3f p = m_debug[i].first; Vector3f q = m_debug[i].second; m_debugGL[j] = p(0); m_debugGL[j+1] = p(1); m_debugGL[j+2] = p(2); m_debugGL[j+3] = norm(0); m_debugGL[j+4] = norm(1); m_debugGL[j+5] = norm(2); m_debugGL[j+6] = q(0); m_debugGL[j+7] = q(1); m_debugGL[j+8] = q(2); m_debugGL[j+9] = norm(0); m_debugGL[j+10] = norm(1); m_debugGL[j+11] = norm(2); j += 12; } return static_cast<const GLfloat*>(m_debugGL.data()); } //--------------------------------------------------------- void Cloud::clear() { QMutexLocker locker(&m_recMutex); m_cloud.clear(); m_norms.clear(); m_cloud_bak.clear(); m_norms_bak.clear(); delete m_CT; m_CT = nullptr; m_CTStale = true; m_bBox = nullptr; m_npointsOrig = 0; } //--------------------------------------------------------- void Cloud::backup() { QMutexLocker locker(&m_recMutex); m_cloud_bak = m_cloud; m_norms_bak = m_norms; } //--------------------------------------------------------- void Cloud::restore() { QMutexLocker locker(&m_recMutex); std::swap(m_cloud, m_cloud_bak); std::swap(m_norms, m_norms_bak); m_npointsOrig = m_cloud.size(); delete m_CT; m_CT = nullptr; m_CTStale = true; } //--------------------------------------------------------- void Cloud::setBoundBox(BoundBox *bBox) { QMutexLocker locker(&m_recMutex); m_bBox = bBox; bBox->setParentCloud(this); m_CTStale = true; } //--------------------------------------------------------- void Cloud::invalidateCT() { QMutexLocker locker(&m_recMutex); m_CTStale = true; } //--------------------------------------------------------- void Cloud::fromPCL(CloudPtr cloud) { QMutexLocker locker(&m_recMutex); clear(); Vector3f n(0.0f, 0.0f, 1.0f); size_t npoints = cloud->points.size(); float centx = 0.0f; float centy = 0.0f; float centz = 0.0f; for(size_t i = 0; i < npoints; ++i){ centx = centx + cloud->points[i].x; centy = centy + cloud->points[i].y; centz = centz + cloud->points[i].z; } centx = centx/float(npoints); centy = centy/float(npoints); centz = centz/float(npoints); for(size_t i = 0; i < npoints; ++i){ Vector3f v; v(0) = cloud->points[i].x - centx; v(1) = cloud->points[i].y - centy; v(2) = cloud->points[i].z - centz; addPoint(v, n); //m_cloud.push_back(v); //m_norms.push_back(n); } if(m_msgLogger != nullptr) { m_msgLogger->logMessage(QString::number(npoints) + " points loaded.\n"); } m_npointsOrig = npoints; } //--------------------------------------------------------- void Cloud::toPCL(CloudPtr& cloud) { QMutexLocker locker(&m_recMutex); for(size_t i = 0; i < m_cloud.size(); ++i){ pcl::PointXYZ v; v.x = m_cloud[i][0]; v.y = m_cloud[i][1]; v.z = m_cloud[i][2]; cloud->push_back(v); } } //--------------------------------------------------------- void Cloud::fromRandomPlanePoints( Vector3f norm, size_t npoints, const std::function<float(float xu, float xv)> heightFun) { QMutexLocker locker(&m_recMutex); clear(); Plane plane(Vector3f(0.0f,0.0f,0.0f), norm); Vector3f u, v; plane.getUVAxes(u,v); for(size_t i = 0; i < npoints; ++i){ Vector2f uvScale = Vector2f::Random(); Vector3f q = uvScale(0)*u + uvScale(1)*v; if( heightFun != nullptr ){ float normScale = heightFun(uvScale(0), uvScale(1)); q = q + normScale*norm; } addPoint(q, norm); } if(m_msgLogger != nullptr) { m_msgLogger->logMessage(QString::number(npoints) + " points created.\n"); } m_npointsOrig = npoints; } //--------------------------------------------------------- size_t Cloud::addPoint(const Vector3f& v, const Vector3f& n, bool threadSafe) { if ( threadSafe ) m_recMutex.lock(); size_t idx = m_cloud.size(); m_cloud.push_back(v); m_norms.push_back(n); if( m_CT != nullptr ) { CoverTreePoint<Vector3f> cp(v, idx); m_CT->insert(cp); ++m_npointsCT; } if ( threadSafe ) m_recMutex.unlock(); return idx; } //--------------------------------------------------------- void Cloud::replacePoint( size_t idx, const Vector3f& v, const Vector3f& n, bool threadSafe) { if ( threadSafe ) m_recMutex.lock(); assert(idx < m_cloud.size()); m_cloud[idx] = v; m_norms[idx] = n; if( m_CT != nullptr ) { CoverTreePoint<Vector3f> cp(v, idx); m_CT->remove(cp); m_CT->insert(cp); } if ( threadSafe ) m_recMutex.unlock(); } //--------------------------------------------------------- void Cloud::pointKNN( const Vector3f& p, size_t kNN, vector<CoverTreePoint<Vector3f>>& neighs) const { assert(m_CT != nullptr); CoverTreePoint<Vector3f> cp(p, 0); neighs = m_CT->kNearestNeighbors(cp, kNN); } //--------------------------------------------------------- Eigen::Vector3f Cloud::approxNorm( const Vector3f& p, int iters, const vector<CoverTreePoint<Vector3f>>& neighs, vector<Vector3f>& vneighs, vector<Vector3f>& vwork) const { static const Vector3f origin(0.0f,0.0f,0.0f); assert(m_CT != nullptr); getNeighVects(p, neighs, vneighs); return cloud_normal(origin, vneighs, iters, vwork); } //--------------------------------------------------------- void Cloud::getNeighVects( const Vector3f& p, const vector<CoverTreePoint<Vector3f>>& neighs, vector<Vector3f>& vneighs) const { vneighs.reserve(neighs.size()); vneighs.resize(0); typename vector<CoverTreePoint<Vector3f>>::const_iterator it; for(it=neighs.begin(); it!=neighs.end(); ++it){ size_t idx = it->getId(); Vector3f v = m_cloud[idx] - p; vneighs.push_back(v); } } //--------------------------------------------------------- void Cloud::buildSpatialIndex(bool useBBox) { QMutexLocker locker(&m_recMutex); if( m_CT != nullptr ) { delete m_CT; m_CT = nullptr; } m_CT = new CoverTree<CoverTreePoint<Vector3f>>(); bool useBBox2 = (m_bBox != nullptr) && useBBox; size_t npoints = m_cloud.size(); size_t threshold = 0, lastPos = 0; m_npointsCT = 0; for(size_t i = 0; i < npoints; ++i){ // Log progress if(m_msgLogger != nullptr) { // QCoreApplication::processEvents(); m_msgLogger->logProgress( "Building cloud spatial index", i+1, npoints, 5, threshold, lastPos); } Vector3f p = m_cloud[i]; if( useBBox2 ) if( !m_bBox->pointInBBox(p) ) continue; CoverTreePoint<Vector3f> cp(p, i); m_CT->insert(cp); ++m_npointsCT; } m_CTStale = false; } //--------------------------------------------------------- void Cloud::approxCloudNorms(int iters, size_t kNN) { QMutexLocker locker(&m_recMutex); bool useBBox = (m_bBox != nullptr); Index npoints = m_cloud.size(); size_t threshold = 0, lastPos = 0, progress = 0; if( m_CTStale ) buildSpatialIndex(); // std::clock_t c_start = std::clock();//*** const bool useOpenMP = true; #pragma omp parallel if(useOpenMP) default(shared) { vector<CoverTreePoint<Vector3f>> neighs; vector<Vector3f> vneighs; vector<Vector3f> vwork; #pragma omp for schedule(dynamic) for(Index i=0; i < npoints; ++i){ Vector3f p = m_cloud[i]; if( useBBox ) if( !m_bBox->pointInBBox(p) ) continue; CoverTreePoint<Vector3f> cp(p, 0); neighs = m_CT->kNearestNeighbors(cp, kNN); m_norms[i] = approxNorm(p, iters, neighs, vneighs, vwork); // Log progress if(m_msgLogger != nullptr) { #pragma omp atomic ++progress; m_msgLogger->logProgress( "Building cloud normals", progress, npoints, 5, threshold, lastPos); } } } //Parallel // std::clock_t c_end = std::clock();//*** // double time_elapsed_ms = 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC; // std::cout << "\nCPU time used: " << time_elapsed_ms << " ms\n" << std::endl; m_msgLogger->logMessage("Building cloud normals: 100%...", false); } //--------------------------------------------------------- void Cloud::decimate(size_t nHoles, size_t kNN) { QMutexLocker locker(&m_recMutex); size_t npoints = m_cloud.size(); if(npoints == 0 || nHoles <= 0 || kNN <= 0) return; vector<CoverTreePoint<Vector3f>> neighs; vector<bool> deletedPoint(npoints, false); size_t threshold = 0, lastPos = 0; size_t ndeleted = 0; bool useBBox = (m_bBox != nullptr); if( m_CTStale && kNN > 1 ) buildSpatialIndex(); QString actionStr = kNN > 1 ? "Decimating" : "Sparsifying"; //std::random_device rd; //std::mt19937 mt(rd()); vector<size_t> shuffled; shuffled.reserve(npoints); for(size_t idx=0; idx < npoints; ++idx){ if( useBBox ){ if( !m_bBox->pointInBBox(m_cloud[idx]) ) continue; } shuffled.push_back(idx); } std::random_shuffle(shuffled.begin(), shuffled.end()); size_t nSubset = min(nHoles,shuffled.size()); for(size_t i=0; i < nSubset; ++i){ // Log progress if(m_msgLogger != nullptr) { m_msgLogger->logProgress(actionStr, i+1, nSubset, 10, threshold, lastPos); } size_t randIdx = shuffled[i]; if( kNN > 1 ){ pointKNN(m_cloud[randIdx], kNN, neighs); typename vector<CoverTreePoint<Vector3f>>::const_iterator it; for(it=neighs.begin(); it!=neighs.end(); ++it){ size_t idx = it->getId(); if( deletedPoint[idx] ) continue; //m_CT->remove(*it); deletedPoint[idx] = true; ++ndeleted; } } else{ deletedPoint[randIdx] = true; ++ndeleted; } if(ndeleted >= npoints) break; } size_t nremaining = max(size_t(0), npoints-ndeleted); if( nremaining <= 0 ){ m_cloud.clear(); m_norms.clear(); } else{ vector<Vector3f> m_cloud2(nremaining); vector<Vector3f> m_norms2(nremaining); for(size_t idx=0, idx2=0; idx < npoints; ++idx){ if( deletedPoint[idx] ) continue; m_cloud2[idx2] = m_cloud[idx]; m_norms2[idx2] = m_norms[idx]; ++idx2; } m_cloud = std::move(m_cloud2); m_norms = std::move(m_norms2); } m_CTStale = true; m_npointsOrig = npoints; if(m_msgLogger != nullptr) { m_msgLogger->logMessage( QString::number(ndeleted) + " points deleted, " + QString::number(nremaining) + " points remaining.\n"); } } //--------------------------------------------------------- void Cloud::sparsify(float percent) { QMutexLocker locker(&m_recMutex); bool useBBox = (m_bBox != nullptr); size_t nPointsUse = 0; if( useBBox ){ for(size_t idx=0; idx < m_cloud.size(); ++idx){ if( !m_bBox->pointInBBox(m_cloud[idx]) ) continue; ++nPointsUse; } } else{ nPointsUse = m_cloud.size(); } size_t nKeep = size_t(ceil( percent*nPointsUse/100.0 )); size_t nRemove = max(size_t(0), nPointsUse - nKeep); decimate(nRemove, 1); } //--------------------------------------------------------- void Cloud::reconstruct( int kSVDIters, size_t kNN, size_t nfreq, float densify, size_t natm, size_t latm, size_t maxNewPoints, bool looseBBox, SparseApprox method) { QMutexLocker locker(&m_recMutex); //assert(m_CT != nullptr); assert(kNN >= 1 && nfreq >= 1 && natm >= 1 && latm >= 1 && latm <= natm); m_npointsOrig = m_cloud.size(); if(m_npointsOrig == 0) return; size_t nfreqsq = nfreq*nfreq; //size_t maxGridDim = max(1, int(floor(sqrt(float(kNN))))); bool useBBox = (m_bBox != nullptr); //-------- struct gridLocation { size_t idx = -1; bool inCloud = true; bool inGrid = false; int cellX; int cellY; float u; float v; float w; size_t sigIdx = -1; }; //-------- auto fit_gridXY = [=]( const vector<Vector3f>& vneighsXY, float SD, float& sizeX, float& sizeY, size_t& gridDimX, size_t& gridDimY) { sizeX = sizeY = 0.0f; size_t n = vneighsXY.size(); for(size_t i=0; i<n; ++i){ Vector3f v = vneighsXY[i]; sizeX += v(0)*v(0); sizeY += v(1)*v(1); } sizeX = SD*sqrt(sizeX/n); sizeY = SD*sqrt(sizeY/n); if(min(sizeX,sizeY) <= 1e-3*max(sizeX,sizeY)) return false; if(sizeX <= float_tiny || sizeY <= float_tiny) return false; size_t numInGrid = 0; for(size_t i=0; i<n; ++i){ Vector3f v = vneighsXY[i]; if(abs(v(0)) > sizeX || abs(v(1)) > sizeY) continue; ++numInGrid; } if( numInGrid <= 1 ) return false; gridDimX = gridDimY = max(1, int(floor(0.8f*sqrt(densify*numInGrid)))); return true; }; //-------- auto get_gridXY_occupancy = [=]( const vector<CoverTreePoint<Vector3f>>& neighs, const vector<Vector3f>& vneighsXY, float sizeX, float sizeY, size_t gridDimX, size_t gridDimY, MapMtrxi& gridXY, vector<gridLocation>& gridLoc) { gridXY.setZero(); gridLoc.resize(neighs.size()); for(size_t i=0; i<neighs.size(); ++i){ gridLocation& loc = gridLoc[i]; loc.idx = neighs[i].getId(); loc.inCloud = true; loc.inGrid = false; const Vector3f& q = vneighsXY[i]; if( abs(q(0)) > sizeX ) continue; if( abs(q(1)) > sizeY ) continue; loc.u = (q(0)+sizeX)/(2*sizeX); loc.v = (q(1)+sizeY)/(2*sizeY); loc.w = q(2); loc.cellX = int(floor(gridDimX*loc.u)); loc.cellY = int(floor(gridDimY*loc.v)); ++gridXY(loc.cellX, loc.cellY); loc.inGrid = true; } }; //-------- auto setup_grid = [=]( const Vector3f& norm, const vector<CoverTreePoint<Vector3f>>& neighs, const vector<Vector3f>& vneighs, vector<Vector3f>& vneighsXY, Matrix3f& rotXY, MapMtrxi& gridXY, float& sizeX, float& sizeY, size_t& gridDimX, size_t& gridDimY, vector<gridLocation>& gridLoc, vectoria& iworkGrid) { gridDimX = gridDimY = 0; static const Vector3f zaxis(0.0f, 0.0f, 1.0f); vector_to_vector_rotation_matrix(norm, zaxis, true, true, rotXY); vneighsXY.resize(vneighs.size()); for(size_t j=0; j<vneighs.size(); ++j){ vneighsXY[j].noalias() = rotXY*vneighs[j]; } bool ok = fit_gridXY( vneighsXY, 1.5f, sizeX, sizeY, gridDimX, gridDimY); if( !ok ) return false; size_t nwork = gridDimX*gridDimY; if(iworkGrid.size() < nwork) iworkGrid.resize(nwork); new (&gridXY) MapMtrxi(&iworkGrid[0], gridDimX, gridDimY); get_gridXY_occupancy( neighs, vneighsXY, sizeX, sizeY, gridDimX, gridDimY, gridXY, gridLoc); return true; }; //-------- auto setup_grid_signal = [=]( vector<gridLocation>& gridLoc, VectorXf& Usig, VectorXf& Vsig, VectorXf& Wsig) { size_t numInGrid = 0; for(size_t j=0; j<gridLoc.size(); ++j){ if( !gridLoc[j].inGrid ) continue; ++numInGrid; } Usig.resize(numInGrid); Vsig.resize(numInGrid); Wsig.resize(numInGrid); for(size_t j=0, k=0; j<gridLoc.size(); ++j){ if( !gridLoc[j].inGrid ) continue; Usig(k) = gridLoc[j].u; Vsig(k) = gridLoc[j].v; Wsig(k) = gridLoc[j].w; gridLoc[j].sigIdx = k; ++k; } }; //-------- auto uvw_to_xyz = [=]( float cu, float cv, float cw, const Vector3f& p, const Matrix3f& rotXYInv, float sizeX, float sizeY) { Vector3f qXY, q; qXY(0) = (2*cu - 1.0f)*sizeX; qXY(1) = (2*cv - 1.0f)*sizeY; qXY(2) = cw; q.noalias() = rotXYInv*qXY; q += p; return q; }; //-------- auto get_num_empty_cells = [=]( const Vector3f& p, const Matrix3f& rotXY, const MapMtrxi& gridXY, float sizeX, float sizeY, size_t gridDimX, size_t gridDimY ) { bool ignoreBBox = true; if( useBBox ){ ignoreBBox = !m_bBox->ballInBBox(p, max(sizeX,sizeY)); } size_t numEmpty = 0; if( ignoreBBox ){ for(size_t j=0; j<gridDimY; ++j){ for(size_t k=0; k<gridDimX; ++k){ if(gridXY(k,j) > 0) continue; ++numEmpty; } } } else{ Matrix3f rotXYInv = rotXY.transpose(); for(size_t j=0; j<gridDimY; ++j){ float cv = (j/gridDimY); for(size_t k=0; k<gridDimX; ++k){ if(gridXY(k,j) > 0) continue; float cu = (k/gridDimX); Vector3f q = uvw_to_xyz( cu, cv, 0.0f, p, rotXYInv, sizeX, sizeY); if( !m_bBox->pointInBBox(q) ) continue; ++numEmpty; } } } return numEmpty; }; //-------- auto update_normal = [=]( size_t idx, const vector<CoverTreePoint<Vector3f>>& neighs, vector<CoverTreePoint<Vector3f>>& neighsNrm, vector<Vector3f>& vneighsNrm, vector<Vector3f>& vwork ) { neighsNrm.clear(); // size_t kNNNrm = min(size_t(50), neighs.size()); size_t kNNNrm = neighs.size(); for(size_t j=0;j<kNNNrm;++j){ neighsNrm.push_back(neighs[j]); } m_norms[idx] = approxNorm(m_cloud[idx], 25, neighsNrm, vneighsNrm, vwork); return m_norms[idx]; }; //-------- if(m_msgLogger != nullptr) { m_msgLogger->logMessage("** Point cloud reconstruction **"); } if( m_CTStale || (looseBBox && m_npointsCT < m_cloud.size()) ){ buildSpatialIndex(!looseBBox); } queue<size_t> qpoints; std::priority_queue<std::pair<float, size_t>> pqpoints; vector<VectorXf> Us; vector<VectorXf> Vs; vector<VectorXf> Ws; size_t threshold = 0, lastPos = 0, progress = 0; const bool useOpenMP = true; #pragma omp parallel if(useOpenMP) default(shared) { vector<CoverTreePoint<Vector3f>> neighs; vector<Vector3f> vneighs; vector<Vector3f> vneighsXY; vector<CoverTreePoint<Vector3f>> neighsNrm; vector<Vector3f> vneighsNrm; vector<Vector3f> vwork; MapMtrxi gridXY(nullptr, 0, 0); vectoria iworkGrid(kNN); vector<gridLocation> gridLoc; VectorXf Usig, Vsig, Wsig; #pragma omp for schedule(dynamic) for(Index idx = 0; idx < m_npointsOrig; ++idx){ Vector3f p = m_cloud[idx]; if( useBBox ) if( !m_bBox->pointInBBox(p) ) continue; pointKNN(p, kNN, neighs); getNeighVects(p, neighs, vneighs); Vector3f norm = update_normal(idx, neighs, neighsNrm, vneighsNrm, vwork); float sizeX, sizeY; size_t gridDimX, gridDimY; Matrix3f rotXY; bool success = setup_grid( norm, neighs, vneighs, vneighsXY, rotXY, gridXY, sizeX, sizeY, gridDimX, gridDimY, gridLoc, iworkGrid); if( !success ) continue; setup_grid_signal(gridLoc, Usig, Vsig, Wsig); size_t numEmpty = get_num_empty_cells( p, rotXY, gridXY, sizeX, sizeY, gridDimX, gridDimY); #pragma omp critical { Us.push_back(Usig); Vs.push_back(Vsig); Ws.push_back(Wsig); // if( numEmpty > 0 ) qpoints.push(idx); if( numEmpty > 0 ){ float weight = float(numEmpty)/(gridDimX*gridDimY); pqpoints.push(std::make_pair(weight,idx)); } ++progress; // Log progress if(m_msgLogger != nullptr) { m_msgLogger->logProgress( "Setting up signals", progress, m_npointsOrig, 5, threshold, lastPos); } } // critical } } // parallel while( !pqpoints.empty() ){ size_t idx = pqpoints.top().second; pqpoints.pop(); qpoints.push(idx); } //-------- MatrixXf D = MatrixXf::Random(nfreqsq, natm); D.colwise().normalize(); MatrixXf C = MatrixXf::Random(natm, m_npointsOrig); std::function<void( const Eigen::VectorXf&, const Eigen::MatrixXf&, Eigen::Index, Eigen::VectorXf&, Eigen::VectorXf& )> sparseFunct; MatchingPursuit mp; OrthogonalPursuit op; switch(method){ case SparseApprox::OrthogonalPursuit : sparseFunct = op; break; case SparseApprox::MatchingPursuit : sparseFunct = mp; break; } if(m_msgLogger != nullptr) { m_msgLogger->logMessage("Training dictionary..."); } // std::clock_t c_start = std::clock();//*** ksvd_dct2D(true, Ws, Us, Vs, nfreq, latm, kSVDIters, 0.0, sparseFunct, D, C, m_msgLogger); // std::clock_t c_end = std::clock();//*** // double time_elapsed_ms = 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC; // std::cout << "\nCPU time used: " << time_elapsed_ms << " ms\n" << std::endl; //-------- vector<CoverTreePoint<Vector3f>> neighs; vector<Vector3f> vneighs; vector<Vector3f> vneighsXY; vector<CoverTreePoint<Vector3f>> neighsNrm; vector<Vector3f> vneighsNrm; vector<Vector3f> vwork; MapMtrxi gridXY(nullptr, 0, 0); vectoria iworkGrid(kNN); vector<gridLocation> gridLoc; VectorXf Usig, Vsig, Wsig; MapMtrxf T(nullptr, kNN, nfreqsq); MapMtrxf TD(nullptr, kNN, natm); MapMtrxf TDNrm(nullptr, kNN, natm); MapMtrxf T0b(nullptr, kNN, nfreqsq); MapMtrxf T0D(nullptr, 2*kNN, natm); VectorXf NrmInv(natm); VectorXf Csig(natm); VectorXf CsigNrm(natm); VectorXf R(nfreqsq); VectorXf U0sig, V0sig, W0sig; VectorXf U0bsig, V0bsig; vector<gridLocation> gridLoc0; size_t paddedA[3] = { align_padded(kNN*nfreqsq), align_padded(kNN*natm), align_padded(kNN*natm) }; size_t nworkDctA = paddedA[0] + paddedA[1] + paddedA[2]; vectorfa dworkDctA(nworkDctA); vectorfa dworkDctA0; vectorfa dworkDctB; if(m_msgLogger != nullptr) { m_msgLogger->logMessage("Reconstructing point cloud..."); m_msgLogger->logMessage( QString::number(qpoints.size()) + " patches in queue..."); } size_t nprocessed = 0; size_t nNewPoints = 0; while( !qpoints.empty() ){ // Log progress if(m_msgLogger != nullptr) { if( nprocessed%1000 == 0 ){ m_msgLogger->logMessage( QString::number(nprocessed) + " patches processed..."); } ++nprocessed; } size_t idx = qpoints.front(); qpoints.pop(); Vector3f p = m_cloud[idx]; pointKNN(p, kNN, neighs); getNeighVects(p, neighs, vneighs); Vector3f norm; if( idx < m_npointsOrig ){ norm = m_norms[idx]; } else{ norm = update_normal(idx, neighs, neighsNrm, vneighsNrm, vwork); } float sizeX, sizeY; size_t gridDimX, gridDimY; Matrix3f rotXY; bool success = setup_grid( norm, neighs, vneighs, vneighsXY, rotXY, gridXY, sizeX, sizeY, gridDimX, gridDimY, gridLoc, iworkGrid); if( !success ) continue; setup_grid_signal(gridLoc, Usig, Vsig, Wsig); size_t nsmpl = Wsig.size(); size_t offset = 0; new (&T) MapMtrxf(&dworkDctA[offset], nsmpl, nfreqsq); offset += paddedA[0]; new (&TD) MapMtrxf(&dworkDctA[offset], nsmpl, natm); offset += paddedA[1]; new (&TDNrm) MapMtrxf(&dworkDctA[offset], nsmpl, natm); cosine_transform(Usig, Vsig, nfreq, dworkDctB, T); TD.noalias() = T*D; TDNrm = TD; column_normalize(TDNrm, NrmInv); sparseFunct(Wsig, TDNrm, latm, CsigNrm, R); Csig = CsigNrm.cwiseProduct(NrmInv); gridLoc0.clear(); for(size_t j=0; j<gridLoc.size(); ++j){ if( !gridLoc[j].inGrid ) continue; if( gridLoc[j].idx < m_npointsOrig ) continue; gridLoc0.push_back(gridLoc[j]); } size_t nsmpl0a = gridLoc0.size(); size_t npoints = m_cloud.size(); for(size_t j=0; j<gridDimY; ++j){ for(size_t k=0; k<gridDimX; ++k){ if(gridXY(k,j) > 0) continue; gridLocation loc; loc.idx = npoints; loc.inCloud = false; loc.inGrid = true; loc.u = (k+0.5f)/gridDimX; loc.v = (j+0.5f)/gridDimY; loc.w = 0.0f; loc.cellX = k; loc.cellY = j; gridLoc0.push_back(loc); ++npoints; } } size_t nsmpl0 = gridLoc0.size(); size_t nsmpl0b = nsmpl0 - nsmpl0a; size_t paddedA0[2] = { align_padded(nsmpl0*natm), align_padded(nsmpl0b*nfreqsq) }; size_t nworkDctA0 = paddedA0[0] + paddedA0[1]; if(dworkDctA0.size() < nworkDctA0) dworkDctA0.resize(nworkDctA0); offset = 0; new (&T0D) MapMtrxf(&dworkDctA0[offset], nsmpl0, natm); offset += paddedA0[0]; new (&T0b) MapMtrxf(&dworkDctA0[offset], nsmpl0b, nfreqsq); setup_grid_signal(gridLoc0, U0sig, V0sig, W0sig); for(size_t j=0, k=0; j<gridLoc.size(); ++j){ if( !gridLoc[j].inGrid ) continue; if( gridLoc[j].idx < m_npointsOrig ) continue; T0D.row(k) = TD.row(gridLoc[j].sigIdx); ++k; } U0bsig.resize(nsmpl0b); V0bsig.resize(nsmpl0b); U0bsig.segment(0,nsmpl0b) = U0sig.segment(nsmpl0a,nsmpl0b); V0bsig.segment(0,nsmpl0b) = V0sig.segment(nsmpl0a,nsmpl0b); cosine_transform(U0bsig, V0bsig, nfreq, dworkDctB, T0b); T0D.block(nsmpl0a,0,nsmpl0b,natm).noalias() = T0b*D; W0sig.noalias() = T0D*Csig; Matrix3f rotXYInv = rotXY.transpose(); for(size_t j=0; j<gridLoc0.size(); ++j){ gridLocation& loc = gridLoc0[j]; if( !loc.inCloud ){ if( nNewPoints >= maxNewPoints ) continue; } Vector3f q = uvw_to_xyz( loc.u, loc.v, W0sig(j), p, rotXYInv, sizeX, sizeY); if( useBBox ) if( !m_bBox->pointInBBox(q) ) continue; if( loc.inCloud ){ // Modifying cover tree point coordinates by point // removal and reinsertion is extremely slow. // We ignore the cover tree and change only the // cloud coordinates, treating the cover tree as // an approximation. This shouldn't cause much harm // since the change in coordinates should be modest. //replacePoint(loc.idx, q, m_norms[loc.idx]); m_cloud[loc.idx] = q; } else{ loc.idx = addPoint(q, norm); ++nNewPoints; qpoints.push(loc.idx); } } if( nNewPoints >= maxNewPoints ) break; } m_CTStale = true; if(m_msgLogger != nullptr) { m_msgLogger->logMessage( QString::number(nNewPoints) + " points added to cloud, " + QString::number(m_cloud.size()) + " points total.\n"); } } //---------------------------------------------------------
28,819
C++
.cpp
922
26.975054
80
0.606366
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,802
DecimateDialog.cpp
codearxiv_PCReconstruct/dialogs/DecimateDialog.cpp
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "DecimateDialog.h" #include "get_field.h" #include "constants.h" #include <QMainWindow> #include <QFormLayout> #include <QLabel> #include <QLineEdit> #include <QDialogButtonBox> #include <QObject> #include <QWidget> #include <QIntValidator> DecimateDialog::DecimateDialog(QWidget *parent) : QDialog(parent) { validator = new QIntValidator(1, int_infinity, this); form = new QFormLayout(this); form->addRow(new QLabel("Create random holes within bounding box")); nHolesLineEdit = new QLineEdit(this); nHolesLineEdit->setValidator(validator); nHolesLineEdit->setText("50"); form->addRow(QString("Number of holes:"), nHolesLineEdit); nPointsLineEdit = new QLineEdit(this); nPointsLineEdit->setValidator(validator); nPointsLineEdit->setText("100"); form->addRow(QString("Number of points per hole:"), nPointsLineEdit); buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this); form->addRow(buttonBox); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } bool DecimateDialog::getFields(size_t& nHoles, size_t& kNN) const { bool ok; ok = get_integer_field(nHolesLineEdit, validator, nHoles); if(!ok) return false; ok = get_integer_field(nPointsLineEdit, validator, kNN); if(!ok) return false; return true; }
1,497
C++
.cpp
42
33.52381
70
0.763396
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,803
OptionsDialog.cpp
codearxiv_PCReconstruct/dialogs/OptionsDialog.cpp
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "OptionsDialog.h" #include "get_field.h" #include "constants.h" #include <QMainWindow> #include <QFormLayout> #include <QLabel> #include <QLineEdit> #include <QDialogButtonBox> #include <QObject> #include <QWidget> #include <QIntValidator> OptionsDialog::OptionsDialog(QWidget *parent) : QDialog(parent) { validator = new QDoubleValidator(0.0, double_infinity, 5, this); form = new QFormLayout(this); form->addRow(new QLabel("Change app settings")); pointSizeLineEdit = new QLineEdit(this); pointSizeLineEdit->setValidator(validator); pointSizeLineEdit->setText("5.0"); form->addRow(QString("Display point size:"), pointSizeLineEdit); normScaleLineEdit = new QLineEdit(this); normScaleLineEdit->setValidator(validator); normScaleLineEdit->setText("0.01"); form->addRow(QString("Display normals size:"), normScaleLineEdit); buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this); form->addRow(buttonBox); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } bool OptionsDialog::getFields(float& pointSize, float& normScale) const { bool ok; ok = get_float_field(pointSizeLineEdit, validator, pointSize); if(!ok) return false; ok = get_float_field(normScaleLineEdit, validator, normScale); if(!ok) return false; return true; }
1,570
C++
.cpp
42
34.095238
71
0.742725
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,804
SparsifyDialog.cpp
codearxiv_PCReconstruct/dialogs/SparsifyDialog.cpp
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "SparsifyDialog.h" #include "get_field.h" #include "constants.h" #include <QMainWindow> #include <QFormLayout> #include <QLabel> #include <QLineEdit> #include <QDialogButtonBox> #include <QObject> #include <QWidget> #include <QIntValidator> SparsifyDialog::SparsifyDialog(QWidget *parent) : QDialog(parent) { validator = new QDoubleValidator(0.0, 100.0, 5, this); form = new QFormLayout(this); form->addRow(new QLabel( "Take a random subset of point cloud within bounding box")); percentLineEdit = new QLineEdit(this); percentLineEdit->setValidator(validator); percentLineEdit->setText("7.0"); form->addRow(QString("Percentage of points to keep:"), percentLineEdit); buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this); form->addRow(buttonBox); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } bool SparsifyDialog::getFields(float& percent) const { bool ok = get_float_field(percentLineEdit, validator, percent); return ok; }
1,221
C++
.cpp
35
32.771429
73
0.759796
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,805
get_field.cpp
codearxiv_PCReconstruct/dialogs/get_field.cpp
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "get_field.h" #include <QLineEdit> #include <QIntValidator> #include <QDoubleValidator> bool get_integer_field( QLineEdit *lineEdit, QIntValidator *validator, size_t& field) { QString fieldStr = lineEdit->text(); int pos = 0; if(validator->validate(fieldStr, pos) != QValidator::Acceptable){ lineEdit->clear(); return false; } else{ bool ok; field = fieldStr.toULongLong(&ok); if(!ok) { lineEdit->clear(); return false; } } return true; } bool get_float_field( QLineEdit *lineEdit, QDoubleValidator *validator, float& field) { QString fieldStr = lineEdit->text(); int pos = 0; if(validator->validate(fieldStr, pos) != QValidator::Acceptable){ lineEdit->clear(); return false; } else{ bool ok; field = fieldStr.toFloat(&ok); if(!ok) { lineEdit->clear(); return false; } } return true; }
972
C++
.cpp
44
19.727273
66
0.708243
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,806
RandomSurfDialog.cpp
codearxiv_PCReconstruct/dialogs/RandomSurfDialog.cpp
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "RandomSurfDialog.h" #include "get_field.h" #include "constants.h" #include <QFormLayout> #include <QLabel> #include <QLineEdit> #include <QDialogButtonBox> #include <QObject> #include <QWidget> #include <QIntValidator> RandomSurfDialog::RandomSurfDialog(QWidget *parent) : QDialog(parent) { validator = new QIntValidator(1, int_infinity, this); form = new QFormLayout(this); form->addRow(new QLabel( "Create a new point cloud sampled randomly from a random surface")); nPointsLineEdit = new QLineEdit(this); nPointsLineEdit->setValidator(validator); nPointsLineEdit->setText("15000"); form->addRow(QString("Number of points sampled:"), nPointsLineEdit); buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this); form->addRow(buttonBox); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } bool RandomSurfDialog::getFields(size_t& nPoints) const { bool ok = get_integer_field(nPointsLineEdit, validator, nPoints); return ok; }
1,215
C++
.cpp
34
33.558824
74
0.764555
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,807
ReconstructDialog.cpp
codearxiv_PCReconstruct/dialogs/ReconstructDialog.cpp
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "ReconstructDialog.h" #include "get_field.h" #include "constants.h" #include <QFormLayout> #include <QLabel> #include <QLineEdit> #include <QComboBox> #include <QDialogButtonBox> #include <QObject> #include <QWidget> #include <QIntValidator> #include <QDoubleValidator> ReconstructDialog::ReconstructDialog(QWidget *parent) : QDialog(parent) { intValidator = new QIntValidator(1, int_infinity, this); doubleValidator = new QDoubleValidator(0.0, double_infinity, 2, this); form = new QFormLayout(this); form->addRow(new QLabel("Fill in surface gaps in cloud within bounding box")); nItersLineEdit = new QLineEdit(this); nItersLineEdit->setValidator(intValidator); nItersLineEdit->setText("15"); nItersLineEdit->setToolTip( QString("This sets the number of training iterations within which\n") + QString("the various local surface patterns in the point cloud\n") + QString("are learned, and used in the cloud's reconstruction.")); form->addRow(QString("Number of dictionary learning iterations:"), nItersLineEdit); kNNLineEdit = new QLineEdit(this); kNNLineEdit->setValidator(intValidator); kNNLineEdit->setText("50"); kNNLineEdit->setToolTip( QString("The cloud surface is reconstructed patch-by-patch.\n") + QString("This sets the maximum number of points in a patch.\n\n") + QString("The larger gaps in the cloud are relative to density\n") + QString("of point sampling, the larger this field should be.\n") + QString("Expect crazy results otherwise!")); form->addRow(QString("Local patch size:"), kNNLineEdit); nFreqLineEdit = new QLineEdit(this); nFreqLineEdit->setValidator(intValidator); nFreqLineEdit->setText("4"); nFreqLineEdit->setToolTip( QString("Each local patch has a measure of complexity given by the\n") + QString("surface bumpiness along an axis. This sets the maximum\n") + QString("number of bumps along an axis that can be expected for\n") + QString("the given patch size.\n\n") + QString("Note training time and memory footprint will degrade\n") + QString("quadratically as this value increases.")); form->addRow(QString("Maximum frequency in a patch:"), nFreqLineEdit); densifyLineEdit = new QLineEdit(this); densifyLineEdit->setValidator(doubleValidator); densifyLineEdit->setText("1.0"); densifyLineEdit->setToolTip( QString("This controls the density of the reconstruction in\n") + QString("each region compared to the density of the nearby\n") + QString("points in the original cloud.")); form->addRow(QString("Densification factor:"), densifyLineEdit); nAtmLineEdit = new QLineEdit(this); nAtmLineEdit->setValidator(intValidator); nAtmLineEdit->setText("10"); nAtmLineEdit->setToolTip( QString("Total number of dictionary atoms available.\n\n") + QString("A too large value leads to overfitting, and too small\n") + QString("leads to underfitting, depending on max. frequency.")); form->addRow(QString("Number of dictionary atoms:"), nAtmLineEdit); lAtmLineEdit = new QLineEdit(this); lAtmLineEdit->setValidator(intValidator); lAtmLineEdit->setText("4"); lAtmLineEdit->setToolTip( QString("Maximum dictionary atoms used in patch reconstruction.\n\n") + QString("A too large value leads to overfitting, and too small\n") + QString("leads to underfitting, depending on max. frequency.")); form->addRow(QString("Atom sparsity constraint:"), lAtmLineEdit); maxNewLineEdit = new QLineEdit(this); maxNewLineEdit->setValidator(intValidator); maxNewLineEdit->setText("45000"); maxNewLineEdit->setToolTip( QString("Maximum number of new points to add to the cloud.")); form->addRow(QString("Maximum number of new points to add:"), maxNewLineEdit); bBoxComboBox = new QComboBox; bBoxComboBox->addItem(tr("True")); bBoxComboBox->addItem(tr("False")); bBoxComboBox->setToolTip( QString("Whether positions of points outside the bounding box\n") + QString("are to be considered when reconstructing within the\n") + QString("bounding box.\n\n") + QString("This helps the reconstruction to agree with points just\n") + QString("outside the bounding box.\n\n") + QString("Note that this may have the undesirable effect of\n") + QString("including points from two areas parallel surfaces where\n") + QString("they nearly meet, depending on the patch size. In this\n") + QString("case the bounding box for reconstruction might have to\n") + QString("be adjusted manually to include only desired points,\n") + QString("leaving this field false.")); form->addRow(QString("Use points outside bounding box:"), bBoxComboBox); connect(bBoxComboBox, QOverload<int>::of(&QComboBox::activated), this, &ReconstructDialog::bBoxComboChanged); methodComboBox = new QComboBox; methodComboBox->addItem(tr("Orthogonal Pursuit")); methodComboBox->addItem(tr("Matching Pursuit")); methodComboBox->setToolTip( QString("Sparse approximation method to use during training\n") + QString("and patch reconstruction.")); form->addRow(QString("Sparse approximation method:"), methodComboBox); connect(methodComboBox, QOverload<int>::of(&QComboBox::activated), this, &ReconstructDialog::methodComboChanged); buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this); form->addRow(buttonBox); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } //--------------------------------------------------------- int ReconstructDialog::getFields( int& kSVDIters, size_t& kNN, size_t& nfreq, float& densify, size_t& natm, size_t& latm, size_t& maxNewPoints, bool& looseBBox, SparseApprox& method) const { bool ok; size_t temp; ok = get_integer_field(nItersLineEdit, intValidator, temp); if(!ok) return -1; kSVDIters = int(temp); ok = get_integer_field(kNNLineEdit, intValidator, kNN); if(!ok) return -2; ok = get_integer_field(nFreqLineEdit, intValidator, nfreq); if(!ok) return -3; ok = get_float_field(densifyLineEdit, doubleValidator, densify); if(!ok) return -4; ok = get_integer_field(nAtmLineEdit, intValidator, natm); if(!ok) return -5; ok = get_integer_field(lAtmLineEdit, intValidator, latm); if(ok) if(latm > natm) ok = false; if(!ok) return -6; ok = get_integer_field(maxNewLineEdit, intValidator, maxNewPoints); if(!ok) return -7; switch(m_bBoxComboIdx){ case 0: looseBBox = true; break; case 1: looseBBox = false; break; } switch(m_methodComboIdx){ case 0: method = SparseApprox::OrthogonalPursuit; break; case 1: method = SparseApprox::MatchingPursuit; break; } return 0; }
6,851
C++
.cpp
155
40.974194
84
0.738517
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,808
BoundBoxDialog.cpp
codearxiv_PCReconstruct/dialogs/BoundBoxDialog.cpp
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "BoundBoxDialog.h" #include "get_field.h" #include "constants.h" #include <QMainWindow> #include <QFormLayout> #include <QLabel> #include <QLineEdit> #include <QDialogButtonBox> #include <QObject> #include <QWidget> #include <QIntValidator> BoundBoxDialog::BoundBoxDialog(QWidget *parent) : QDialog(parent) { validator = new QDoubleValidator(-double_infinity, double_infinity, 8, this); QString label[3] = {"X","Y","Z"}; form = new QFormLayout(this); form->addRow(new QLabel( "Set bounding box to perform operations within")); for(int i=0; i < 3; ++i){ minLineEdit[i] = new QLineEdit(this); minLineEdit[i]->setValidator(validator); minLineEdit[i]->setToolTip( QString("The smallest ") + label[i] + QString(" coordinate in bounding box.")); form->addRow(QString("Minimum ") + label[i] + QString(" coordinate:"), minLineEdit[i]); maxLineEdit[i] = new QLineEdit(this); maxLineEdit[i]->setValidator(validator); maxLineEdit[i]->setToolTip( QString("The largest ") + label[i] + QString(" coordinate in bounding box.")); form->addRow(QString("Maximum ") + label[i] + QString(" coordinate:"), maxLineEdit[i]); } buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this); form->addRow(buttonBox); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } //----------------------------------------------------------- bool BoundBoxDialog::getFields(float minBBox[], float maxBBox[]) const { bool ok; for(int i=0; i < 3; ++i){ ok = get_float_field(minLineEdit[i], validator, minBBox[i]); if(!ok) return false; ok = get_float_field(maxLineEdit[i], validator, maxBBox[i]); if(!ok) return false; } return true; } //----------------------------------------------------------- void BoundBoxDialog::setFields(const float minBBox[3], const float maxBBox[3]) { for(int i=0; i < 3; ++i){ minLineEdit[i]->setText(QString::number(minBBox[i])); maxLineEdit[i]->setText(QString::number(maxBBox[i])); } } //-----------------------------------------------------------
2,369
C++
.cpp
64
33.109375
81
0.624891
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,809
NormalsDialog.cpp
codearxiv_PCReconstruct/dialogs/NormalsDialog.cpp
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "NormalsDialog.h" #include "get_field.h" #include "constants.h" #include <QMainWindow> #include <QFormLayout> #include <QLabel> #include <QLineEdit> #include <QDialogButtonBox> #include <QObject> #include <QWidget> #include <QIntValidator> NormalsDialog::NormalsDialog(QWidget *parent) : QDialog(parent) { validator = new QIntValidator(1, int_infinity, this); form = new QFormLayout(this); form->addRow(new QLabel("Approximate cloud normals")); nItersLineEdit = new QLineEdit(this); nItersLineEdit->setValidator(validator); nItersLineEdit->setText("25"); form->addRow(QString("Number of iterations:"), nItersLineEdit); kNNLineEdit = new QLineEdit(this); kNNLineEdit->setValidator(validator); kNNLineEdit->setText("25"); form->addRow(QString("Number of neighbouring points used:"), kNNLineEdit); buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this); form->addRow(buttonBox); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } bool NormalsDialog::getFields(int& nIters, size_t& kNN) const { bool ok; size_t temp; ok = get_integer_field(nItersLineEdit, validator, temp); if(!ok) return false; nIters = int(temp); ok = get_integer_field(kNNLineEdit, validator, kNN); if(!ok) return false; return true; }
1,499
C++
.cpp
44
32.022727
75
0.759028
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,810
Plane.cpp
codearxiv_PCReconstruct/utils/Plane.cpp
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "Plane.h" #include <Eigen/Dense> using Eigen::Index; using Eigen::Matrix3f; using Eigen::Vector3f; using Eigen::Vector2f; //----------------------------------------------------------- void Plane::set(const Vector3f p0, const Vector3f norm) { const float RRT2 = 1.0f/sqrt(2.0f); m_p0 = p0; m_norm = norm; if( abs(norm(0)) < RRT2 ) { m_u(0) = 0.0f; m_u(1) = norm(2); m_u(2) = -norm(1); } else{ m_u(0) = -norm(2); m_u(1) = 0.0f; m_u(2) = norm(0); } m_v = m_u.cross(norm); m_u.normalize(); m_v.normalize(); } //----------------------------------------------------------- Eigen::Vector2f Plane::project_uv(const Vector3f q) { Vector3f w = q - m_p0; Vector2f puv; puv(0) = w.dot(m_u); puv(1) = w.dot(m_v); return puv; } //----------------------------------------------------------- Eigen::Vector3f Plane::project(const Vector3f q, Vector2f& puv) { puv = project_uv(q); Vector3f p = puv(0)*m_u + puv(1)*m_v; return p; } //-----------------------------------------------------------
1,203
C++
.cpp
46
24.152174
63
0.476775
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,811
rotations.cpp
codearxiv_PCReconstruct/utils/rotations.cpp
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "rotations.h" #include "constants.h" #include <Eigen/Geometry> #include <math.h> #include <Eigen/Dense> using Eigen::Vector3f; using Eigen::Matrix3f; //----------------------------------------------------------- // Returns the rotation matrix M that rotates vector v to a // vector w (or to a line through w if lineThruW is true). void vector_to_vector_rotation_matrix( const Vector3f& v, const Vector3f& w, bool normalized, bool lineThruW, Matrix3f& M) { Vector3f vxw = v.cross(w); float vxwLen = vxw.norm(); float cosa = v.dot(w); float sina = vxwLen; if( lineThruW ){ if( cosa < 0.0f ){ cosa = -cosa; vxw = -vxw; } } if( !normalized ){ float vvww = sqrt(v.dot(v)*w.dot(w)); if( vvww > float_tiny ){ cosa = cosa/vvww; sina = sina/vvww; } else{ cosa = 1.0f; sina = 0.0f; } } if( vxwLen > float_tiny ){ Vector3f u = vxw/vxwLen; cos_sin_angle_vector_rotation_matrix(cosa, sina, u, M); } else{ M.setIdentity(); if( cosa < 0.0f ) M = -M; } } //----------------------------------------------------------- /* Returns the counter-clockwise rotation matrix M around a unit vector U by an angle. U must have unit length. */ void angle_vector_rotation_matrix( float angle, const Vector3f& u, Matrix3f& M) { cos_sin_angle_vector_rotation_matrix(cos(angle), sin(angle), u, M); } //----------------------------------------------------------- void cos_sin_angle_vector_rotation_matrix( float cosa, float sina, const Vector3f& u, Matrix3f& M) { Vector3f tu = (1.0f-cosa)*u; Vector3f su = sina*u; M(0,0) = tu(0)*u(0) + cosa; M(1,0) = tu(0)*u(1) + su(2); M(2,0) = tu(0)*u(2) - su(1); M(0,1) = tu(1)*u(0) - su(2); M(1,1) = tu(1)*u(1) + cosa; M(2,1) = tu(1)*u(2) + su(0); M(0,2) = tu(2)*u(0) + su(1); M(1,2) = tu(2)*u(1) - su(0); M(2,2) = tu(2)*u(2) + cosa; } //-----------------------------------------------------------
2,083
C++
.cpp
75
25.48
68
0.546003
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,812
pt_to_pt_distsq.cpp
codearxiv_PCReconstruct/utils/pt_to_pt_distsq.cpp
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "pt_to_pt_distsq.h" #include <Eigen/Dense> #include <vector> //----------------------------------------------------------- double pt_to_pt_distsq(const Eigen::VectorXf& v, const Eigen::VectorXf& w) { double distsq = 0.0; for(Eigen::Index i=0; i < v.size(); ++i) { distsq += (v[i]-w[i])*(v[i]-w[i]); } return distsq; } //----------------------------------------------------------- double pt_to_pt_distsq(const float v[3], const float w[3]) { double distsq = 0.0; for(size_t i=0; i < 3; ++i) { distsq += (v[i]-w[i])*(v[i]-w[i]); } return distsq; } //-----------------------------------------------------------
807
C++
.cpp
25
30.6
74
0.442728
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,813
cloud_normal.cpp
codearxiv_PCReconstruct/utils/cloud_normal.cpp
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "cloud_normal.h" #include "ensure_buffer_size.h" #include "constants.h" #include <math.h> #include <vector> using Eigen::Vector3f; //using Eigen::Matrix; using Eigen::Index; using Eigen::Ref; template<typename T> using vector = std::vector<T>; //------------------------------------------------------------------------- /** Finds a best fitting unit normal N at a point p0 w.r.t. a point cloud. We do this by minimizing over nonzero vectors N the sum of squares F(N) = Sum_i w_i (N.V_i)^2 / (N.N) where V_i = (c_i-p0)/|c_i-p0| for c_i the i^th cloud point, where w_i is a given weighting. We simply take each w_i = 1.0. The gradient of F is Grad F = Sum_i w_i X_i where X_i = 2(N.V_i)/(N.N) V_i - 2 (N.V_i)^2/(N.N)^2 N with which we do gradient descent. @param[in] p0: point to query normal. @param[in] cloud: point cloud of n points. @param[in] niters: number of iterations to optimize the normal. @param[inout] vwork: workspace for V_i's. Resized automatically. */ Vector3f cloud_normal(const Vector3f& p0, const vector<Vector3f>& cloud, int niters, std::vector<Eigen::Vector3f>& vwork) { static const float ONE_OVER_SQRT3 = 1.0f/sqrt(3.0f); Vector3f N(ONE_OVER_SQRT3, ONE_OVER_SQRT3, ONE_OVER_SQRT3); size_t npoints = cloud.size(); vwork.resize(npoints); for(size_t i=0; i < npoints; ++i) { vwork[i] = (cloud[i] - p0).normalized(); } const double s = 0.5/niters; for(int iter=0; iter < niters; ++iter) { Vector3f G(0.0f, 0.0f, 0.0f); //float E = 0.0f; for(size_t i=0; i < npoints; ++i) { Vector3f V = vwork[i]; double t = (N.dot(V)); Vector3f X = t*(V - t*N); G += X; //E += t*t; } double rate = s*double(niters-iter); Vector3f N1 = N - rate*G.normalized(); float N1N1 = N1.dot(N1); if( N1N1 <= float_tiny ) break; N = N1/sqrt(N1N1); } // float minE = float_infinity; // for(int iter=0; iter < 100; ++iter) { // Vector3f N1; // N1.setRandom().normalized(); // float E = 0.0f; // for(size_t i=0; i < npoints; ++i) { // Vector3f V = (cloud[i] - p0).normalized(); // double t = (N1.dot(V)); // E += t*t; // } // if( E < minE ){ // minE = E; // N = N1; // } // } return N; }
2,405
C++
.cpp
74
29.797297
75
0.592721
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,814
cosine_transform.cpp
codearxiv_PCReconstruct/dictionarylearning/cosine_transform.cpp
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "cosine_transform.h" #include "ensure_buffer_size.h" #include "constants.h" #include "alignment.h" #include <Eigen/Core> #include <math.h> #include <vector> #include <cmath> using std::max; using std::vector; using Eigen::MatrixXf; using Eigen::Matrix; using Eigen::VectorXf; using Eigen::Index; using Eigen::Map; using Eigen::Dynamic; //using Eigen::Ref; template<typename T> using Ref = Eigen::Ref<T, ALIGNEDX>; using alloc = Eigen::aligned_allocator<float>; //----------------------------------------------------------- /** 2D non-uniform discrete cosine transform sampled at (u,v) coordinates in vectors U and V. @param[in] U: size n vector of u coordinates. @param[in] V: size n vector of v coordinates. @param[in] nfreq: max frequency in the u and v directions of transform. @param[in/out] dwork: work-array. Reallocated to correct size if too small. @param[out] T: 2D cosine transform, a dimension n x (nfreq*nfreq) matrix (must already be of this size on input). */ void cosine_transform( const VectorXf& U, const VectorXf& V, Index nfreq, vector<float,alloc>& dwork, Ref<MatrixXf> T ) { Index nsmpl = U.size(); size_t nf = nsmpl*nfreq; assert(nsmpl == V.size()); assert(nsmpl == T.rows()); assert(nfreq*nfreq == T.cols()); Map<MatrixXf> CU(nullptr, nsmpl, nfreq); Map<MatrixXf> SU(nullptr, nsmpl, nfreq); Map<MatrixXf> CV(nullptr, nsmpl, nfreq); Map<MatrixXf> SV(nullptr, nsmpl, nfreq); size_t p = align_padded(nf); ensure_buffer_size(4*p, dwork); new (&SU) Map<MatrixXf, ALIGNEDX>(&dwork[0], nsmpl, nfreq); new (&CU) Map<MatrixXf, ALIGNEDX>(&dwork[p], nsmpl, nfreq); new (&SV) Map<MatrixXf, ALIGNEDX>(&dwork[2*p], nsmpl, nfreq); new (&CV) Map<MatrixXf, ALIGNEDX>(&dwork[3*p], nsmpl, nfreq); float maxu = 0.0f; float maxv = 0.0f; for(int k=0; k<nsmpl; ++k){ maxu = max(maxu, abs(U(k))); maxv = max(maxv, abs(V(k))); } //---- float scaleu = float(maxu > 0.0 ? M_PI/maxu : M_PI); float scalev = float(maxv > 0.0 ? M_PI/maxv : M_PI); // for(Index i=0; i<nfreq; ++i){ // float scaleui = scaleu*i; // float scalevi = scalev*i; // for(Index k=0; k<nsmpl; ++k){ // CU(k,i) = cos(scaleui*U(k)); // CV(k,i) = cos(scalevi*V(k)); // } // } // This part is a bit performance sensitive. Instead of // computing cosines over each frequency directly, compute // the lowest frequency and apply angle-sum trig. identities // to recursively compute the remaining frequencies. We can // use a quick sin/cos approximation for the lowest frequency // since we are in the range (-PI,PI). // std::function< float(float) > approx_sin = [=](float t) { // if(t < 0){ return 1.27323954f*t + 0.405284735f*t*t; } // else{ return 1.27323954f*t - 0.405284735f*t*t; } // }; // std::function< float(float) > approx_cos = [=](float t) { // return approx_sin(t+1.57079632f); // }; for(Index k=0; k<nsmpl; ++k){ CU(k,0) = 1.0f; CV(k,0) = 1.0f; // SU(k,1) = approx_sin(scaleu*U(k)); // CU(k,1) = approx_cos(scaleu*U(k)); // SV(k,1) = approx_sin(scalev*V(k)); // CV(k,1) = approx_cos(scalev*V(k)); SU(k,1) = sin(scaleu*U(k)); CU(k,1) = cos(scaleu*U(k)); SV(k,1) = sin(scalev*V(k)); CV(k,1) = cos(scalev*V(k)); } for(Index i=2; i<nfreq; ++i){ for(Index k=0; k<nsmpl; ++k){ SU(k,i) = SU(k,i-1)*CU(k,1) + CU(k,i-1)*SU(k,1); CU(k,i) = CU(k,i-1)*CU(k,1) - SU(k,i-1)*SU(k,1); SV(k,i) = SV(k,i-1)*CV(k,1) + CV(k,i-1)*SV(k,1); CV(k,i) = CV(k,i-1)*CV(k,1) - SV(k,i-1)*SV(k,1); } } //---- Index l = 0; for(Index i=0; i<nfreq; ++i){ for(Index j=0; j<nfreq; ++j){ for(Index k=0; k<nsmpl; ++k){ T(k,l) = CU(k,i)*CV(k,j); } l = l + 1; } } } //-----------------------------------------------------------
4,092
C++
.cpp
120
30.458333
70
0.586357
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,815
ksvd.cpp
codearxiv_PCReconstruct/dictionarylearning/ksvd.cpp
//------------------------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. //#define DEBUG_KSVD #include "ksvd.h" #include "constants.h" #include "alignment.h" #include <Eigen/Dense> #include <functional> #include <math.h> #include <vector> #include <omp.h> #include <iostream> using std::cout; using std::endl; using std::vector; using Eigen::MatrixXf; using Eigen::MatrixXi; using Eigen::Matrix; using Eigen::VectorXf; using Eigen::VectorXi; using Eigen::Index; using Eigen::Map; using Eigen::Dynamic; using Eigen::Aligned16; //----------------------------------------------------------- /** The K-SVD dictionary learning algorithm. Provided an integer L and n x k matrix Y consisting of our k size n signal vectors, we look for an n x m dictionary matrix D of m atoms (unit column vectors of size n) and a sparse m x k matrix X of column code vectors that encode the signals in Y as closely as possible using no more than L atoms in D. In detail, we solve the minimization problem min_{X, D} ||Y - DX||_F subject to ||X||_0 <= L where ||.||_F is the matrix Frobenius norm, and ||.||_0 is the vector L_0 norm (the number of non-zero entries in a vector). @param[in] useOpenMP: Whether to parallelize using OpenMP. @param[in] Y: n x k signal matrix. @param[in] latm: Sparsity constraint L. @param[in] maxIters: Max. number of K-SVD iterations. @param[in] maxError: Max. error ||Y-D*X||^2 before an iteration can be aborted (< 0.0 for none). @param[in] svdPowIters: Number of power iterations to approximate first singular vectors. @param[in] Sparse approximation functor. @param[in/out] D in: first approximation n x m 'dictionary' matrix. D out: learnt dictionary adapted to the signals Y. @param[out] X: m x k 'code' matrix. */ void ksvd( bool useOpenMP, const MatrixXf& Y, Index latm, int maxIters, float maxError, int svPowIters, const std::function<void( const VectorXf&, const MatrixXf&, Index, VectorXf&, VectorXf&)> sparseFunct, MatrixXf& D, MatrixXf& X ) { Index ndim = D.rows(); Index natm = D.cols(); Index nsig = Y.cols(); assert(ndim == Y.rows()); assert(natm == X.rows()); assert(nsig == X.cols()); assert(maxIters >= 1); assert(svPowIters >= 1); assert(latm <= ndim && latm <= natm); bool stopAtMaxError = (maxError >= 0.0f); float maxErrorSq = 0.0f; bool smallError; float* errsig = new float[nsig]; for(Index i=0; i < nsig; ++i) { errsig[i] = float_infinity; } if( stopAtMaxError ) maxErrorSq = maxError*maxError; float *dwork = new float[nsig*ndim]; MatrixXf Z(ndim,nsig); Map<MatrixXf, ALIGNEDX> Zblk(nullptr, 0, 0); VectorXf ZTA(nsig); VectorXf ZZTA(ndim); VectorXf A(ndim); VectorXf B(nsig); MatrixXi iatmUsed(latm,nsig); VectorXi natmUsed(nsig); #pragma omp parallel if(useOpenMP) default(shared) firstprivate(sparseFunct) { VectorXf Ysig(ndim); VectorXf Xsig(natm); VectorXf R(ndim); for(int iter = 1; iter <= maxIters; ++iter){ //*** #pragma omp single { #ifdef DEBUG_KSVD if(iter == 1) cout << "\nAverge error (coordinate difference):\n" ; cout << (Y-(D*X)).cwiseAbs().sum()/(ndim*nsig) << endl; #endif } // Fix dictionary D and optimize code matrix X. #pragma omp for schedule(dynamic) for(Index isig = 0; isig < nsig; ++isig){ Ysig = Y.col(isig); sparseFunct(Ysig, D, latm, Xsig, R); float error = R.dot(R); if( error <= errsig[isig] ) { X.col(isig) = Xsig; errsig[isig] = error; } } if( stopAtMaxError ){ // Stop if Y and D*X are similar within tolerance. #pragma omp single { smallError = true; for(Index isig = 0; isig < nsig; ++isig){ if( errsig[isig] > maxErrorSq ){ smallError = false; break; } } }//single if( smallError ) break; } // --- // Now optimize dictionary D for the current code vector X // one column (atom) at a time. //#pragma omp for schedule(dynamic) #pragma omp single { // queue up atoms used by each signal for(Index isig = 0; isig < nsig; ++isig){ int ic = 0; for(Index iatm = 0; iatm < natm; ++iatm){ if( X(iatm,isig) == 0.0f ) continue; iatmUsed(ic,isig) = int(iatm); ++ic; if(ic >= latm) break; } natmUsed(isig) = ic; } for(Index iatm = 0; iatm < natm; ++iatm){ A = D.col(iatm); // Original atom is our initial approx. // Compute the matrix Z of residuals for current atom. Index nsigUsing = 0; for(Index isig = 0; isig < nsig; ++isig){ if( X(iatm,isig) == 0.0f ) continue; Z.col(nsigUsing) = Y.col(isig); for(Index i = 0; i < natmUsed(isig); ++i){ Index jatm = iatmUsed(i,isig); if( jatm == iatm ) continue; Z.col(nsigUsing) -= X(jatm,isig)*D.col(jatm); } ++nsigUsing; } if( nsigUsing == 0 ) continue; // Map to workspace new (&Zblk) Map<MatrixXf, ALIGNEDX>(dwork,ndim,nsigUsing); Zblk = Z.block(0,0,ndim,nsigUsing); // We only need the first singular vector, do a power // iteration to approximate it. This is our new improved atom. for(int i=1; i <= svPowIters; ++i){ ZTA.segment(0,nsigUsing).noalias() = Zblk.transpose()*A; ZZTA.noalias() = Zblk*ZTA.segment(0,nsigUsing); A = ZZTA.normalized(); // Optimized atom } // The projection coefficients describe the code vector // corresponding to the updated atom. B.segment(0,nsigUsing).noalias() = Zblk.transpose()*A; Index ic2 = 0; for(Index isig = 0; isig < nsig; ++isig){ if( X(iatm,isig) == 0.0f ) continue; X(iatm,isig) = B(ic2); ++ic2; } D.col(iatm) = A; } }//single } }//parallel delete[] dwork; if( stopAtMaxError ) delete[] errsig; } //-----------------------------------------------------------
6,190
C++
.cpp
192
27.333333
77
0.6125
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,816
MatchingPursuit.cpp
codearxiv_PCReconstruct/dictionarylearning/MatchingPursuit.cpp
//------------------------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "MatchingPursuit.h" #include "ensure_buffer_size.h" #include "constants.h" #include <Eigen/Core> using Index = Eigen::Index; using MatrixXf = Eigen::MatrixXf; using VectorXf = Eigen::VectorXf; //------------------------------------------------------------------------- void MatchingPursuit::ensure( Index nd, Index na, Index lm) { if(nd != ndim || na != natm || lm != lmax){ ndim = nd; natm = na; lmax = (na < lm) ? na : lm; } } //------------------------------------------------------------------------- /** Given a size n signal vector Y, an n x m dictionary matrix D of m atoms (unit column vectors of size n), and an integer L, our task is to find a sparse size m code vector X that encodes Y as closely as possible using no more than L atoms in D. In detail, we try to solve to minimization problem min_X ||Y - DX||_F subject to ||X||_0 <= L where ||.||_F is the matrix Frobenius norm, and ||.||_0 is the vector L_0 norm (the number of non-zero entries in a vector). This is a greedy approach using the matching pursuit algorithm. @param[in] Y: size n vector. @param[in] D: n x m dictionary matrix. @param[in] latm: Sparsity constraint L. @param[out] X: size m code vector. @param[out] R: size n residual vector. */ void MatchingPursuit::operator()( const VectorXf& Y, const MatrixXf& D, Index latm, VectorXf& X, VectorXf& R) { assert(D.rows() == Y.rows()); assert(D.cols() == X.rows()); ensure(D.rows(), D.cols(), latm); X.setZero(); R = Y; for(Index j = 1; j <= latm; ++j){ float absprojmax = -float_infinity; float projmax = 0; Index imax = 0; for(Index i = 0; i < natm; ++i){ if( X(i) != 0.0f ) continue; float proj = R.dot(D.col(i)); float absproj = abs(proj); if( absproj > absprojmax ){ projmax = proj; absprojmax = absproj; imax = i; } } X(imax) = projmax; R = R - projmax*D.col(imax); } } //-------------------------------------------------------------------------
2,324
C++
.cpp
66
30.606061
78
0.536871
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,817
ksvd_dct2D.cpp
codearxiv_PCReconstruct/dictionarylearning/ksvd_dct2D.cpp
//------------------------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "ksvd_dct2D.h" #include "cosine_transform.h" #include "ensure_buffer_size.h" #include "constants.h" #include "alignment.h" #include "MessageLogger.h" #include <Eigen/Dense> #include <functional> #include <omp.h> #include <math.h> #include <iostream> #include <vector> using std::cout; using std::endl; using std::vector; using Eigen::MatrixXf; using Eigen::MatrixXi; using Eigen::Matrix; using Eigen::VectorXf; using Eigen::VectorXi; using Eigen::Index; using Eigen::Map; using Eigen::Dynamic; using Eigen::Aligned16; using Eigen::LDLT; //using Eigen::Ref; template<typename T> using aligned = Eigen::aligned_allocator<T>; using vectorfa = vector<float, aligned<float>>; using vectoria = vector<int, aligned<int>>; template<typename T> using Ref = Eigen::Ref<T, ALIGNEDX>; using MapMtrxf = Map<MatrixXf, ALIGNEDX>; using MapVectf = Map<VectorXf, ALIGNEDX>; //----------------------------------------------------------- /** An extension of K-SVD to the domain of continuous signals and dictionary atoms, in this case realized by linear combinations of products of cosines of various frequencies coming from 2D discrete cosine transform sampled non-uniformly at given (u,v) coordinates associated to each signal's coordinates (samples). This allows signals of varying length as well estimating values of signals away from their sampled (u,v)-coordinates. C.f. "Cloud Dictionary: Coding and Modeling for Point Clouds", https://arxiv.org/abs/1612.04956 @param[in] useOpenMP: Whether to parallelize using OpenMP. @param[in] Y: array of signal vectors (possibly of variable length). @param[in] U: array of vectors of 'u' coordinates for each coordinate of vector in Y. @param[in] V: array of vectors of 'v' coordinates for each coordinate of vector in Y. @param[in] nfreq: Largest cosine frequency. @param[in] latm: Sparsity constraint L. @param[in] maxIters: Max. number of K-SVD iterations. @param[in] maxError: Max. error ||Y-D*X||^2 before an iteration can be aborted (< 0.0 for none). @param[in] svdPowIters: Number of power iterations to approximate first singular vectors. @param[in] Sparse approx. functor. @param[in/out] D in: first approx. (nfreq*nfreq) x m 'dictionary' matrix. D out: learnt dictionary adapted to the signals Y. @param[out] X: m x nsig 'code' matrix. */ void ksvd_dct2D( bool useOpenMP, const vector<VectorXf>& Y, const vector<VectorXf>& U, const vector<VectorXf>& V, Index nfreq, Index latm, int maxIters, float maxError, const std::function<void( const VectorXf&, const MatrixXf&, Index, VectorXf&, VectorXf&)> sparseFunct, MatrixXf& D, MatrixXf& X, MessageLogger* msgLogger ) { Index nsig = Y.size(); Index nfreqsq = nfreq*nfreq; Index natm = D.cols(); assert(size_t(nsig) == U.size()); assert(size_t(nsig) == V.size()); assert(nfreqsq == D.rows()); assert(natm == X.rows()); assert(nsig == X.cols()); assert(maxIters >= 1); assert(latm <= natm); Index maxThreads = omp_get_max_threads(); Index lastIter = 0; bool stopAtMaxError = (maxError >= 0.0f); float maxErrorSq = 0.0f; bool smallError; float* errsig = new float[nsig]; for(Index i=0; i < nsig; ++i) { errsig[i] = float_infinity; } if( stopAtMaxError ) maxErrorSq = maxError*maxError; Index maxSamples = 0; Index totalSamplesPadded = 0; for(Index isig = 0; isig < nsig; ++isig){ Index nsmpl = Y[isig].size(); maxSamples = std::max(maxSamples, nsmpl); totalSamplesPadded += align_padded(nsmpl); } vectorfa dworkZ; ensure_buffer_size(totalSamplesPadded, dworkZ); vector<MapVectf> Zblk(nsig, MapVectf(nullptr,0)); Index p = 0; for(Index isig = 0; isig < nsig; ++isig){ Index nsmpl = Y[isig].size(); new (&Zblk[isig]) MapVectf(&dworkZ[p], nsmpl); p = p + align_padded(nsmpl); } bool aSigUsingAtm; MatrixXi iatmUsed(latm,nsig); VectorXi natmUsed(nsig); VectorXf TZS(nfreqsq); MatrixXf TTS(nfreqsq,nfreqsq); vector<VectorXf> TZSs(maxThreads,VectorXf(nfreqsq)); vector<MatrixXf> TTSs(maxThreads,MatrixXf(nfreqsq,nfreqsq)); //Eigen::LDLT<MatrixXf> *ldlt = new LDLT<MatrixXf>(nfreqsq*nfreqsq); Eigen::LDLT<MatrixXf> *ldlt = new LDLT<MatrixXf>(); #pragma omp parallel if(useOpenMP) default(shared) firstprivate(sparseFunct) { Index numThreads = omp_get_num_threads(); Index iThread = omp_get_thread_num(); VectorXf TDatm(maxSamples); VectorXf TA(maxSamples); VectorXf TZ(nfreqsq); VectorXf Xsig(natm); VectorXf R(nfreqsq); size_t paddedA[2] = { align_padded(maxSamples*nfreqsq), align_padded(maxSamples*natm) }; vectorfa dworkDctA(paddedA[0] + paddedA[1]); vectorfa dworkDctB;//(4*align_padded(maxSamples*nfreq)); MapMtrxf T(nullptr, maxSamples, nfreqsq); MatrixXf TT(nfreqsq,nfreqsq); MapMtrxf TD(nullptr, maxSamples, natm); VectorXf NrmInv(natm); VectorXf TY(nfreqsq); for(int iter = 1; iter <= maxIters; ++iter){ // Fix dictionary D and optimize code matrix X. #pragma omp for schedule(dynamic) for(Index isig = 0; isig < nsig; ++isig){ Index nsmpl = Y[isig].size(); new (&T) MapMtrxf(&dworkDctA[0], nsmpl, nfreqsq); cosine_transform(U[isig], V[isig], nfreq, dworkDctB, T); new (&TD) MapMtrxf(&dworkDctA[paddedA[0]], nsmpl, natm); TD.noalias() = T*D; column_normalize(TD, NrmInv); sparseFunct(Y[isig], TD, latm, Xsig, R); float error = R.dot(R); if( error <= errsig[isig] ) { X.col(isig) = Xsig.cwiseProduct(NrmInv); errsig[isig] = error; } } if( stopAtMaxError ){ // Stop if Y and D*X are similar within tolerance. #pragma omp single { smallError = true; for(Index isig = 0; isig < nsig; ++isig){ if( errsig[isig] > maxErrorSq ){ smallError = false; break; } } }//single if( smallError ) break; } #pragma omp single { // queue up atoms used by each signal for(Index isig = 0; isig < nsig; ++isig){ int ic = 0; for(Index iatm = 0; iatm < natm; ++iatm){ if( X(iatm,isig) == 0.0f ) continue; iatmUsed(ic,isig) = int(iatm); ++ic; if(ic >= latm) break; } natmUsed(isig) = ic; } } //single // --- // Now optimize dictionary D for the current code vector X // one column (atom) at a time. for(Index iatm = 0; iatm < natm; ++iatm){ TTSs[iThread].setZero(); TZSs[iThread].setZero(); #pragma omp for schedule(static) for(Index isig = 0; isig < nsig; ++isig){ if(X(iatm,isig) == 0.0f) continue; Index nsmpl = Y[isig].size(); new (&T) MapMtrxf(&dworkDctA[0], nsmpl, nfreqsq); cosine_transform(U[isig], V[isig], nfreq, dworkDctB, T); // Compute the residual Z for current atom and signal. MapVectf& Z = Zblk[isig]; Z = Y[isig]; for(Index i = 0; i < natmUsed(isig); ++i){ Index jatm = iatmUsed(i,isig); if( jatm == iatm ) continue; TDatm.segment(0,nsmpl).noalias() = T*D.col(jatm); Z -= X(jatm,isig)*TDatm.segment(0,nsmpl); } TT.noalias() = T.transpose() * T; TA.segment(0,nsmpl).noalias() = T*D.col(iatm); float normsqTA = TA.segment(0,nsmpl).squaredNorm(); TZ.noalias() = T.transpose() * Z; float r = Z.dot(TA.segment(0,nsmpl)) / normsqTA; TTSs[iThread] += (r*r)*TT; TZSs[iThread] += r*TZ; aSigUsingAtm = true; } #pragma omp single { if( aSigUsingAtm ){ TTS.setZero(); TZS.setZero(); for(int i = 0; i < numThreads; ++i){ TTS += TTSs[i]; TZS += TZSs[i]; } // This is an analog of a single SVD power // iteration. Now the vector optimized to // best match each residual is constrained // to be a linear transformation of another // vector. // It can be worked out with some matrix // calculus by minimizing the sum of inner // products: // // Sum_i(Z_i-a_iT_iD').(Z_i-a_iT_iD') // // over D' and reals a_i, where D' is the // atom being optimized, Z_i the residual // for the ith signal that uses atom D', // and T_i the cosine transform for this // signal. The a_i's are the projections // Z_i.(T_iD')/(T_iD').(T_iD') . ldlt->compute(TTS); D.col(iatm) = ldlt->solve(TZS); // Optimized atom } } //single if( aSigUsingAtm ){ #pragma omp for schedule(static) for(Index isig = 0; isig < nsig; ++isig){ if(X(iatm,isig) == 0.0f) continue; Index nsmpl = Y[isig].size(); new (&T) MapMtrxf(&dworkDctA[0], nsmpl, nfreqsq); cosine_transform(U[isig], V[isig], nfreq, dworkDctB, T); TA.segment(0,nsmpl).noalias() = T*D.col(iatm); float normsqTA = TA.segment(0,nsmpl).squaredNorm(); // The projection coefficients describe the code vector // corresponding to the updated atom. X(iatm,isig) = Zblk[isig].dot(TA.segment(0,nsmpl)) / normsqTA; } } } if(msgLogger != nullptr) { #pragma omp single { lastIter = iter; if(iter == 1){ msgLogger->logMessage( "Avg. error (coord. diff., cos angle, vect. diff.)"); print_error_dct2D( useOpenMP, Y, U, V, D, X, nfreq, iter, msgLogger); } } } } // kSVD iterations if(msgLogger != nullptr) { #pragma omp single { print_error_dct2D( useOpenMP, Y, U, V, D, X, nfreq, lastIter, msgLogger); } } } //parallel if( stopAtMaxError ) delete[] errsig; delete ldlt; } //----------------------------------------------------------- void print_error_dct2D( bool useOpenMP, const vector<VectorXf>& Y, const vector<VectorXf>& U, const vector<VectorXf>& V, const MatrixXf& D, const MatrixXf& X, Index nfreq, Index iter, MessageLogger* msgLogger ) { Index nsig = Y.size(); Index natm = D.cols(); Index nfreqsq = nfreq*nfreq; Index maxThreads = omp_get_max_threads(); Index numThreads; vector<float> threadError1(maxThreads, 0.0f); vector<float> threadError2(maxThreads, 0.0f); vector<float> threadError3(maxThreads, 0.0f); vector<Index> threadTotalSmpl(maxThreads, 0); #pragma omp parallel if(useOpenMP) default(shared) { numThreads = omp_get_num_threads(); Index iThread = omp_get_thread_num(); MapMtrxf T(nullptr, 0, 0); MapMtrxf TD(nullptr, 0, 0); MapVectf TDX(nullptr, 0); vectorfa dworkA; vectorfa dworkB; size_t paddedA[3]; #pragma omp for schedule(static) for(Index isig = 0; isig < nsig; ++isig){ Index nsmpl = Y[isig].size(); paddedA[0] = align_padded(nsmpl*nfreqsq); paddedA[1] = align_padded(nsmpl*natm); paddedA[2] = align_padded(nsmpl); ensure_buffer_size(paddedA[0]+paddedA[1]+paddedA[2], dworkA); new (&T) MapMtrxf(&dworkA[0], nsmpl, nfreqsq); new (&TD) MapMtrxf(&dworkA[paddedA[0]], nsmpl, natm); new (&TDX) MapVectf(&dworkA[paddedA[1]], nsmpl); cosine_transform(U[isig], V[isig], nfreq, dworkB, T); TD.noalias() = T*D; TDX.noalias() = TD*(X.col(isig)); float normY = Y[isig].norm(); threadError1[iThread] += (Y[isig] - TDX).cwiseAbs().sum(); threadError2[iThread] += Y[isig].dot(TDX)/(normY*TDX.norm()); threadError3[iThread] += (Y[isig] - TDX).norm()/normY; threadTotalSmpl[iThread] += nsmpl; } } //parallel float error1 = 0.0f; float error2 = 0.0f; float error3 = 0.0f; Index totalsmpl = 0; for(Index iThread = 0; iThread < numThreads; ++iThread){ error1 += threadError1[iThread]; error2 += threadError2[iThread]; error3 += threadError3[iThread]; totalsmpl += threadTotalSmpl[iThread]; } QString errorStr = "Iteration " + QString::number(iter) + ": " + QString::number(error1/totalsmpl) + ", " + QString::number(error2/nsig) + ", " + QString::number(error3/nsig); msgLogger->logMessage(errorStr); } //----------------------------------------------------------- void column_normalize(Ref<MatrixXf> M, Ref<VectorXf> NrmInv) { for(Index i=0; i < M.cols(); ++i) { NrmInv(i) = 1.0f/M.col(i).norm(); M.col(i) *= NrmInv(i); } } //-----------------------------------------------------------
12,461
C++
.cpp
369
29.308943
78
0.640834
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,818
OrthogonalPursuit.cpp
codearxiv_PCReconstruct/dictionarylearning/OrthogonalPursuit.cpp
//------------------------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #include "OrthogonalPursuit.h" #include "ensure_buffer_size.h" #include "constants.h" #include <Eigen/Dense> #include <functional> using Eigen::Matrix; using Eigen::Dynamic; using Eigen::LDLT; using Eigen::Aligned16; using Eigen::Index; using Eigen::MatrixXf; using Eigen::VectorXf; using MapVectf = Eigen::Map<VectorXf, ALIGNEDX>; using MapMtrxf = Eigen::Map<MatrixXf, ALIGNEDX>; template<typename T> using Map = Eigen::Map<T, ALIGNEDX>; template<typename T> using vector = std::vector<T, Eigen::aligned_allocator<T>>; //------------------------------------------------------------------------- void OrthogonalPursuit::ensure(Index nd, Index na, Index lm) { if(nd != ndim || na != natm || lm != lmax){ ndim = nd; natm = na; lmax = (na < lm) ? na : lm; ensureWorkspace(); } } //------------------------------------------------------------------------- void OrthogonalPursuit::ensureWorkspace() { // Allocate more workspace as necessary. //std::function< size_t(Index) > align_padded = // [=](Index n) ->size_t { return ALIGNEDX*(1+(n/ALIGNEDX)); }; size_t paddednd = align_padded(ndim); size_t paddedlm = align_padded(lmax); size_t paddedndlm = align_padded(ndim*lmax); size_t paddedlmsq = align_padded(lmax*lmax); size_t ndworkNeed = paddednd + 3*paddedlm + 2*paddedndlm + 2*paddedlmsq; ensure_buffer_size(ndworkNeed+ndworkNeed/2, dwork); // Map to pre-allocated workspace. size_t p = 0; new (&U) MapVectf(&dwork[0],ndim); p = p + paddednd; new (&V) MapVectf(&dwork[p],lmax); p = p + paddedlm; new (&W) MapVectf(&dwork[p],lmax); p = p + paddedlm; new (&XI) MapVectf(&dwork[p],lmax); p = p + paddedlm; new (&E) MapMtrxf(&dwork[p],ndim,lmax); p = p + paddedndlm; new (&F) MapMtrxf(&dwork[p],lmax,lmax); p = p + paddedlmsq; dworkOffset = p; size_t niworkNeed = lmax; ensure_buffer_size(niworkNeed+niworkNeed/2, iwork); // Map to pre-allocated workspace. new (&I) Map<Matrix<Index,Dynamic,1>>(&iwork[0],lmax); if( lmax*lmax > ldltSize ){ ldltSize = lmax*lmax; delete ldlt; ldlt = new LDLT<MatrixXf>(ldltSize); } } //------------------------------------------------------------------------- /** Orthogonal Matching Pursuit: Similar to matching pursuit, but provides a better approximation at the expense of significantly more computation. Namely, updates all the coefficients of the current code vector X' at each iteration so that DX' is an orthogonal projection of the signal vector Y onto the subspace spanned by the dictionary atoms corresponding to the nonzero entries of X'. @param[in] Y: size n vector. @param[in] D: n x m dictionary matrix of unit column vectors. @param[in] latm: Sparsity constraint. @param[out] X: size m code vector. @param[out] R: size n residual vector. */ void OrthogonalPursuit::operator() ( const VectorXf& Y, const MatrixXf& D, Index latm, VectorXf& X, VectorXf& R) { assert(D.rows() == Y.rows()); assert(D.cols() == X.rows()); ensure(D.rows(),D.cols(),latm); X.setZero(); R = Y; for(Index j = 1; j <= latm; ++j){ // Find the next 'nearest' atom to current residual R. float absprojmax = -float_infinity; Index imax = 0; for(Index i = 0; i < natm; ++i){ if( X(i) != 0.0f ) continue; float proj = R.dot(D.col(i)); float absproj = abs(proj); if( absproj > absprojmax ){ absprojmax = absproj; imax = i; } } U = D.col(imax); // Dictionary atom U 'nearest' to R E.col(j-1) = U; // ...save it in j^th column of E I(j-1) = imax; // ...and save column index of U X(imax) = 1.0f; // Set temporarily 1.0 to mark traversed. // Map to pre-allocated workspace. Index p = dworkOffset; new (&ETblk) MapMtrxf(&dwork[p],j,ndim); p = p + align_padded(j*ndim); new (&Fblk) MapMtrxf(&dwork[p],j,j); // With U added to the current set E of j nearest atoms, // optimise the coefficients of XI w.r.t this E. This is // done by projecting Y onto the subspace spanned by E. if( j > 1 ) { // Compute the product E^T(:,1:j) * E(:,1:j), // This can be done quicker by reusing the product // E^T(:,1:j-1) * E(:,1:j-1) from the previous // iteration. V.segment(0,j-1).noalias() = U.transpose() * E.block(0,0,ndim,j-1); F.col(j-1).segment(0,j-1) = V.segment(0,j-1); F.row(j-1).segment(0,j-1) = V.segment(0,j-1); F(j-1,j-1) = 1.0f; Fblk = F.block(0,0,j,j); ETblk = E.block(0,0,ndim,j).transpose(); W.segment(0,j).noalias() = ETblk * Y; // Solve (E^T*E)*XI = (E^T)*Y ldlt->compute(Fblk); XI.segment(0,j) = ldlt->solve(W.segment(0,j)); //Update residual R R = Y; R.noalias() -= (E.block(0,0,ndim,j))*(XI.segment(0,j)); } else{ F(0,0) = 1.0f; XI(0) = Y.dot(U); //Update residual R R = Y; R.noalias() -= XI(0)*U; } } // Map back to code vector. for(Index i = 0; i < latm; ++i){ X(I(i)) = XI(i); } } //-------------------------------------------------------------------------
5,329
C++
.cpp
148
31.959459
81
0.589073
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,819
MessageLogger.h
codearxiv_PCReconstruct/MessageLogger.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef MESSAGELOGGER_H #define MESSAGELOGGER_H #include <QObject> #include <QRecursiveMutex> //QT_BEGIN_NAMESPACE //class QPlainTextEdit; //QT_END_NAMESPACE class MessageLogger : public QObject { Q_OBJECT public: explicit MessageLogger(QObject *parent = nullptr); ~MessageLogger(); void logMessage(const QString& text, bool append = true); void logProgress(const QString& msgPrefix, size_t i, size_t n, int infreq, size_t& threshold, size_t& lastPos); signals: void undo(); void logTextAppend(const QString& text); void logTextInsert(const QString& text); private: //QPlainTextEdit *m_logText; size_t m_lastPos = 0; QRecursiveMutex m_recMutex; }; #endif // MESSAGELOGGER_H
880
C++
.h
29
28.413793
64
0.711058
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,821
Window.h
codearxiv_PCReconstruct/Window.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef WINDOW_H #define WINDOW_H #include "MessageLogger.h" #include "constants.h" //#include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <QWidget> QT_BEGIN_NAMESPACE class QSlider; class QPushButton; class QMainWindow; QT_END_NAMESPACE class GLWidget; class Window : public QWidget { Q_OBJECT typedef pcl::PointCloud<pcl::PointXYZ>::Ptr CloudPtr; public: Window(QMainWindow *mw, MessageLogger* msgLogger = nullptr); public slots: void setCloud(CloudPtr cloud) { emit cloudChanged(cloud); } void getCloud(CloudPtr& cloud) { emit cloudQueried(cloud); } void undoCloud() { emit cloudUndo(); } void viewGLCloudNorms(bool enabled) { emit cloudNormsViewGL(enabled); } void setRandomCloud(size_t nPoints) { emit cloudSetRandom(nPoints); } void setCloudBBox(float minBBox[3], float maxBBox[3]) { emit cloudSetBBox(minBBox, maxBBox); } void approxCloudNorms(int nIters, size_t kNN) { emit cloudApproxNorms(nIters, kNN); } void decimateCloud(size_t nHoles, size_t kNN) { emit cloudDecimate(nHoles, kNN); } void sparsifyCloud(float percent) { emit cloudSparsify(percent); } void reconstructCloud( int kSVDIters, size_t kNN, size_t nfreq, float densify, size_t natm, size_t latm, size_t maxNewPoints, bool looseBBox, SparseApprox method) { emit cloudReconstruct( kSVDIters, kNN, nfreq, densify, natm, latm, maxNewPoints, looseBBox, method); } void setPointSize(float size) { emit pointSizeChanged(size); } void setNormScale(float scale) { emit normScaleChanged(scale); } void changeBBoxFields(float minBBox[3], float maxBBox[3]) { emit bBoxFieldsChanged(minBBox, maxBBox);} signals: void cloudChanged(CloudPtr cloud); void cloudQueried(CloudPtr& cloud); void cloudUndo(); void cloudNormsViewGL(bool enabled); void cloudSetRandom(size_t nPoints); void cloudSetBBox(float minBBox[3], float maxBBox[3]); void cloudApproxNorms(int nIters, size_t kNN); void cloudDecimate(size_t nHoles, size_t kNN); void cloudSparsify(float percent); void cloudReconstruct( int kSVDIters, size_t kNN, size_t nfreq, float densify, size_t natm, size_t latm, size_t maxNewPoints, bool looseBBox, SparseApprox method); void pointSizeChanged(float size); void normScaleChanged(float scale); void bBoxFieldsChanged(float minBBox[3], float maxBBox[3]); protected: void keyPressEvent(QKeyEvent *event) override; private: QSlider *createSlider(); GLWidget *glWidget; QMainWindow *mainWindow; MessageLogger* m_msgLogger; }; #endif
2,896
C++
.h
82
30.829268
68
0.71553
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,822
MainWindow.h
codearxiv_PCReconstruct/MainWindow.h
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef MAINWINDOW_H #define MAINWINDOW_H #include "constants.h" //#include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <QMainWindow> QT_BEGIN_NAMESPACE class QAction; class QMenu; class QPlainTextEdit; class QListWidget; QT_END_NAMESPACE class GLWidget; class Window; class MessageLogger; class RandomSurfDialog; class BoundBoxDialog; class NormalsDialog; class DecimateDialog; class SparsifyDialog; class ReconstructDialog; class OptionsDialog; class MainWindow : public QMainWindow { Q_OBJECT typedef pcl::PointCloud<pcl::PointXYZ>::Ptr CloudPtr; public: explicit MainWindow(QWidget *parent = nullptr); void badInputMessageBox(const QString& info); private: void open(); void saveAs(); void undo(); void viewGLNorms(bool enabled); void setRandom(); void setBBox(); void approxNorms(); void decimate(); void sparsify(); void reconstruct(); void options(); void about(); public slots: void changeBBoxFields(float minBBox[3], float maxBBox[3]); void appendLogText(const QString& text); void insertLogText(const QString& text); signals: void cloudChanged(CloudPtr cloud); void cloudQueried(CloudPtr& cloud); void cloudUndo(); void cloudNormsViewGL(bool enabled); void cloudSetRandom(size_t nPoints); void cloudSetBBox(float minBBox[3], float maxBBox[3]); void cloudApproxNorms(int nIters, size_t kNN); void cloudDecimate(size_t nHoles, size_t kNN); void cloudSparsify(float percent); void cloudReconstruct( int kSVDIters, size_t kNN, size_t nfreq, float densify, size_t natm, size_t latm, size_t maxNewPoints, bool looseBBox, SparseApprox method); void pointSizeChanged(float size); void normScaleChanged(float scale); private: Window *centralWidget; QToolBar *mainToolBar; QStatusBar *statusBar; QToolBar *toolBar; QPlainTextEdit *logText; RandomSurfDialog *randomSurfDialog; BoundBoxDialog *boundBoxDialog; NormalsDialog *normalsDialog; DecimateDialog *decimateDialog; SparsifyDialog *sparsifyDialog; ReconstructDialog *reconstructDialog; OptionsDialog *optionsDialog; MessageLogger *msgLogger; }; #endif // MAINWINDOW_H
2,377
C++
.h
81
25.91358
68
0.762577
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,823
GLWidget.h
codearxiv_PCReconstruct/GLWidget.h
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /**************************************************************************** ** Peter Beben: heavily modified this file for the purpose of point ** cloud visualization in this project. ** Views ALL points in the point cloud without any pruning (so it ** must be small enough to fit into video memory!!). ****************************************************************************/ #ifndef GLWIDGET_H #define GLWIDGET_H #include "BoundBox.h" #include "Cloud.h" #include "CloudWorker.h" //#include "MessageLogger.h" #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <QOpenGLWidget> #include <QOpenGLFunctions> #include <QOpenGLVertexArrayObject> #include <QOpenGLBuffer> #include <QMatrix4x4> #include <QRecursiveMutex> class MessageLogger; class CloudWorker; QT_BEGIN_NAMESPACE class QThread; QT_END_NAMESPACE QT_FORWARD_DECLARE_CLASS(QOpenGLShaderProgram) class GLWidget : public QOpenGLWidget, protected QOpenGLFunctions { Q_OBJECT typedef pcl::PointCloud<pcl::PointXYZ>::Ptr CloudPtr; public: GLWidget(QWidget *parent = nullptr, MessageLogger* msgLogger = nullptr); ~GLWidget(); static bool isTransparent() { return m_transparent; } static void setTransparent(bool t) { m_transparent = t; } QSize minimumSizeHint() const override; QSize sizeHint() const override; public slots: void setVectRotation(int angle, QVector3D v); void setVectTranslation(QVector3D v); void cleanup(); void setCloud(CloudPtr cloud); void setRandomCloud(size_t nPoints); void getCloud(CloudPtr& cloud); void undoCloud(); void setCloudBBox(float minBBox[3], float maxBBox[3]); void viewGLCloudNorms(bool enabled); void approxCloudNorms(int nIters, size_t kNN) { emit cloudApproxNorms(nIters, kNN); } void decimateCloud(size_t nHoles, size_t kNN) { emit cloudDecimate(nHoles,kNN); } void sparsifyCloud(float percent) { emit cloudSparsify(percent); } void reconstructCloud( int kSVDIters, size_t kNN, size_t nfreq, float densify, size_t natm, size_t latm, size_t maxNewPoints, bool looseBBox, SparseApprox method) { emit cloudReconstruct( kSVDIters, kNN, nfreq, densify, natm, latm, maxNewPoints, looseBBox, method); } void setPointSize(float size) { m_pointSize = size; } void setNormScale(float scale) { setGLCloudNorms(scale*m_modelSize); } void updateCloud(bool updateBBox); signals: void vectRotationChanged(int angle, QVector3D v); void vectTranslationChanged(QVector3D v); //void cloudSetRandom(size_t nPoints); void cloudApproxNorms(int nIters, size_t kNN); void cloudDecimate(size_t nHoles, size_t kNN); void cloudSparsify(float percent); void cloudReconstruct( int kSVDIters, size_t kNN, size_t nfreq, float densify, size_t natm, size_t latm, size_t maxNewPoints, bool looseBBox, SparseApprox method); void bBoxFieldsChanged(float minBBox[3], float maxBBox[3]); void logMessage(const QString& text); protected: void initializeGL() override; void paintGL() override; void resizeGL(int width, int height) override; void mousePressEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; void wheelEvent(QWheelEvent *event) override; private: void setupVertexAttribs(QOpenGLBuffer vbo); void setGLView(); void setGLCloud(); void setGLCloudNorms(float scale); void setGLCloudDebug(); void setGLBBox( BoundBox bBox, QOpenGLBuffer vbo, QOpenGLBuffer ebo); float frobeniusNorm4x4(QMatrix4x4 M); bool m_core; int m_vRot; QPoint m_lastMousePos; //QPoint m_lastWheelPos; Cloud m_cloud; BoundBox m_cloudBBox; QOpenGLVertexArrayObject m_cloudVao; QOpenGLVertexArrayObject m_cloudBBoxVao; QOpenGLVertexArrayObject m_cloudNormsVao; QOpenGLVertexArrayObject m_cloudDebugVao; QOpenGLBuffer m_cloudVbo; QOpenGLBuffer m_cloudBBoxVbo; QOpenGLBuffer m_cloudBBoxEbo; QOpenGLBuffer m_cloudNormsVbo; QOpenGLBuffer m_cloudDebugVbo; QOpenGLShaderProgram *m_program; int m_projMatrixLoc; float m_aspectRatio; float m_nearPlane; float m_farPlane; float m_modelSize; int m_mvMatrixLoc; int m_normalMatrixLoc; int m_lightPosLoc; int m_colorLoc; int m_pointSizeLoc; float m_pointSize; float m_normScale; bool m_showCloudNorms; QMatrix4x4 m_proj; QMatrix4x4 m_camera; QMatrix4x4 m_world; QVector3D m_rotVect; QVector3D m_movVect; static bool m_transparent; MessageLogger* m_msgLogger; QThread* m_cloudThread; CloudWorker* m_cloudWorker; QRecursiveMutex m_recMutex; }; #endif
7,139
C++
.h
184
35.663043
78
0.724302
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,824
CloudWorker.h
codearxiv_PCReconstruct/CloudWorker.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef RECONSTRUCTTHREAD_H #define RECONSTRUCTTHREAD_H #include "constants.h" #include <QMutex> #include <QObject> class Cloud; class BoundBox; class CloudWorker : public QObject { Q_OBJECT public: explicit CloudWorker( Cloud& cloud, QObject *parent = nullptr); ~CloudWorker(); public slots: void approxCloudNorms(int nIters, size_t kNN); void decimateCloud(size_t nHoles, size_t kNN); void sparsifyCloud(float percent); void reconstructCloud( int kSVDIters, size_t kNN, size_t nfreq, float densify, size_t natm, size_t latm, size_t maxNewPoints, bool looseBBox, SparseApprox method); signals: void finished(bool updateBBox); private: Cloud *m_cloud; QMutex m_mutex; }; #endif // RECONSTRUCTTHREAD_H
915
C++
.h
32
26.5
65
0.718391
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,825
constants.h
codearxiv_PCReconstruct/constants.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef CONSTANTS_H #define CONSTANTS_H #include <limits> const float float_infinity = std::numeric_limits<float>::infinity(); const float float_tiny = std::numeric_limits<float>::min(); const double double_infinity = std::numeric_limits<double>::infinity(); const int int_infinity = std::numeric_limits<int>::max(); enum class SparseApprox { OrthogonalPursuit = 0, MatchingPursuit = 1 }; #endif // CONSTANTS_H
612
C++
.h
12
48.166667
72
0.655932
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,826
Cloud.h
codearxiv_PCReconstruct/Cloud.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef CLOUD_H #define CLOUD_H #include "Cover_Tree.h" #include "CoverTreePoint.h" #include "BoundBox.h" #include "constants.h" //#include "MessageLogger.h" #include <Eigen/Core> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <qopengl.h> #include <QObject> #include <QRecursiveMutex> //#include <QMutexLocker> #include <vector> #include <functional> class MessageLogger; class BoundBox; class Cloud : public QObject { Q_OBJECT template<typename T> using vector = std::vector<T>; using Index = Eigen::Index; using Vector3f = Eigen::Vector3f; using Matrix3f = Eigen::Matrix3f; typedef pcl::PointCloud<pcl::PointXYZ>::Ptr CloudPtr; public: Cloud(MessageLogger* msgLogger = nullptr, QObject *parent = nullptr); ~Cloud(); const Vector3f point(size_t idx) const { return m_cloud[idx]; } const GLfloat* vertGLData(); const GLfloat* normGLData(float scale); const GLfloat* debugGLData(); size_t pointCount() const { return m_cloud.size(); } size_t pointCountOrig() const { return m_npointsOrig; } size_t debugCount() const { return m_debug.size(); } void setBoundBox(BoundBox *bBox); void invalidateCT(); void clear(); void backup(); void restore(); void fromPCL(CloudPtr cloud); void toPCL(CloudPtr& cloud); void fromRandomPlanePoints( Vector3f norm, size_t npoints, const std::function<float(float xu, float xv)> heightFun = nullptr); size_t addPoint(const Vector3f& v, const Vector3f &n, bool threadSafe = false); void replacePoint( size_t idx, const Vector3f& v, const Vector3f &n, bool threadSafe = false); Vector3f approxNorm( const Vector3f& p, int iters, const vector<CoverTreePoint<Vector3f>>& neighs, vector<Vector3f>& vneighs, vector<Vector3f>& vwork) const; void pointKNN( const Vector3f& p, size_t kNN, vector<CoverTreePoint<Vector3f>>& neighs) const; void buildSpatialIndex(bool useBBox = true); void approxCloudNorms(int iters=25, size_t kNN=25); void decimate(size_t nHoles, size_t kNN); void sparsify(float percent); void reconstruct( int kSVDIters, size_t kNN, size_t nfreq, float densify, size_t natm, size_t latm, size_t maxNewPoints, bool looseBBox, SparseApprox method = SparseApprox::OrthogonalPursuit); private: void getNeighVects(const Vector3f& p, const vector<CoverTreePoint<Vector3f>>& neighs, vector<Vector3f>& vneighs) const; vector<Vector3f> m_cloud; vector<Vector3f> m_norms; vector<Vector3f> m_cloud_bak; vector<Vector3f> m_norms_bak; vector<std::pair<Vector3f,Vector3f>> m_debug; vector<GLfloat> m_vertGL; vector<GLfloat> m_normGL; vector<GLfloat> m_debugGL; BoundBox* m_bBox = nullptr; CoverTree<CoverTreePoint<Vector3f>> *m_CT; bool m_CTStale = true; size_t m_npointsCT = 0; MessageLogger* m_msgLogger; QRecursiveMutex m_recMutex; size_t m_npointsOrig = 0; }; #endif // CLOUD_H
3,147
C++
.h
91
30.868132
72
0.710788
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,827
BoundBox.h
codearxiv_PCReconstruct/BoundBox.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef BOUNDBOX_H #define BOUNDBOX_H #include "pt_to_pt_distsq.h" #include <qopengl.h> #include <Eigen/Dense> #include <array> class MessageLogger; class Cloud; class BoundBox { using Index = Eigen::Index; using Vector3f = Eigen::Vector3f; public: BoundBox(MessageLogger* msgLogger = nullptr): m_msgLogger(msgLogger){} BoundBox( const float minBBox[3], const float maxBBox[3], MessageLogger* msgLogger = nullptr); BoundBox(const Cloud& cloud, MessageLogger* msgLogger = nullptr); void set(const float minBBox[3], const float maxBBox[3]); void set(const Cloud& cloud); void pad(float padX, float padY, float padZ); void rescale(float frac); void setParentCloud(Cloud *cloud); int vertCount() const { return m_vertCount; } void getExtents(float minBBox[], float maxBBox[]) const { for(int i=0; i < 3; ++i){ minBBox[i] = m_minBBox[i]; maxBBox[i] = m_maxBBox[i]; } } float diagonalSize() const { return sqrt(pt_to_pt_distsq(m_minBBox, m_maxBBox)); } const GLfloat *vertGLData(); const GLuint *elemGLData() const { return static_cast<const GLuint*>(m_elemGL.data()); } bool pointInBBox(const Vector3f& p) const { return p(0) >= m_minBBox[0] && p(0) <= m_maxBBox[0] && p(1) >= m_minBBox[1] && p(1) <= m_maxBBox[1] && p(2) >= m_minBBox[2] && p(2) <= m_maxBBox[2]; } float ballInBBox(const Vector3f& p, float radius) const { return p(0) - m_minBBox[0] >= radius && p(1) - m_minBBox[1] >= radius && p(2) - m_minBBox[2] >= radius && m_maxBBox[0] - p(0) >= radius && m_maxBBox[1] - p(1) >= radius && m_maxBBox[2] - p(2) >= radius; } void logMessageBBox() const; private: float m_minBBox[3] = {0.0f,0.0f,0.0f}; float m_maxBBox[3] = {0.0f,0.0f,0.0f}; int m_vertCount = 0; std::array<GLfloat, 8*6> m_vertGL; Cloud* m_cloud = nullptr; static constexpr std::array<GLuint, 24> m_elemGL = { 0, 1, 0, 2, 0, 4, 1, 3, 1, 5, 2, 3, 2, 6, 3, 7, 4, 5, 4, 6, 5, 7, 6, 7 }; MessageLogger* m_msgLogger; }; #endif // BOUNDBOX_H
2,207
C++
.h
76
26.315789
71
0.640625
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,828
alignment.h
codearxiv_PCReconstruct/alignment.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef ALIGNMENT_H #define ALIGNMENT_H #include <Eigen/Dense> #define ALIGNED_MEMORY #ifdef ALIGNED_MEMORY const size_t ALIGNEDX = Eigen::Aligned16; inline size_t align_padded(size_t n) { return ALIGNEDX > 0 ? ALIGNEDX*(1+((n-1)/ALIGNEDX)) : n; } #else const size_t ALIGNEDX = Eigen::Unaligned; inline size_t align_padded(size_t n) { return n; } #endif #endif // ALIGNMENT_H
563
C++
.h
17
31.647059
64
0.654917
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,829
BoundBoxDialog.h
codearxiv_PCReconstruct/dialogs/BoundBoxDialog.h
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef BOUNDBOXDIALOG_H #define BOUNDBOXDIALOG_H #include <QWidget> #include <QDialog> #include <QObject> QT_BEGIN_NAMESPACE class QFormLayout; class QLineEdit; class QDialogButtonBox; class QDoubleValidator; QT_END_NAMESPACE class BoundBoxDialog : public QDialog { Q_OBJECT public: BoundBoxDialog(QWidget *parent = nullptr); bool getFields(float minBBox[], float maxBBox[]) const; void setFields(const float minBBox[3], const float maxBBox[3]); private: QFormLayout *form; QLineEdit* minLineEdit[3]; QLineEdit* maxLineEdit[3]; QDialogButtonBox *buttonBox; QDoubleValidator *validator; }; #endif // BOUNDBOXDIALOG_H
773
C++
.h
28
25.214286
64
0.775815
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,830
DecimateDialog.h
codearxiv_PCReconstruct/dialogs/DecimateDialog.h
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef DECIMATEDIALOG_H #define DECIMATEDIALOG_H #include <QWidget> #include <QDialog> #include <QObject> QT_BEGIN_NAMESPACE class QFormLayout; class QLineEdit; class QDialogButtonBox; class QIntValidator; QT_END_NAMESPACE class DecimateDialog : public QDialog { Q_OBJECT public: DecimateDialog(QWidget *parent = nullptr); bool getFields(size_t& nHoles, size_t& kNN) const; private: QFormLayout *form; QLineEdit *nHolesLineEdit; QLineEdit *nPointsLineEdit; QDialogButtonBox *buttonBox; QIntValidator *validator; }; #endif // DECIMATEDIALOG_H
677
C++
.h
27
23.444444
64
0.804992
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,831
ReconstructDialog.h
codearxiv_PCReconstruct/dialogs/ReconstructDialog.h
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef RECONSTRUCTDIALOG_H #define RECONSTRUCTDIALOG_H #include "constants.h" #include <QWidget> #include <QDialog> #include <QObject> QT_BEGIN_NAMESPACE class QFormLayout; class QLineEdit; class QDialogButtonBox; class QIntValidator; class QDoubleValidator; class QComboBox; QT_END_NAMESPACE class ReconstructDialog : public QDialog { Q_OBJECT public: ReconstructDialog(QWidget *parent = nullptr); int getFields( int& kSVDIters, size_t& kNN, size_t& nfreq, float& densify, size_t& natm, size_t& latm, size_t& maxNewPoints, bool& looseBBox, SparseApprox& method) const; public slots: void bBoxComboChanged(int idx) { m_bBoxComboIdx = idx; } void methodComboChanged(int idx) { m_methodComboIdx = idx; } private: QFormLayout *form; QLineEdit *nItersLineEdit; QLineEdit *kNNLineEdit; QLineEdit *nFreqLineEdit; QLineEdit *densifyLineEdit; QLineEdit *nAtmLineEdit; QLineEdit *lAtmLineEdit; QLineEdit *maxNewLineEdit; QComboBox *bBoxComboBox; int m_bBoxComboIdx = 0; QComboBox *methodComboBox; int m_methodComboIdx = 0; QDialogButtonBox *buttonBox; QIntValidator *intValidator; QDoubleValidator *doubleValidator; }; #endif // RECONSTRUCTDIALOG_H
1,322
C++
.h
46
26.347826
71
0.783399
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,832
get_field.h
codearxiv_PCReconstruct/dialogs/get_field.h
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef GET_FIELD_H #define GET_FIELD_H #include <QObject> QT_BEGIN_NAMESPACE class QLineEdit; class QIntValidator; class QDoubleValidator; QT_END_NAMESPACE bool get_integer_field( QLineEdit *lineEdit, QIntValidator *validator, size_t& field); bool get_float_field( QLineEdit *lineEdit, QDoubleValidator *validator, float& field); #endif // GET_FIELD_H
480
C++
.h
15
30.333333
66
0.782135
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,833
OptionsDialog.h
codearxiv_PCReconstruct/dialogs/OptionsDialog.h
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef OPTIONSDIALOG_H #define OPTIONSDIALOG_H #include <QWidget> #include <QDialog> #include <QObject> QT_BEGIN_NAMESPACE class QFormLayout; class QLineEdit; class QDialogButtonBox; class QDoubleValidator; QT_END_NAMESPACE class OptionsDialog : public QDialog { Q_OBJECT public: OptionsDialog(QWidget *parent = nullptr); bool getFields(float& pointSize, float& normScale) const; private: QFormLayout *form; QLineEdit *pointSizeLineEdit; QLineEdit *normScaleLineEdit; QDialogButtonBox *buttonBox; QDoubleValidator *validator; }; #endif // OPTIONSDIALOG_H
705
C++
.h
27
23.925926
64
0.793722
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,834
NormalsDialog.h
codearxiv_PCReconstruct/dialogs/NormalsDialog.h
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef NORMALSDIALOG_H #define NORMALSDIALOG_H #include <QWidget> #include <QDialog> #include <QObject> QT_BEGIN_NAMESPACE class QFormLayout; class QLineEdit; class QDialogButtonBox; class QIntValidator; QT_END_NAMESPACE class NormalsDialog : public QDialog { Q_OBJECT public: NormalsDialog(QWidget *parent = nullptr); bool getFields(int& nIters, size_t& kNN) const; private: QFormLayout *form; QLineEdit *nItersLineEdit; QLineEdit *kNNLineEdit; QDialogButtonBox *buttonBox; QIntValidator *validator; }; #endif // NORMALSDIALOG_H
665
C++
.h
27
23
64
0.802862
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,835
SparsifyDialog.h
codearxiv_PCReconstruct/dialogs/SparsifyDialog.h
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef SPARSIFYDIALOG_H #define SPARSIFYDIALOG_H #include <QWidget> #include <QDialog> #include <QObject> QT_BEGIN_NAMESPACE class QFormLayout; class QLineEdit; class QDialogButtonBox; class QDoubleValidator; QT_END_NAMESPACE class SparsifyDialog : public QDialog { Q_OBJECT public: SparsifyDialog(QWidget *parent = nullptr); bool getFields(float& percent) const; private: QFormLayout *form; QLineEdit *percentLineEdit; QDialogButtonBox *buttonBox; QDoubleValidator *validator; }; #endif // SPARSIFYDIALOG_H
641
C++
.h
26
23.076923
64
0.810544
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,836
RandomSurfDialog.h
codearxiv_PCReconstruct/dialogs/RandomSurfDialog.h
// Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef SETRANDOMDIALOG_H #define SETRANDOMDIALOG_H #include <QWidget> #include <QDialog> #include <QObject> QT_BEGIN_NAMESPACE class QFormLayout; class QLineEdit; class QDialogButtonBox; class QIntValidator; QT_END_NAMESPACE class RandomSurfDialog : public QDialog { Q_OBJECT public: RandomSurfDialog(QWidget *parent = nullptr); bool getFields(size_t& nPoints) const; private: QFormLayout *form; QLineEdit *nPointsLineEdit; QDialogButtonBox *buttonBox; QIntValidator *validator; }; #endif // SETRANDOMDIALOG_H
646
C++
.h
26
23.153846
64
0.805556
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,838
CoverTreePoint.h
codearxiv_PCReconstruct/Cover-Tree/CoverTreePoint.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. // Brief description // Point on a cover tree stored as a vector in Eigen. #ifndef _COVERTREEPOINT_H #define _COVERTREEPOINT_H #include "pt_to_pt_distsq.h" #include <iostream> template<class T> class CoverTreePoint { private: T _vec; size_t _id; public: CoverTreePoint(T v, size_t id) : _vec(v), _id(id) {} CoverTreePoint(){} ~CoverTreePoint(){} double distance(const CoverTreePoint<T>& p) const; const T& getVec() const; size_t getId() const; void set(const T& v, size_t id); void print() const; bool operator==(const CoverTreePoint<T>&) const; }; template<class T> double CoverTreePoint<T>::distance(const CoverTreePoint<T>& p) const { const T& vec2 = p.getVec(); assert(vec2.size() == _vec.size()); double distsq = 0.0; size_t n = size_t(_vec.size()); for(size_t i=0; i < n; ++i) { distsq += (_vec[i]-vec2[i])*(_vec[i]-vec2[i]); } return distsq; } template<class T> const T& CoverTreePoint<T>::getVec() const { return _vec; } template<class T> size_t CoverTreePoint<T>::getId() const { return _id; } template<class T> void CoverTreePoint<T>::set(const T& v, size_t id) { _vec = v; _id = id; } template<class T> void CoverTreePoint<T>::print() const { std::cout << "point " << _id << ": " << _vec << "\n"; } template<class T> bool CoverTreePoint<T>::operator==(const CoverTreePoint<T>& p) const { return (_id==p.getId()); } #endif // _COVERTREEPOINT_H
1,655
C++
.h
58
25.413793
71
0.632928
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,839
Plane.h
codearxiv_PCReconstruct/utils/Plane.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef PLANE_H #define PLANE_H #include <Eigen/Dense> class Plane { using Index = Eigen::Index; using Matrix3f = Eigen::Matrix3f; using Vector3f = Eigen::Vector3f; using Vector2f = Eigen::Vector2f; public: Plane(const Vector3f p0, const Vector3f norm) { set(p0,norm); } void set(const Vector3f p0, const Vector3f norm); Vector2f project_uv(const Vector3f q); Vector3f project(const Vector3f q, Vector2f& puv); void getUVAxes(Vector3f& u, Vector3f& v) {u = m_u; v = m_v;} private: Vector3f m_p0; Vector3f m_norm; Vector3f m_u; Vector3f m_v; }; #endif // PLANE_H
757
C++
.h
25
28.4
64
0.679115
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,840
cloud_normal.h
codearxiv_PCReconstruct/utils/cloud_normal.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef CLOUD_NORMAL_H #define CLOUD_NORMAL_H #include <Eigen/Dense> #include <vector> Eigen::Vector3f cloud_normal( const Eigen::Vector3f& p0, const std::vector<Eigen::Vector3f>& cloud, int niters, std::vector<Eigen::Vector3f>& vwork); #endif // CLOUD_NORMAL_H
446
C++
.h
11
38.545455
71
0.64486
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,841
rotations.h
codearxiv_PCReconstruct/utils/rotations.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef ROTATIONS_H #define ROTATIONS_H #include <Eigen/Dense> void vector_to_vector_rotation_matrix( const Eigen::Vector3f& v, const Eigen::Vector3f& w, bool normalized, bool lineThruW, Eigen::Matrix3f& M); void angle_vector_rotation_matrix( float angle, const Eigen::Vector3f& u, Eigen::Matrix3f& M); void cos_sin_angle_vector_rotation_matrix( float cosa, float sina, const Eigen::Vector3f& u, Eigen::Matrix3f& M); #endif // ROTATIONS_H
630
C++
.h
16
37.25
61
0.680921
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,842
ensure_buffer_size.h
codearxiv_PCReconstruct/utils/ensure_buffer_size.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef ENSURE_BUFFER_SIZE_H #define ENSURE_BUFFER_SIZE_H #include <vector> //----------------------------------------------------------- template <typename T, typename Allocator = std::allocator<T>> void ensure_buffer_size(size_t sizeEnsure, std::vector<T, Allocator>& buffer) { if( buffer.capacity() < sizeEnsure ) buffer.reserve(2*sizeEnsure); if( buffer.size() < sizeEnsure ) buffer.resize(sizeEnsure); } //----------------------------------------------------------- #endif // ENSURE_BUFFER_SIZE_H
712
C++
.h
15
44
78
0.536189
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,535,843
pt_to_pt_distsq.h
codearxiv_PCReconstruct/utils/pt_to_pt_distsq.h
//----------------------------------------------------------- // Copyright (C) 2019 Piotr (Peter) Beben <pdbcas@gmail.com> // See LICENSE included with this distribution. #ifndef PT_TO_PT_DISTSQ_H #define PT_TO_PT_DISTSQ_H #include <Eigen/Dense> double pt_to_pt_distsq(const Eigen::VectorXf& v, const Eigen::VectorXf& w); double pt_to_pt_distsq(const float v[3], const float w[3]); #endif // PT_TO_PT_DISTSQ_H
435
C++
.h
9
44.777778
76
0.61165
codearxiv/PCReconstruct
38
8
2
LGPL-2.1
9/20/2024, 10:44:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false