source: pcp/src/perturbed.c@ 2399875

Last change on this file since 2399875 was 2399875, checked in by Frederik Heber <heber@…>, 17 years ago

CalculatePerturbationOperator_RxP(): commented-out lines for gathering max/min values added

  • Property mode set to 100644
File size: 209.0 KB
Line 
1/** \file perturbed.c
2 * Perturbation calculation due to external magnetic field.
3 *
4 * Central function is MinimisePerturbed() wherein the actual minimisation of the two different operators with each
5 * three components takes place subsequently. Helpful routines are CalculatePerturbationOperator_P() - which applies a
6 * specified component of p on the current wave function - and CalculatePerturbationOperator_RxP() - which does the
7 * same for the RxP operator.
8 * The actual minimisation loop FindPerturbedMinimum() depends on the same routines also used for the occupied orbitals,
9 * however with a different energy functional and derivatives, evaluated in Calculate1stPerturbedDerivative() and
10 * Calculate2ndPerturbedDerivative(). InitPerturbedEnergyCalculation() calculates the total energy functional
11 * perturbed in second order for all wave functions, UpdatePerturbedEnergyCalculation() just updates the one
12 * for the wave function after it has been minimised during the line search. Both use CalculatePerturbedEnergy() which
13 * evaluates the energy functional (and the gradient if specified).
14 * Finally, FillCurrentDensity() evaluates the current density at a given point in space using the perturbed
15 * wave functions. Afterwards by calling CalculateMagneticSusceptibility() or
16 * CalculateChemicalShieldingByReciprocalCurrentDensity() susceptibility respectively shielding tensor are possible uses
17 * of this current density.
18 *
19 * There are also some test routines: TestCurrent() checks whether the integrated current is zero in each component.
20 * test_fft_symmetry() tests the "pulling out imaginary unit" before fourier transformation on a given wave function.
21 * CheckOrbitalOverlap() outputs the overlap matrix for the wave functions of a given minimisation state, this might
22 * be important for the additional \f$\Delta J{ij}\f$ contribution to the current density, which is non-zero for
23 * non-zero mutual overlap, which is evaluated if FillDeltaCurrentDensity() is called.
24 *
25 * Finally, there are also some smaller routines: truedist() gives the correct relative distance between two points
26 * in the unit cell under periodic boundary conditions with minimum image convention. ApplyTotalHamiltonian() returns
27 * the hamiltonian applied to a given wave function. sawtooth() is a sawtooth implementation which is needed in order
28 * to avoid flipping of position eigenvalues for nodes close to or on the cell boundary. CalculateOverlap()
29 * is used in the energy functional derivatives, keeping an overlap table between perturbed wave functions up to date.
30 * fft_Psi() is very similar to CalculateOneDensityR(), it does the extension of the wave function to the upper level
31 * RunStruct#Lev0 while fouriertransforming it to real space. cross() gives correct indices in evaluating a vector cross
32 * product. AllocCurrentDensity() and DisAllocCurrentDensity() mark the current density arrays as currently being in use or not.
33 *
34 Project: ParallelCarParrinello
35 \author Frederik Heber
36 \date 2006
37
38*/
39
40#include <stdlib.h>
41#include <stdio.h>
42#include <math.h>
43#include <string.h>
44#include <time.h>
45#include <gsl/gsl_matrix.h>
46#include <gsl/gsl_eigen.h>
47#include <gsl/gsl_complex.h>
48#include <gsl/gsl_complex_math.h>
49#include <gsl/gsl_sort_vector.h>
50#include <gsl/gsl_linalg.h>
51#include <gsl/gsl_multimin.h>
52
53#include "data.h"
54#include "density.h"
55#include "energy.h"
56#include "excor.h"
57#include "errors.h"
58#include "grad.h"
59#include "gramsch.h"
60#include "mergesort2.h"
61#include "helpers.h"
62#include "init.h"
63#include "myfft.h"
64#include "mymath.h"
65#include "output.h"
66#include "pcp.h"
67#include "perturbed.h"
68#include "run.h"
69#include "wannier.h"
70
71
72/** Minimisation of the PsiTypeTag#Perturbed_RxP0, PsiTypeTag#Perturbed_P0 and other orbitals.
73 * For each of the above PsiTypeTag we go through the following before the minimisation loop:
74 * -# ResetGramSchTagType() resets current type that is to be minimised to NotOrthogonal.
75 * -# UpdateActualPsiNo() steps on to next perturbed of current PsiTypeTag type.
76 * -# GramSch() orthonormalizes perturbed wave functions.
77 * -# TestGramSch() tests if orthonormality was achieved.
78 * -# InitDensityCalculation() gathers densities from all wave functions (and all processes), within SpeedMeasure() DensityTime.
79 * -# InitPerturbedEnergyCalculation() performs initial calculation of the perturbed energy functional.
80 * -# RunStruct#OldActualLocalPsiNo is set to RunStruct#ActualLocalPsiNo, immediately followed by UpdateGramSchOldActualPsiNo()
81 * to bring info on all processes on par.
82 * -# UpdatePerturbedEnergyCalculation() re-calculates Gradient and GradientTypes#H1cGradient for RunStruct#ActualLocalPsiNo
83 * -# EnergyAllReduce() gathers various energy terms and sums up into Energy#TotalEnergy.
84 *
85 * And during the minimisation loop:
86 * -# FindPerturbedMinimum() performs the gradient conjugation, the line search and wave function update.
87 * -# UpdateActualPsiNo() steps on to the next wave function, orthonormalizing by GramSch() if necessary.
88 * -# UpdateEnergyArray() shifts TotalEnergy values to make space for new one.
89 * -# There is no density update as the energy function does not depend on the changing perturbed density but only on the fixed
90 * unperturbed one.
91 * -# UpdatePerturbedEnergyCalculation() re-calculates the perturbed energy of the changed wave function.
92 * -# EnergyAllReduce() gathers energy terms and sums up.
93 * -# CheckCPULIM() checks if external Stop signal has been given.
94 * -# CalculateMinimumStop() checks whether we have dropped below a certain minimum change during minimisation of total energy.
95 * -# finally step counters LatticeLevel#Step and SpeedStruct#Steps are increased.
96 *
97 * After the minimisation loop:
98 * -# SetGramSchExtraPsi() removes extra Psis from orthogonaliy check.
99 * -# ResetGramSchTagType() sets GramSchToDoType to NotUsedtoOrtho.
100 *
101 * And after all minimisation runs are done:
102 * -# UpdateActualPsiNo() steps back to PsiTypeTag#Occupied type.
103 *
104 * At the end we return to Occupied wave functions.
105 * \param *P at hand
106 * \param *Stop flag to determine if epsilon stop conditions have met
107 * \param *SuperStop flag to determinte whether external signal's required end of calculations
108 */
109void MinimisePerturbed (struct Problem *P, int *Stop, int *SuperStop) {
110 struct RunStruct *R = &P->R;
111 struct Lattice *Lat = &P->Lat;
112 struct Psis *Psi = &Lat->Psi;
113 int type, flag = 0;//,i;
114
115 for (type=Perturbed_P0;type<=Perturbed_RxP2;type++) { // go through each perturbation group separately //
116 *Stop=0; // reset stop flag
117 if(P->Call.out[LeaderOut]) fprintf(stderr,"(%i)Beginning perturbed minimisation of type %s ...\n", P->Par.me, R->MinimisationName[type]);
118 //OutputOrbitalPositions(P, Occupied);
119 R->PsiStep = R->MaxPsiStep; // reset in-Psi-minimisation-counter, so that we really advance to the next wave function
120 UpdateActualPsiNo(P, type); // step on to next perturbed one
121
122 if(P->Call.out[MinOut]) fprintf(stderr, "(%i) Re-initializing perturbed psi array for type %s ", P->Par.me, R->MinimisationName[type]);
123 if (P->Call.ReadSrcFiles && (flag = ReadSrcPsiDensity(P,type,1, R->LevS->LevelNo))) {// in flag store whether stored Psis are readible or not
124 SpeedMeasure(P, InitSimTime, StartTimeDo);
125 if(P->Call.out[MinOut]) fprintf(stderr,"from source file of recent calculation\n");
126 ReadSrcPsiDensity(P,type, 0, R->LevS->LevelNo);
127 ResetGramSchTagType(P, Psi, type, IsOrthogonal); // loaded values are orthonormal
128 SpeedMeasure(P, DensityTime, StartTimeDo);
129 //InitDensityCalculation(P);
130 SpeedMeasure(P, DensityTime, StopTimeDo);
131 R->OldActualLocalPsiNo = R->ActualLocalPsiNo; // needed otherwise called routines in function below crash
132 UpdateGramSchOldActualPsiNo(P,Psi);
133 InitPerturbedEnergyCalculation(P, 1); // go through all orbitals calculate each H^{(0)}-eigenvalue, recalc HGDensity, cause InitDensityCalc zero'd it
134 UpdatePerturbedEnergyCalculation(P); // H1cGradient and Gradient must be current ones
135 EnergyAllReduce(P); // gather energies for minimum search
136 SpeedMeasure(P, InitSimTime, StopTimeDo);
137 }
138 if ((P->Call.ReadSrcFiles != 1) || (!flag)) { // read and don't minimise only if SrcPsi were parsable!
139 SpeedMeasure(P, InitSimTime, StartTimeDo);
140 ResetGramSchTagType(P, Psi, type, NotOrthogonal); // perturbed now shall be orthonormalized
141 if ((P->Call.ReadSrcFiles != 2) || (!flag)) {
142 if (R->LevSNo == Lat->MaxLevel-1) { // is it the starting level? (see InitRunLevel())
143 if(P->Call.out[MinOut]) fprintf(stderr, "randomly.\n");
144 InitPsisValue(P, Psi->TypeStartIndex[type], Psi->TypeStartIndex[type+1]); // initialize perturbed array for this run
145 } else {
146 if(P->Call.out[MinOut]) fprintf(stderr, "from source file of last level.\n");
147 ReadSrcPerturbedPsis(P, type);
148 }
149 }
150 SpeedMeasure(P, InitGramSchTime, StartTimeDo);
151 GramSch(P, R->LevS, Psi, Orthogonalize);
152 SpeedMeasure(P, InitGramSchTime, StopTimeDo);
153 SpeedMeasure(P, InitDensityTime, StartTimeDo);
154 //InitDensityCalculation(P);
155 SpeedMeasure(P, InitDensityTime, StopTimeDo);
156 InitPerturbedEnergyCalculation(P, 1); // go through all orbitals calculate each H^{(0)}-eigenvalue, recalc HGDensity, cause InitDensityCalc zero'd it
157 R->OldActualLocalPsiNo = R->ActualLocalPsiNo; // needed otherwise called routines in function below crash
158 UpdateGramSchOldActualPsiNo(P,Psi);
159 UpdatePerturbedEnergyCalculation(P); // H1cGradient and Gradient must be current ones
160 EnergyAllReduce(P); // gather energies for minimum search
161 SpeedMeasure(P, InitSimTime, StopTimeDo);
162 R->LevS->Step++;
163 EnergyOutput(P,0);
164 while (*Stop != 1) {
165 //debug(P,"FindPerturbedMinimum");
166 FindPerturbedMinimum(P); // find minimum
167 //debug(P,"UpdateActualPsiNo");
168 UpdateActualPsiNo(P, type); // step on to next perturbed Psi
169 //debug(P,"UpdateEnergyArray");
170 UpdateEnergyArray(P); // shift energy values in their array by one
171 //debug(P,"UpdatePerturbedEnergyCalculation");
172 UpdatePerturbedEnergyCalculation(P); // re-calc energies (which is hopefully lower)
173 EnergyAllReduce(P); // gather from all processes and sum up to total energy
174 //ControlNativeDensity(P); // check total density (summed up PertMixed must be zero!)
175 //printf ("(%i,%i,%i)S(%i,%i,%i):\t %5d %10.5f\n",P->Par.my_color_comm_ST,P->Par.me_comm_ST, P->Par.me_comm_ST_PsiT, R->MinStep, R->ActualLocalPsiNo, R->PsiStep, (int)iter, s_multi->f);
176 if (*SuperStop != 1)
177 *SuperStop = CheckCPULIM(P);
178 *Stop = CalculateMinimumStop(P, *SuperStop);
179 P->Speed.Steps++; // step on
180 R->LevS->Step++;
181 }
182 // now release normalization condition and minimize wrt to norm
183 if(P->Call.out[MinOut]) fprintf(stderr,"(%i) Writing %s srcpsi to disk\n", P->Par.me, R->MinimisationName[type]);
184 OutputSrcPsiDensity(P, type);
185// if (!TestReadnWriteSrcDensity(P,type))
186// Error(SomeError,"TestReadnWriteSrcDensity failed!");
187 }
188
189 TestGramSch(P,R->LevS,Psi, type); // functions are orthonormal?
190 // calculate current density summands
191 //if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Filling current density grid ...\n",P->Par.me);
192 SpeedMeasure(P, CurrDensTime, StartTimeDo);
193 if (*SuperStop != 1) {
194 if ((R->DoFullCurrent == 1) || ((R->DoFullCurrent == 2) && (CheckOrbitalOverlap(P) == 1))) { //test to check whether orbitals have mutual overlap and thus \\DeltaJ_{xc} must not be dropped
195 R->DoFullCurrent = 1; // set to 1 if it was 2 but Check...() yielded necessity
196 //debug(P,"Filling with Delta j ...");
197 //FillDeltaCurrentDensity(P);
198 }// else
199 //debug(P,"There is no overlap between orbitals.");
200 //debug(P,"Filling with j ...");
201 FillCurrentDensity(P);
202 }
203 SpeedMeasure(P, CurrDensTime, StopTimeDo);
204
205 SetGramSchExtraPsi(P,Psi,NotUsedToOrtho); // remove extra Psis from orthogonality check
206 ResetGramSchTagType(P, Psi, type, NotUsedToOrtho); // remove this group from the check for the next minimisation group as well!
207 }
208 UpdateActualPsiNo(P, Occupied); // step on back to an occupied one
209}
210
211/** Tests overlap matrix between each pair of orbitals for non-diagonal form.
212 * We simply check whether the overlap matrix Psis#lambda has off-diagonal entries greater MYEPSILON or not.
213 * \param *P Problem at hand
214 * \note The routine is meant as atest criteria if \f$\Delta J_[ij]\f$ contribution is necessary, as it is only non-zero if
215 * there is mutual overlap between the two orbitals.
216 */
217int CheckOrbitalOverlap(struct Problem *P)
218{
219 struct Lattice *Lat = &P->Lat;
220 struct Psis *Psi = &Lat->Psi;
221 int i,j;
222 int counter = 0;
223
224 // output matrix
225 if (P->Par.me == 0) fprintf(stderr, "(%i) S_ij =\n", P->Par.me);
226 for (i=0;i<Psi->NoOfPsis;i++) {
227 for (j=0;j<Psi->NoOfPsis;j++) {
228 if (fabs(Psi->lambda[i][j]) > MYEPSILON) counter++;
229 if (P->Par.me == 0) fprintf(stderr, "%e\t", Psi->lambda[i][j]); //Overlap[i][j]
230 }
231 if (P->Par.me == 0) fprintf(stderr, "\n");
232 }
233
234 fprintf(stderr, "(%i) CheckOverlap: %i overlaps found.\t", P->Par.me, counter);
235 if (counter > 0) return (1);
236 else return(0);
237}
238
239/** Initialization of perturbed energy.
240 * For each local wave function of the current minimisation type RunStruct#CurrentMin it is called:
241 * - CalculateNonLocalEnergyNoRT(): for the coefficient-dependent form factors
242 * - CalculatePerturbedEnergy(): for the perturbed energy, yet without gradient calculation
243 * - CalculateOverlap(): for the overlap between the perturbed wave functions of the current RunStruct#CurrentMin state.
244 *
245 * Afterwards for the two types AllPsiEnergyTypes#Perturbed1_0Energy and AllPsiEnergyTypes#Perturbed0_1Energy the
246 * energy contribution from each wave function is added up in Energy#AllLocalPsiEnergy.
247 * \param *P Problem at hand
248 * \param first state whether it is the first (1) or successive call (0), which avoids some initial calculations.
249 * \sa UpdatePerturbedEnergy()
250 * \note Afterwards EnergyAllReduce() must be called.
251 */
252void InitPerturbedEnergyCalculation(struct Problem *P, const int first)
253{
254 struct Lattice *Lat = &(P->Lat);
255 int p,i;
256 const enum PsiTypeTag state = P->R.CurrentMin;
257 for (p=Lat->Psi.TypeStartIndex[state]; p < Lat->Psi.TypeStartIndex[state+1]; p++) {
258 //if (p < 0 || p >= Lat->Psi.LocalNo) Error(SomeError,"InitPerturbedEnergyCalculation: p out of range");
259 //CalculateNonLocalEnergyNoRT(P, p); // recalculating non-local form factors which are coefficient dependent!
260 CalculatePsiEnergy(P,p,1);
261 CalculatePerturbedEnergy(P, p, 0, first);
262 CalculateOverlap(P, p, state);
263 }
264 for (i=0; i<= Perturbed0_1Energy; i++) {
265 Lat->E->AllLocalPsiEnergy[i] = 0.0;
266 for (p=0; p < Lat->Psi.LocalNo; p++)
267 if (P->Lat.Psi.LocalPsiStatus[p].PsiType == state)
268 Lat->E->AllLocalPsiEnergy[i] += Lat->E->PsiEnergy[i][p];
269 }
270}
271
272
273/** Updating of perturbed energy.
274 * For current and former (if not the same) local wave function RunStruct#ActualLocal, RunStruct#OldActualLocalPsiNo it is called:
275 * - CalculateNonLocalEnergyNoRT(): for the form factors
276 * - CalculatePerturbedEnergy(): for the perturbed energy, gradient only for RunStruct#ActualLocal
277 * - CalculatePerturbedOverlap(): for the overlap between the perturbed wave functions
278 *
279 * Afterwards for the two types AllPsiEnergyTypes#Perturbed1_0Energy and AllPsiEnergyTypes#Perturbed0_1Energy the
280 * energy contribution from each wave function is added up in Energy#AllLocalPsiEnergy.
281 * \param *P Problem at hand
282 * \sa CalculatePerturbedEnergy() called from here.
283 * \note Afterwards EnergyAllReduce() must be called.
284 */
285void UpdatePerturbedEnergyCalculation(struct Problem *P)
286{
287 struct Lattice *Lat = &(P->Lat);
288 struct Psis *Psi = &Lat->Psi;
289 struct RunStruct *R = &P->R;
290 const enum PsiTypeTag state = R->CurrentMin;
291 int p = R->ActualLocalPsiNo;
292 const int p_old = R->OldActualLocalPsiNo;
293 int i;
294
295 if (p != p_old) {
296 //if (p_old < 0 || p_old >= Lat->Psi.LocalNo) Error(SomeError,"UpdatePerturbedEnergyCalculation: p_old out of range");
297 //CalculateNonLocalEnergyNoRT(P, p_old);
298 CalculatePsiEnergy(P,p_old,0);
299 CalculatePerturbedEnergy(P, p_old, 0, 0);
300 CalculateOverlap(P, p_old, state);
301 }
302 //if (p < 0 || p >= Lat->Psi.LocalNo) Error(SomeError,"InitPerturbedEnergyCalculation: p out of range");
303 // recalculating non-local form factors which are coefficient dependent!
304 //CalculateNonLocalEnergyNoRT(P,p);
305 CalculatePsiEnergy(P,p,0);
306 CalculatePerturbedEnergy(P, p, 1, 0);
307 CalculateOverlap(P, p, state);
308
309 for (i=0; i<= Perturbed0_1Energy; i++) {
310 Lat->E->AllLocalPsiEnergy[i] = 0.0;
311 for (p=0; p < Psi->LocalNo; p++)
312 if (Psi->LocalPsiStatus[p].PsiType == state)
313 Lat->E->AllLocalPsiEnergy[i] += Lat->E->PsiEnergy[i][p];
314 }
315}
316
317/** Calculates gradient and evaluates second order perturbed energy functional for specific wave function.
318 * The in second order perturbed energy functional reads as follows.
319 * \f[
320 * E^{(2)} = \sum_{kl} \langle \varphi_k^{(1)} | H^{(0)} \delta_{kl} - \lambda_{kl} | \varphi_l^{(1)} \rangle
321 * + \underbrace{\langle \varphi_l^{(0)} | H^{(1)} | \varphi_l^{(1)} \rangle + \langle \varphi_l^{(1)} | H^{(1)} | \varphi_l^{(0)} \rangle}_{2 {\cal R} \langle \varphi_l^{(1)} | H^{(1)} | \varphi_l^{(0)} \rangle}
322 * \f]
323 * And the gradient
324 * \f[
325 * \widetilde{\varphi}_k^{(1)} = - \sum_l ({\cal H}^{(0)} \delta_{kl} - \lambda_{kl} | \varphi_l^{(1)} \rangle + {\cal H}^{(1)} | \varphi_k^{(0)} \rangle
326 * \f]
327 * First, the HGDensity is recalculated if \a first says so - see ApplyTotalHamiltonian().
328 *
329 * Next, we need the perturbation hamiltonian acting on both the respective occupied and current wave function,
330 * see perturbed.c for respective function calls.
331 *
332 * Finally, the scalar product between the wave function and Hc_Gradient yields the eigenvalue of the hamiltonian,
333 * which is summed up over all reciprocal grid vectors and stored in OnePsiElementAddData#Lambda. The Gradient is
334 * the inverse of Hc_Gradient and with the following summation over all perturbed wave functions (MPI exchange of
335 * non-local coefficients) the gradient is computed. Here we need Psis#lambda, which is computed in CalculateHamiltonian().
336 *
337 * Also \f${\cal H}^{(1)} | \varphi_l^{(0)} \rangle\f$ is stored in GradientTypes#H1cGradient.
338 * \param *P Problem at hand, contains RunStruct, Lattice, LatticeLevel RunStruct#LevS
339 * \param l offset of perturbed wave function within Psi#LocalPsiStatus (\f$\varphi_l^{(1)}\f$)
340 * \param DoGradient (1 = yes, 0 = no) whether gradient shall be calculated or not
341 * \param first recaculate HGDensity (1) or not (0)
342 * \note DensityTypes#ActualPsiDensity must be recent for gradient calculation!
343 * \sa CalculateGradientNoRT() - same procedure for evaluation of \f${\cal H}^{(0)}| \varphi_l^{(1)} \rangle\f$
344 * \note without the simplification of \f$2 {\cal R} \langle \varphi_l^{(1)} | H^{(1)} | \varphi_l^{(0)} \rangle\f$ the
345 * calculation would be impossible due to non-local nature of perturbed wave functions. The position operator would
346 * be impossible to apply in a sensible manner.
347 */
348void CalculatePerturbedEnergy(struct Problem *P, const int l, const int DoGradient, const int first)
349{
350 struct Lattice *Lat = &P->Lat;
351 struct Psis *Psi = &Lat->Psi;
352 struct Energy *E = Lat->E;
353 struct PseudoPot *PP = &P->PP;
354 struct RunStruct *R = &P->R;
355 struct LatticeLevel *LevS = R->LevS;
356 const int state = R->CurrentMin;
357 const int l_normal = Psi->TypeStartIndex[Occupied] + (l - Psi->TypeStartIndex[state]); // offset l to \varphi_l^{(0)}
358 const int ActNum = l - Psi->TypeStartIndex[state] + Psi->TypeStartIndex[1] * Psi->LocalPsiStatus[l].my_color_comm_ST_Psi;
359 int g, i, m, j;
360 double lambda, Lambda;
361 double RElambda10, RELambda10;
362 const fftw_complex *source = LevS->LPsi->LocalPsi[l];
363 fftw_complex *grad = P->Grad.GradientArray[ActualGradient];
364 fftw_complex *Hc_grad = P->Grad.GradientArray[HcGradient];
365 fftw_complex *H1c_grad = P->Grad.GradientArray[H1cGradient];
366 fftw_complex *TempPsi_0 = H1c_grad;
367 fftw_complex *varphi_1, *varphi_0;
368 struct OnePsiElement *OnePsiB, *LOnePsiB;
369 fftw_complex *LPsiDatB=NULL;
370 const int ElementSize = (sizeof(fftw_complex) / sizeof(double));
371 int RecvSource;
372 MPI_Status status;
373
374 // ============ Calculate H^(0) psi^(1) =============================
375 //if (Hc_grad != P->Grad.GradientArray[HcGradient]) Error(SomeError,"CalculatePerturbedEnergy: Hc_grad corrupted");
376 SetArrayToDouble0((double *)Hc_grad,2*R->InitLevS->MaxG);
377 ApplyTotalHamiltonian(P,source,Hc_grad, PP->fnl[l], 1, first);
378
379 // ============ ENERGY FUNCTIONAL Evaluation PART 1 ================
380 //if (l_normal < 0 || l_normal >= Psi->LocalNo) Error(SomeError,"CalculatePerturbedEnergy: l_normal out of range");
381 varphi_0 = LevS->LPsi->LocalPsi[l_normal];
382 //if (l < 0 || l >= Psi->LocalNo) Error(SomeError,"CalculatePerturbedEnergy: l out of range");
383 varphi_1 = LevS->LPsi->LocalPsi[l];
384 //if (TempPsi_0 != P->Grad.GradientArray[H1cGradient]) Error(SomeError,"CalculatePerturbedEnergy: TempPsi_0 corrupted");
385 SetArrayToDouble0((double *)TempPsi_0,2*R->InitLevS->MaxG);
386 switch (state) {
387 case Perturbed_P0:
388 CalculatePerturbationOperator_P(P,varphi_0,TempPsi_0,0); // \nabla_0 | \varphi_l^{(0)} \rangle
389 break;
390 case Perturbed_P1:
391 CalculatePerturbationOperator_P(P,varphi_0,TempPsi_0,1); // \nabla_1 | \varphi_l^{(0)} \rangle
392 break;
393 case Perturbed_P2:
394 CalculatePerturbationOperator_P(P,varphi_0,TempPsi_0,2); // \nabla_1 | \varphi_l^{(0)} \rangle
395 break;
396 case Perturbed_RxP0:
397 CalculatePerturbationOperator_RxP(P,varphi_0,TempPsi_0,l_normal,0); // r \times \nabla | \varphi_l^{(0)} \rangle
398 break;
399 case Perturbed_RxP1:
400 CalculatePerturbationOperator_RxP(P,varphi_0,TempPsi_0,l_normal,1); // r \times \nabla | \varphi_l^{(0)} \rangle
401 break;
402 case Perturbed_RxP2:
403 CalculatePerturbationOperator_RxP(P,varphi_0,TempPsi_0,l_normal,2); // r \times \nabla | \varphi_l^{(0)} \rangle
404 break;
405 default:
406 fprintf(stderr,"(%i) CalculatePerturbedEnergy called whilst not within perturbation run: CurrentMin = %i !\n",P->Par.me, R->CurrentMin);
407 break;
408 }
409
410 // ============ GRADIENT and EIGENVALUE Evaluation Part 1==============
411 lambda = 0.0;
412 if ((DoGradient) && (grad != NULL)) {
413 g = 0;
414 if (LevS->GArray[0].GSq == 0.0) {
415 lambda += Hc_grad[0].re*source[0].re;
416 //if (grad != P->Grad.GradientArray[ActualGradient]) Error(SomeError,"CalculatePerturbedEnergy: grad corrupted");
417 grad[0].re = -(Hc_grad[0].re + TempPsi_0[0].re);
418 grad[0].im = -(Hc_grad[0].im + TempPsi_0[0].im);
419 g++;
420 }
421 for (;g<LevS->MaxG;g++) {
422 lambda += 2.*(Hc_grad[g].re*source[g].re + Hc_grad[g].im*source[g].im);
423 //if (grad != P->Grad.GradientArray[ActualGradient] || g<0 || g>=LevS->MaxG) Error(SomeError,"CalculatePerturbedEnergy: grad corrupted");
424 grad[g].re = -(Hc_grad[g].re + TempPsi_0[g].re);
425 grad[g].im = -(Hc_grad[g].im + TempPsi_0[g].im);
426 }
427
428 m = -1;
429 for (j=0; j < Psi->MaxPsiOfType+P->Par.Max_me_comm_ST_PsiT; j++) { // go through all wave functions
430 OnePsiB = &Psi->AllPsiStatus[j]; // grab OnePsiB
431 if (OnePsiB->PsiType == state) { // drop all but the ones of current min state
432 m++; // increase m if it is type-specific wave function
433 if (OnePsiB->my_color_comm_ST_Psi == P->Par.my_color_comm_ST_Psi) // local?
434 LOnePsiB = &Psi->LocalPsiStatus[OnePsiB->MyLocalNo];
435 else
436 LOnePsiB = NULL;
437 if (LOnePsiB == NULL) { // if it's not local ... receive it from respective process into TempPsi
438 RecvSource = OnePsiB->my_color_comm_ST_Psi;
439 MPI_Recv( LevS->LPsi->TempPsi, LevS->MaxG*ElementSize, MPI_DOUBLE, RecvSource, PerturbedTag, P->Par.comm_ST_PsiT, &status );
440 LPsiDatB=LevS->LPsi->TempPsi;
441 } else { // .. otherwise send it to all other processes (Max_me... - 1)
442 for (i=0;i<P->Par.Max_me_comm_ST_PsiT;i++)
443 if (i != OnePsiB->my_color_comm_ST_Psi)
444 MPI_Send( LevS->LPsi->LocalPsi[OnePsiB->MyLocalNo], LevS->MaxG*ElementSize, MPI_DOUBLE, i, PerturbedTag, P->Par.comm_ST_PsiT);
445 LPsiDatB=LevS->LPsi->LocalPsi[OnePsiB->MyLocalNo];
446 } // LPsiDatB is now set to the coefficients of OnePsi either stored or MPI_Received
447
448 g = 0;
449 if (LevS->GArray[0].GSq == 0.0) { // perform the summation
450 //if (grad != P->Grad.GradientArray[ActualGradient]) Error(SomeError,"CalculatePerturbedEnergy: grad corrupted");
451 grad[0].re += Lat->Psi.lambda[ActNum][m]*LPsiDatB[0].re;
452 grad[0].im += Lat->Psi.lambda[ActNum][m]*LPsiDatB[0].im;
453 g++;
454 }
455 for (;g<LevS->MaxG;g++) {
456 //if (grad != P->Grad.GradientArray[ActualGradient] || g<0 || g>=LevS->MaxG) Error(SomeError,"CalculatePerturbedEnergy: grad corrupted");
457 grad[g].re += Lat->Psi.lambda[ActNum][m]*LPsiDatB[g].re;
458 grad[g].im += Lat->Psi.lambda[ActNum][m]*LPsiDatB[g].im;
459 }
460 }
461 }
462 } else {
463 lambda = GradSP(P,LevS,Hc_grad,source);
464 }
465 MPI_Allreduce ( &lambda, &Lambda, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi);
466 //fprintf(stderr,"(%i) Lambda[%i] = %lg\n",P->Par.me, l, Lambda);
467 //if (l < 0 || l >= Psi->LocalNo) Error(SomeError,"CalculatePerturbedEnergy: l out of range");
468 Lat->Psi.AddData[l].Lambda = Lambda;
469
470 // ============ ENERGY FUNCTIONAL Evaluation PART 2 ================
471 // varphi_1 jas negative symmetry, returning TempPsi_0 from CalculatePerturbedOperator also, thus real part of scalar product
472 // "-" due to purely imaginary wave function is on left hand side, thus becomes complex conjugated: i -> -i
473 // (-i goes into pert. op., "-" remains when on right hand side)
474 RElambda10 = GradSP(P,LevS,varphi_1,TempPsi_0) * sqrt(Psi->LocalPsiStatus[l].PsiFactor * Psi->LocalPsiStatus[l_normal].PsiFactor);
475 //RElambda01 = -GradSP(P,LevS,varphi_0,TempPsi_1) * sqrt(Psi->LocalPsiStatus[l].PsiFactor * Psi->LocalPsiStatus[l_normal].PsiFactor);
476
477 MPI_Allreduce ( &RElambda10, &RELambda10, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi);
478 //MPI_Allreduce ( &RElambda01, &RELambda01, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi);
479
480 //if (l < 0 || l >= Psi->LocalNo) Error(SomeError,"CalculatePerturbedEnergy: l out of range");
481 E->PsiEnergy[Perturbed1_0Energy][l] = RELambda10;
482 E->PsiEnergy[Perturbed0_1Energy][l] = RELambda10;
483// if (P->Par.me == 0) {
484// fprintf(stderr,"RE.Lambda10[%i-%i] = %lg\t RE.Lambda01[%i-%i] = %lg\n", l, l_normal, RELambda10, l_normal, l, RELambda01);
485// }
486 // GradImSP() is only applicable to a product of wave functions with uneven symmetry!
487 // Otherwise, due to the nature of symmetry, a sum over only half of the coefficients will in most cases not result in zero!
488}
489
490/** Applies \f$H^{(0)}\f$ to a given \a source.
491 * The DensityTypes#HGDensity is computed, the exchange potential added and the
492 * whole multiplied - coefficient by coefficient - with the current wave function, taken from its density coefficients,
493 * on the upper LatticeLevel (RunStruct#Lev0), which (DensityTypes#ActualPsiDensity) is updated beforehand.
494 * After an inverse fft (now G-dependent) the non-local potential is added and
495 * within the reciprocal basis set, the kinetic energy can be evaluated easily.
496 * \param *P Problem at hand
497 * \param *source pointer to source coefficient array, \f$| \varphi(G) \rangle\f$
498 * \param *dest pointer to dest coefficient array,\f$H^{(0)} | \varphi(G) \rangle\f$
499 * \param **fnl pointer to non-local form factor array
500 * \param PsiFactor occupation number of orbital
501 * \param first 1 - Re-calculate DensityTypes#HGDensity, 0 - don't
502 * \sa CalculateConDirHConDir() - same procedure
503 */
504void ApplyTotalHamiltonian(struct Problem *P, const fftw_complex *source, fftw_complex *dest, fftw_complex ***fnl, const double PsiFactor, const int first) {
505 struct Lattice *Lat = &P->Lat;
506 struct RunStruct *R = &P->R;
507 struct LatticeLevel *LevS = R->LevS;
508 struct LatticeLevel *Lev0 = R->Lev0;
509 struct Density *Dens0 = Lev0->Dens;
510 struct fft_plan_3d *plan = Lat->plan;
511 struct PseudoPot *PP = &P->PP;
512 struct Ions *I = &P->Ion;
513 fftw_complex *work = Dens0->DensityCArray[TempDensity];
514 fftw_real *HGcR = Dens0->DensityArray[HGcDensity];
515 fftw_complex *HGcRC = (fftw_complex*)HGcR;
516 fftw_complex *HGC = Dens0->DensityCArray[HGDensity];
517 fftw_real *HGCR = (fftw_real *)HGC;
518 fftw_complex *PsiC = Dens0->DensityCArray[ActualPsiDensity];
519 fftw_real *PsiCR = (fftw_real *)PsiC;
520 //const fftw_complex *dest_bak = dest;
521 int nx,ny,nz,iS,i0;
522 const int Nx = LevS->Plan0.plan->local_nx;
523 const int Ny = LevS->Plan0.plan->N[1];
524 const int Nz = LevS->Plan0.plan->N[2];
525 const int NUpx = LevS->NUp[0];
526 const int NUpy = LevS->NUp[1];
527 const int NUpz = LevS->NUp[2];
528 const double HGcRCFactor = 1./LevS->MaxN;
529 int g, Index, i, it;
530 fftw_complex vp,rp,rhog,TotalPsiDensity;
531 double Fac;
532
533 if (first) {
534 // recalculate HGDensity
535 //if (HGC != Dens0->DensityCArray[HGDensity]) Error(SomeError,"ApplyTotalHamiltonian: HGC corrupted");
536 SetArrayToDouble0((double *)HGC,2*Dens0->TotalSize);
537 g=0;
538 if (Lev0->GArray[0].GSq == 0.0) {
539 Index = Lev0->GArray[0].Index;
540 c_re(vp) = 0.0;
541 c_im(vp) = 0.0;
542 for (it = 0; it < I->Max_Types; it++) {
543 c_re(vp) += (c_re(I->I[it].SFactor[0])*PP->phi_ps_loc[it][0]);
544 c_im(vp) += (c_im(I->I[it].SFactor[0])*PP->phi_ps_loc[it][0]);
545 }
546 //if (HGC != Dens0->DensityCArray[HGDensity] || Index<0 || Index>=Dens0->LocalSizeC) Error(SomeError,"ApplyTotalHamiltonian: HGC corrupted");
547 c_re(HGC[Index]) = c_re(vp);
548 c_re(TotalPsiDensity) = c_re(Dens0->DensityCArray[TotalDensity][Index]);
549 c_im(TotalPsiDensity) = c_im(Dens0->DensityCArray[TotalDensity][Index]);
550
551 g++;
552 }
553 for (; g < Lev0->MaxG; g++) {
554 Index = Lev0->GArray[g].Index;
555 Fac = 4.*PI/(Lev0->GArray[g].GSq);
556 c_re(vp) = 0.0;
557 c_im(vp) = 0.0;
558 c_re(rp) = 0.0;
559 c_im(rp) = 0.0;
560 for (it = 0; it < I->Max_Types; it++) {
561 c_re(vp) += (c_re(I->I[it].SFactor[g])*PP->phi_ps_loc[it][g]);
562 c_im(vp) += (c_im(I->I[it].SFactor[g])*PP->phi_ps_loc[it][g]);
563 c_re(rp) += (c_re(I->I[it].SFactor[g])*PP->FacGauss[it][g]);
564 c_im(rp) += (c_im(I->I[it].SFactor[g])*PP->FacGauss[it][g]);
565 } // rp = n^{Gauss)(G)
566
567 // n^{tot} = n^0 + \lambda n^1 + ...
568 //if (isnan(c_re(Dens0->DensityCArray[TotalDensity][Index]))) { fprintf(stderr,"(%i) WARNING in CalculatePerturbedEnergy(): TotalDensity[%i] = NaN!\n", P->Par.me, Index); Error(SomeError, "NaN-Fehler!"); }
569 c_re(TotalPsiDensity) = c_re(Dens0->DensityCArray[TotalDensity][Index]);
570 c_im(TotalPsiDensity) = c_im(Dens0->DensityCArray[TotalDensity][Index]);
571
572 c_re(rhog) = c_re(TotalPsiDensity)*R->HGcFactor+c_re(rp);
573 c_im(rhog) = c_im(TotalPsiDensity)*R->HGcFactor+c_im(rp);
574 // rhog = n(G) + n^{Gauss}(G), rhoe = n(G)
575 //if (HGC != Dens0->DensityCArray[HGDensity] || Index<0 || Index>=Dens0->LocalSizeC) Error(SomeError,"ApplyTotalHamiltonian: HGC corrupted");
576 c_re(HGC[Index]) = c_re(vp)+Fac*c_re(rhog);
577 c_im(HGC[Index]) = c_im(vp)+Fac*c_im(rhog);
578 }
579 //
580 for (i=0; i<Lev0->MaxDoubleG; i++) {
581 //if (HGC != Dens0->DensityCArray[HGDensity] || Lev0->DoubleG[2*i+1]<0 || Lev0->DoubleG[2*i+1]>Dens0->LocalSizeC || Lev0->DoubleG[2*i]<0 || Lev0->DoubleG[2*i]>Dens0->LocalSizeC) Error(SomeError,"CalculatePerturbedEnergy: grad corrupted");
582 HGC[Lev0->DoubleG[2*i+1]].re = HGC[Lev0->DoubleG[2*i]].re;
583 HGC[Lev0->DoubleG[2*i+1]].im = -HGC[Lev0->DoubleG[2*i]].im;
584 }
585 }
586 // ============ GRADIENT and EIGENVALUE Evaluation Part 1==============
587 // \lambda_l^{(1)} = \langle \varphi_l^{(1)} | H^{(0)} | \varphi_l^{(1)} \rangle and gradient calculation
588 SpeedMeasure(P, LocTime, StartTimeDo);
589 // back-transform HGDensity: (G) -> (R)
590 //if (HGC != Dens0->DensityCArray[HGDensity]) Error(SomeError,"ApplyTotalHamiltonian: HGC corrupted");
591 if (first) fft_3d_complex_to_real(plan, Lev0->LevelNo, FFTNF1, HGC, work);
592 // evaluate exchange potential with this density, add up onto HGCR
593 //if (HGCR != (fftw_real *)Dens0->DensityCArray[HGDensity]) Error(SomeError,"ApplyTotalHamiltonian: HGCR corrupted");
594 if (first) CalculateXCPotentialNoRT(P, HGCR); // add V^{xc} on V^H + V^{ps}
595 // make sure that ActualPsiDensity is recent
596 CalculateOneDensityR(Lat, LevS, Dens0, source, Dens0->DensityArray[ActualDensity], R->FactorDensityR*PsiFactor, 1);
597 for (nx=0;nx<Nx;nx++)
598 for (ny=0;ny<Ny;ny++)
599 for (nz=0;nz<Nz;nz++) {
600 i0 = nz*NUpz+Nz*NUpz*(ny*NUpy+Ny*NUpy*nx*NUpx);
601 iS = nz+Nz*(ny+Ny*nx);
602 //if (HGcR != Dens0->DensityArray[HGcDensity] || iS<0 || iS>=LevS->Dens->LocalSizeR) Error(SomeError,"ApplyTotalHamiltonian: HGC corrupted");
603 HGcR[iS] = HGCR[i0]*PsiCR[i0]; /* Matrix Vector Mult */
604 }
605 // (R) -> (G)
606 //if (HGcRC != (fftw_complex *)Dens0->DensityArray[HGcDensity]) Error(SomeError,"ApplyTotalHamiltonian: HGcRC corrupted");
607 fft_3d_real_to_complex(plan, LevS->LevelNo, FFTNF1, HGcRC, work);
608 SpeedMeasure(P, LocTime, StopTimeDo);
609 /* NonLocalPP */
610 SpeedMeasure(P, NonLocTime, StartTimeDo);
611 //if (dest != dest_bak) Error(SomeError,"ApplyTotalHamiltonian: dest corrupted");
612 CalculateAddNLPot(P, dest, fnl, PsiFactor); // wave function hidden in form factors fnl, also resets Hc_grad beforehand
613 SpeedMeasure(P, NonLocTime, StopTimeDo);
614
615 /* create final vector */
616 for (g=0;g<LevS->MaxG;g++) {
617 Index = LevS->GArray[g].Index; /* FIXME - factoren */
618 //if (dest != dest_bak || g<0 || g>=LevS->MaxG) Error(SomeError,"ApplyTotalHamiltonian: dest corrupted");
619 dest[g].re += PsiFactor*(HGcRC[Index].re*HGcRCFactor + 0.5*LevS->GArray[g].GSq*source[g].re);
620 dest[g].im += PsiFactor*(HGcRC[Index].im*HGcRCFactor + 0.5*LevS->GArray[g].GSq*source[g].im);
621 }
622}
623
624#define stay_above 0.001 //!< value above which the coefficient of the wave function will always remain
625
626/** Finds the minimum of perturbed energy in regards of actual wave function.
627 * The following happens step by step:
628 * -# The Gradient is copied into GradientTypes#GraSchGradient (which is nothing but a pointer to
629 * one array in LPsiDat) and orthonormalized via GramSch() to all occupied wave functions
630 * except to the current perturbed one.
631 * -# Then comes pre-conditioning, analogous to CalculatePreConGrad().
632 * -# The Gradient is projected onto the current perturbed wave function and this is subtracted, i.e.
633 * vector is the conjugate gradient.
634 * -# Finally, Calculate1stPerturbedDerivative() and Calculate2ndPerturbedDerivative() are called and
635 * with these results and the current total energy, CalculateDeltaI() finds the parameter for the one-
636 * dimensional minimisation. The current wave function is set to newly found minimum and approximated
637 * total energy is printed.
638 *
639 * \param *P Problem at hand
640 * \sa CalculateNewWave() and functions therein
641 */
642void FindPerturbedMinimum(struct Problem *P)
643{
644 struct Lattice *Lat = &P->Lat;
645 struct RunStruct *R = &P->R;
646 struct Psis *Psi = &Lat->Psi;
647 struct PseudoPot *PP = &P->PP;
648 struct LatticeLevel *LevS = R->LevS;
649 struct LatticeLevel *Lev0 = R->Lev0;
650 struct Density *Dens = Lev0->Dens;
651 struct Energy *En = Lat->E;
652 struct FileData *F = &P->Files;
653 int g,p,i;
654 int step = R->PsiStep;
655 double *GammaDiv = &Lat->Psi.AddData[R->ActualLocalPsiNo].Gamma;
656 const int ElementSize = (sizeof(fftw_complex) / sizeof(double));
657 fftw_complex *source = LevS->LPsi->LocalPsi[R->ActualLocalPsiNo];
658 fftw_complex *grad = P->Grad.GradientArray[ActualGradient];
659 fftw_complex *GradOrtho = P->Grad.GradientArray[GraSchGradient];
660 fftw_complex *PCgrad = P->Grad.GradientArray[PreConGradient];
661 fftw_complex *PCOrtho = P->Grad.GradientArray[GraSchGradient];
662 fftw_complex *ConDir = P->Grad.GradientArray[ConDirGradient];
663 fftw_complex *ConDir_old = P->Grad.GradientArray[OldConDirGradient];
664 fftw_complex *Ortho = P->Grad.GradientArray[GraSchGradient];
665 const fftw_complex *Hc_grad = P->Grad.GradientArray[HcGradient];
666 const fftw_complex *H1c_grad = P->Grad.GradientArray[H1cGradient];
667 fftw_complex *HConDir = Dens->DensityCArray[ActualDensity];
668 const double PsiFactor = Lat->Psi.LocalPsiStatus[R->ActualLocalPsiNo].PsiFactor;
669 //double Lambda = Lat->Psi.AddData[R->ActualLocalPsiNo].Lambda;
670 double T;
671 double x, K; //, dK;
672 double dS[2], S[2], Gamma, GammaDivOld = *GammaDiv;
673 double LocalSP, PsiSP;
674 double dEdt0, ddEddt0, ConDirHConDir, ConDirConDir;//, sourceHsource;
675 double E0, E, delta;
676 //double E0, E, dE, ddE, delta, dcos, dsin;
677 //double EI, dEI, ddEI, deltaI, dcosI, dsinI;
678 //double HartreeddEddt0, XCddEddt0;
679 double d[4],D[4], Diff;
680 const int Num = Psi->NoOfPsis;
681
682 // ORTHOGONALIZED-GRADIENT
683 for (g=0;g<LevS->MaxG;g++) {
684 //if (GradOrtho != P->Grad.GradientArray[GraSchGradient] || g<0 || g>=LevS->MaxG) Error(SomeError,"FindPerturbedMinimum: GradOrtho corrupted");
685 GradOrtho[g].re = grad[g].re; //+Lambda*source[g].re;
686 GradOrtho[g].im = grad[g].im; //+Lambda*source[g].im;
687 }
688 // include the ExtraPsi (which is the GraSchGradient!)
689 SetGramSchExtraPsi(P, Psi, NotOrthogonal);
690 // exclude the minimised Psi
691 SetGramSchActualPsi(P, Psi, NotUsedToOrtho);
692 SpeedMeasure(P, GramSchTime, StartTimeDo);
693 // makes conjugate gradient orthogonal to all other orbits
694 //fprintf(stderr,"CalculateCGGradient: GramSch() for extra orbital\n");
695 GramSch(P, LevS, Psi, Orthogonalize);
696 SpeedMeasure(P, GramSchTime, StopTimeDo);
697 //if (grad != P->Grad.GradientArray[ActualGradient]) Error(SomeError,"FindPerturbedMinimum: grad corrupted");
698 memcpy(grad, GradOrtho, ElementSize*LevS->MaxG*sizeof(double));
699 //memcpy(PCOrtho, GradOrtho, ElementSize*LevS->MaxG*sizeof(double));
700
701 // PRE-CONDITION-GRADIENT
702 //if (fabs(T) < MYEPSILON) T = 1;
703 T = 0.;
704 for (i=0;i<Num;i++)
705 T += Psi->lambda[i][i];
706 for (g=0;g<LevS->MaxG;g++) {
707 x = .5*LevS->GArray[g].GSq;
708 // FIXME: Good way of accessing reciprocal Lev0 Density coefficients on LevS! (not so trivial)
709 //x += sqrt(Dens->DensityCArray[HGDensity][g].re*Dens->DensityCArray[HGDensity][g].re+Dens->DensityCArray[HGDensity][g].im*Dens->DensityCArray[HGDensity][g].im);
710 x -= T/(double)Num;
711 K = x/(x*x+stay_above*stay_above);
712 //if (PCOrtho != P->Grad.GradientArray[GraSchGradient] || g<0 || g>=LevS->MaxG) Error(SomeError,"FindPerturbedMinimum: PCOrtho corrupted");
713 c_re(PCOrtho[g]) = K*c_re(grad[g]);
714 c_im(PCOrtho[g]) = K*c_im(grad[g]);
715 }
716 SetGramSchExtraPsi(P, Psi, NotOrthogonal);
717 SpeedMeasure(P, GramSchTime, StartTimeDo);
718 // preconditioned direction is orthogonalized
719 //fprintf(stderr,"CalculatePreConGrad: GramSch() for extra orbital\n");
720 GramSch(P, LevS, Psi, Orthogonalize);
721 SpeedMeasure(P, GramSchTime, StopTimeDo);
722 //if (PCgrad != P->Grad.GradientArray[PreConGradient]) Error(SomeError,"FindPerturbedMinimum: PCgrad corrupted");
723 memcpy(PCgrad, PCOrtho, ElementSize*LevS->MaxG*sizeof(double));
724
725 //debug(P, "Before ConDir");
726 //fprintf(stderr,"|(%i)|^2 = %lg\t |PCgrad|^2 = %lg\t |PCgrad,(%i)| = %lg\n", R->ActualLocalPsiNo, GradSP(P,LevS,source,source),GradSP(P,LevS,PCgrad,PCgrad), R->ActualLocalPsiNo, GradSP(P,LevS,PCgrad,source));
727 // CONJUGATE-GRADIENT
728 LocalSP = GradSP(P, LevS, PCgrad, grad);
729 MPI_Allreduce ( &LocalSP, &PsiSP, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi);
730 *GammaDiv = dS[0] = PsiSP;
731 dS[1] = GammaDivOld;
732 S[0]=dS[0]; S[1]=dS[1];
733 /*MPI_Allreduce ( dS, S, 2, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_PsiT);*/
734 if (step) { // only in later steps is the scalar product used, but always condir stored in oldcondir and Ortho (working gradient)
735 if (fabs(S[1]) < MYEPSILON) fprintf(stderr,"CalculateConDir: S[1] = %lg\n",S[1]);
736 Gamma = S[0]/S[1];
737 if (fabs(S[1]) < MYEPSILON) {
738 if (fabs(S[0]) < MYEPSILON)
739 Gamma = 1.0;
740 else
741 Gamma = 0.0;
742 }
743 for (g=0; g < LevS->MaxG; g++) {
744 //if (ConDir != P->Grad.GradientArray[ConDirGradient] || g<0 || g>=LevS->MaxG) Error(SomeError,"FindPerturbedMinimum: ConDir corrupted");
745 c_re(ConDir[g]) = c_re(PCgrad[g]) + Gamma*c_re(ConDir_old[g]);
746 c_im(ConDir[g]) = c_im(PCgrad[g]) + Gamma*c_im(ConDir_old[g]);
747 //if (ConDir_old != P->Grad.GradientArray[OldConDirGradient] || g<0 || g>=LevS->MaxG) Error(SomeError,"FindPerturbedMinimum: ConDir_old corrupted");
748 c_re(ConDir_old[g]) = c_re(ConDir[g]);
749 c_im(ConDir_old[g]) = c_im(ConDir[g]);
750 //if (Ortho != P->Grad.GradientArray[GraSchGradient] || g<0 || g>=LevS->MaxG) Error(SomeError,"FindPerturbedMinimum: Ortho corrupted");
751 c_re(Ortho[g]) = c_re(ConDir[g]);
752 c_im(Ortho[g]) = c_im(ConDir[g]);
753 }
754 } else {
755 Gamma = 0.0;
756 for (g=0; g < LevS->MaxG; g++) {
757 //if (ConDir != P->Grad.GradientArray[ConDirGradient] || g<0 || g>=LevS->MaxG) Error(SomeError,"FindPerturbedMinimum: ConDir corrupted");
758 c_re(ConDir[g]) = c_re(PCgrad[g]);
759 c_im(ConDir[g]) = c_im(PCgrad[g]);
760 //if (ConDir_old != P->Grad.GradientArray[OldConDirGradient] || g<0 || g>=LevS->MaxG) Error(SomeError,"FindPerturbedMinimum: ConDir_old corrupted");
761 c_re(ConDir_old[g]) = c_re(ConDir[g]);
762 c_im(ConDir_old[g]) = c_im(ConDir[g]);
763 //if (Ortho != P->Grad.GradientArray[GraSchGradient] || g<0 || g>=LevS->MaxG) Error(SomeError,"FindPerturbedMinimum: Ortho corrupted");
764 c_re(Ortho[g]) = c_re(ConDir[g]);
765 c_im(Ortho[g]) = c_im(ConDir[g]);
766 }
767 }
768 // orthonormalize
769 SetGramSchExtraPsi(P, Psi, NotOrthogonal);
770 SpeedMeasure(P, GramSchTime, StartTimeDo);
771 //fprintf(stderr,"CalculateConDir: GramSch() for extra orbital\n");
772 GramSch(P, LevS, Psi, Orthogonalize);
773 SpeedMeasure(P, GramSchTime, StopTimeDo);
774 //if (ConDir != P->Grad.GradientArray[ConDirGradient]) Error(SomeError,"FindPerturbedMinimum: ConDir corrupted");
775 memcpy(ConDir, Ortho, ElementSize*LevS->MaxG*sizeof(double));
776 //debug(P, "Before LineSearch");
777 //fprintf(stderr,"|(%i)|^2 = %lg\t |ConDir|^2 = %lg\t |ConDir,(%i)| = %lg\n", R->ActualLocalPsiNo, GradSP(P,LevS,source,source),GradSP(P,LevS,ConDir,ConDir), R->ActualLocalPsiNo, GradSP(P,LevS,ConDir,source));
778 SetGramSchActualPsi(P, Psi, IsOrthogonal);
779
780 //fprintf(stderr,"(%i) Testing conjugate gradient for Orthogonality ...\n", P->Par.me);
781 //TestForOrth(P,LevS,ConDir);
782
783 // ONE-DIMENSIONAL LINE-SEARCH
784
785 // ========= dE / dt | 0 ============
786 p = Lat->Psi.TypeStartIndex[Occupied] + (R->ActualLocalPsiNo - Lat->Psi.TypeStartIndex[R->CurrentMin]);
787 //if (Hc_grad != P->Grad.GradientArray[HcGradient]) Error(SomeError,"FindPerturbedMinimum: Hc_grad corrupted");
788 //if (H1c_grad != P->Grad.GradientArray[H1cGradient]) Error(SomeError,"FindPerturbedMinimum: H1c_grad corrupted");
789 d[0] = Calculate1stPerturbedDerivative(P, LevS->LPsi->LocalPsi[p], source, ConDir, Hc_grad, H1c_grad);
790 //CalculateConDirHConDir(P, ConDir, PsiFactor, &d[1], &d[2], &d[3]);
791 //if (ConDir != P->Grad.GradientArray[ConDirGradient]) Error(SomeError,"FindPerturbedMinimum: ConDir corrupted");
792 CalculateCDfnl(P, ConDir, PP->CDfnl); // calculate needed non-local form factors
793 //if (HConDir != Dens->DensityCArray[ActualDensity]) Error(SomeError,"FindPerturbedMinimum: HConDir corrupted");
794 SetArrayToDouble0((double *)HConDir,Dens->TotalSize*2);
795 //if (ConDir != P->Grad.GradientArray[ConDirGradient]) Error(SomeError,"FindPerturbedMinimum: ConDir corrupted");
796 ApplyTotalHamiltonian(P,ConDir,HConDir, PP->CDfnl, PsiFactor, 0); // applies H^(0) with total perturbed density!
797 d[1] = GradSP(P,LevS,ConDir,HConDir);
798 d[2] = GradSP(P,LevS,ConDir,ConDir);
799 d[3] = 0.;
800
801 // gather results
802 MPI_Allreduce ( &d, &D, 4, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi);
803 // ========== ddE / ddt | 0 =========
804 dEdt0 = D[0];
805 for (i=MAXOLD-1; i > 0; i--)
806 En->dEdt0[i] = En->dEdt0[i-1];
807 En->dEdt0[0] = dEdt0;
808 ConDirHConDir = D[1];
809 ConDirConDir = D[2];
810 ddEddt0 = 0.0;
811 //if (ConDir != P->Grad.GradientArray[ConDirGradient]) Error(SomeError,"FindPerturbedMinimum: ConDir corrupted");
812 //if (H1c_grad != P->Grad.GradientArray[H1cGradient]) Error(SomeError,"FindPerturbedMinimum: H1c_grad corrupted");
813 ddEddt0 = Calculate2ndPerturbedDerivative(P, LevS->LPsi->LocalPsi[p], source, ConDir, Lat->Psi.AddData[R->ActualLocalPsiNo].Lambda * Psi->LocalPsiStatus[R->ActualLocalPsiNo].PsiFactor, ConDirHConDir, ConDirConDir);
814
815 for (i=MAXOLD-1; i > 0; i--)
816 En->ddEddt0[i] = En->ddEddt0[i-1];
817 En->ddEddt0[0] = ddEddt0;
818 E0 = En->TotalEnergy[0];
819 // delta
820 //if (isnan(E0)) { fprintf(stderr,"(%i) WARNING in CalculateLineSearch(): E0_%i[%i] = NaN!\n", P->Par.me, i, 0); Error(SomeError, "NaN-Fehler!"); }
821 //if (isnan(dEdt0)) { fprintf(stderr,"(%i) WARNING in CalculateLineSearch(): dEdt0_%i[%i] = NaN!\n", P->Par.me, i, 0); Error(SomeError, "NaN-Fehler!"); }
822 //if (isnan(ddEddt0)) { fprintf(stderr,"(%i) WARNING in CalculateLineSearch(): ddEddt0_%i[%i] = NaN!\n", P->Par.me, i, 0); Error(SomeError, "NaN-Fehler!"); }
823
824 ////deltaI = CalculateDeltaI(E0, dEdt0, ddEddt0,
825 //// &EI, &dEI, &ddEI, &dcosI, &dsinI);
826 ////delta = deltaI; E = EI; dE = dEI; ddE = ddEI; dcos = dcosI; dsin = dsinI;
827 if (ddEddt0 > 0) {
828 delta = - dEdt0/ddEddt0;
829 E = E0 + delta * dEdt0 + delta*delta/2. * ddEddt0;
830 } else {
831 delta = 0.;
832 E = E0;
833 fprintf(stderr,"(%i) Taylor approximation leads not to minimum!\n",P->Par.me);
834 }
835
836 // shift energy delta values
837 for (i=MAXOLD-1; i > 0; i--) {
838 En->delta[i] = En->delta[i-1];
839 En->ATE[i] = En->ATE[i-1];
840 }
841 // store new one
842 En->delta[0] = delta;
843 En->ATE[0] = E;
844 if (En->TotalEnergy[1] != 0.)
845 Diff = fabs(En->TotalEnergy[1] - E0)/(En->TotalEnergy[1] - E0)*fabs((E0 - En->ATE[1])/E0);
846 else
847 Diff = 0.;
848 R->Diffcount += pow(Diff,2);
849
850 // reinstate actual density (only needed for UpdateDensityCalculation) ...
851 //CalculateOneDensityR(Lat, LevS, Dens, source, Dens->DensityArray[ActualDensity], R->FactorDensityR*Psi->LocalPsiStatus[R->ActualLocalPsiNo].PsiFactor, 1);
852 // ... before changing actual local Psi
853 for (g = 0; g < LevS->MaxG; g++) { // Here all coefficients are updated for the new found wave function
854 //if (isnan(ConDir[g].re)) { fprintf(stderr,"WARNGING: CalculateLineSearch(): ConDir_%i(%i) = NaN!\n", R->ActualLocalPsiNo, g); Error(SomeError, "NaN-Fehler!"); }
855 //if (source != LevS->LPsi->LocalPsi[R->ActualLocalPsiNo] || g<0 || g>=LevS->MaxG) Error(SomeError,"FindPerturbedMinimum: source corrupted");
856 ////c_re(source[g]) = c_re(source[g])*dcos + c_re(ConDir[g])*dsin;
857 ////c_im(source[g]) = c_im(source[g])*dcos + c_im(ConDir[g])*dsin;
858 c_re(source[g]) = c_re(source[g]) + c_re(ConDir[g])*delta;
859 c_im(source[g]) = c_im(source[g]) + c_im(ConDir[g])*delta;
860 }
861 if (P->Call.out[StepLeaderOut]) {
862 fprintf(stderr, "(%i,%i,%i)S(%i,%i,%i):\tTE: %e\tATE: %e\t Diff: %e\t --- d: %e\tdEdt0: %e\tddEddt0: %e\n",P->Par.my_color_comm_ST,P->Par.me_comm_ST, P->Par.me_comm_ST_PsiT, R->MinStep, R->ActualLocalPsiNo, R->PsiStep, E0, E, Diff,delta, dEdt0, ddEddt0);
863 //fprintf(stderr, "(%i,%i,%i)S(%i,%i,%i):\tp0: %e p1: %e p2: %e \tATE: %e\t Diff: %e\t --- d: %e\tdEdt0: %e\tddEddt0: %e\n",P->Par.my_color_comm_ST,P->Par.me_comm_ST, P->Par.me_comm_ST_PsiT, R->MinStep, R->ActualLocalPsiNo, R->PsiStep, En->parts[0], En->parts[1], En->parts[2], E, Diff,delta, dEdt0, ddEddt0);
864 }
865 if (P->Par.me == 0) {
866 fprintf(F->MinimisationFile, "%i\t%i\t%i\t%e\t%e\t%e\t%e\t%e\n",R->MinStep, R->ActualLocalPsiNo, R->PsiStep, E0, E, delta, dEdt0, ddEddt0);
867 fflush(F->MinimisationFile);
868 }
869}
870
871/** Applies perturbation operator \f$\nabla_{index}\f$ to \a *source.
872 * As wave functions are stored in the reciprocal basis set, the application is straight-forward,
873 * for every G vector, the by \a index specified component is multiplied with the respective
874 * coefficient. Afterwards, 1/i is applied by flipping real and imaginary components (and an additional minus sign on the new imaginary term).
875 * \param *P Problem at hand
876 * \param *source complex coefficients of wave function \f$\varphi(G)\f$
877 * \param *dest returned complex coefficients of wave function \f$\widehat{p}_{index}|\varphi(G)\f$
878 * \param index_g vectorial index of operator to be applied
879 */
880void CalculatePerturbationOperator_P(struct Problem *P, const fftw_complex *source, fftw_complex *dest, const int index_g)
881{
882 struct RunStruct *R = &P->R;
883 struct LatticeLevel *LevS = R->LevS;
884 //const fftw_complex *dest_bak = dest;
885 int g = 0;
886 if (LevS->GArray[0].GSq == 0.0) {
887 //if (dest != dest_bak) Error(SomeError,"CalculatePerturbationOperator_P: dest corrupted");
888 dest[0].re = LevS->GArray[0].G[index_g]*source[0].im;
889 dest[0].im = -LevS->GArray[0].G[index_g]*source[0].re;
890 g++;
891 }
892 for (;g<LevS->MaxG;g++) {
893 //if (dest != dest_bak || g<0 || g>=LevS->MaxG) Error(SomeError,"CalculatePerturbationOperator_P: g out of range");
894 dest[g].re = LevS->GArray[g].G[index_g]*source[g].im;
895 dest[g].im = -LevS->GArray[g].G[index_g]*source[g].re;
896 }
897 // don't put dest[0].im = 0! Otherwise real parts of perturbed01/10 are not the same anymore!
898}
899
900/** Applies perturbation operator \f$\widehat{r}_{index}\f$ to \a *source.
901 * The \a *source wave function is blown up onto upper level LatticeLevel RunStruct#Lev0, fourier
902 * transformed. Afterwards, for each point on the real mesh the coefficient is multiplied times the real
903 * vector pointing within the cell to the mesh point, yet on LatticeLevel RunStruct#LevS. The new wave
904 * function is inverse fourier transformed and the resulting reciprocal coefficients stored in *dest.
905 * \param *P Problem at hand
906 * \param *source source coefficients
907 * \param *source2 second source coefficients, e.g. in the evaluation of a scalar product
908 * \param *dest destination coefficienta array, is overwrittten!
909 * \param index_r index of real vector.
910 * \param wavenr index of respective PsiTypeTag#Occupied(!) OnePsiElementAddData for the needed Wanner centre of the wave function.
911 */
912void CalculatePerturbationOperator_R(struct Problem *P, const fftw_complex *source, fftw_complex *dest, const fftw_complex *source2, const int index_r, const int wavenr)
913{
914 struct Lattice *Lat = &P->Lat;
915 struct RunStruct *R = &P->R;
916 struct LatticeLevel *Lev0 = R->Lev0;
917 struct LatticeLevel *LevS = R->LevS;
918 struct Density *Dens0 = Lev0->Dens;
919 struct fft_plan_3d *plan = Lat->plan;
920 fftw_complex *TempPsi = Dens0->DensityCArray[Temp2Density];
921 fftw_real *TempPsiR = (fftw_real *) TempPsi;
922 fftw_complex *workC = Dens0->DensityCArray[TempDensity];
923 fftw_complex *PsiC = Dens0->DensityCArray[ActualPsiDensity];
924 fftw_real *PsiCR = (fftw_real *) PsiC;
925 fftw_complex *tempdestRC = (fftw_complex *)Dens0->DensityArray[TempDensity];
926 fftw_complex *posfac, *destsnd, *destrcv;
927 double x[NDIM], fac[NDIM], Wcentre[NDIM];
928 const int k_normal = Lat->Psi.TypeStartIndex[Occupied] + (wavenr - Lat->Psi.TypeStartIndex[R->CurrentMin]);
929 int n[NDIM], n0, g, Index, pos, iS, i0;
930 int N[NDIM], NUp[NDIM];
931 const int N0 = LevS->Plan0.plan->local_nx;
932 N[0] = LevS->Plan0.plan->N[0];
933 N[1] = LevS->Plan0.plan->N[1];
934 N[2] = LevS->Plan0.plan->N[2];
935 NUp[0] = LevS->NUp[0];
936 NUp[1] = LevS->NUp[1];
937 NUp[2] = LevS->NUp[2];
938 Wcentre[0] = Lat->Psi.AddData[k_normal].WannierCentre[0];
939 Wcentre[1] = Lat->Psi.AddData[k_normal].WannierCentre[1];
940 Wcentre[2] = Lat->Psi.AddData[k_normal].WannierCentre[2];
941 // init pointers and values
942 const int myPE = P->Par.me_comm_ST_Psi;
943 const double FFTFactor = 1./LevS->MaxN;
944 double vector;
945 //double result, Result;
946
947 // blow up source coefficients
948 LockDensityArray(Dens0,TempDensity,real); // tempdestRC
949 LockDensityArray(Dens0,Temp2Density,imag); // TempPsi
950 LockDensityArray(Dens0,ActualPsiDensity,imag); // PsiC
951 //if (tempdestRC != (fftw_complex *)Dens0->DensityArray[TempDensity]) Error(SomeError,"CalculatePerturbationOperator_R: tempdestRC corrupted");
952 SetArrayToDouble0((double *)tempdestRC ,Dens0->TotalSize*2);
953 //if (TempPsi != Dens0->DensityCArray[Temp2Density]) Error(SomeError,"CalculatePerturbationOperator_R: TempPsi corrupted");
954 SetArrayToDouble0((double *)TempPsi ,Dens0->TotalSize*2);
955 //if (PsiC != Dens0->DensityCArray[ActualPsiDensity]) Error(SomeError,"CalculatePerturbationOperator_R: PsiC corrupted");
956 SetArrayToDouble0((double *)PsiC,Dens0->TotalSize*2);
957 for (g=0; g<LevS->MaxG; g++) {
958 Index = LevS->GArray[g].Index;
959 posfac = &LevS->PosFactorUp[LevS->MaxNUp*g];
960 destrcv = &tempdestRC[LevS->MaxNUp*Index];
961 for (pos=0; pos < LevS->MaxNUp; pos++) {
962 //if (destrcv != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->LocalSizeC) Error(SomeError,"CalculatePerturbationOperator_R: destrcv corrupted");
963 destrcv [pos].re = (( source[g].re)*posfac[pos].re-(source[g].im)*posfac[pos].im);
964 destrcv [pos].im = (( source[g].re)*posfac[pos].im+(source[g].im)*posfac[pos].re);
965 }
966 }
967 for (g=0; g<LevS->MaxDoubleG; g++) {
968 destsnd = &tempdestRC [LevS->DoubleG[2*g]*LevS->MaxNUp];
969 destrcv = &tempdestRC [LevS->DoubleG[2*g+1]*LevS->MaxNUp];
970 for (pos=0; pos<LevS->MaxNUp; pos++) {
971 //if (destrcv != &tempdestRC [LevS->DoubleG[2*g+1]*LevS->MaxNUp] || LevS->DoubleG[2*g]*LevS->MaxNUp+pos<0 || LevS->DoubleG[2*g]*LevS->MaxNUp+pos>=Dens0->LocalSizeC|| LevS->DoubleG[2*g+1]*LevS->MaxNUp+pos<0 || LevS->DoubleG[2*g+1]*LevS->MaxNUp+pos>=Dens0->LocalSizeC) Error(SomeError,"CalculatePerturbationOperator_R: destrcv corrupted");
972 destrcv [pos].re = destsnd [pos].re;
973 destrcv [pos].im = -destsnd [pos].im;
974 }
975 }
976 // fourier transform blown up wave function
977 //if (tempdestRC != (fftw_complex *)Dens0->DensityArray[TempDensity]) Error(SomeError,"CalculatePerturbationOperator_R: tempdestRC corrupted");
978 //if (workC != Dens0->DensityCArray[TempDensity]) Error(SomeError,"CalculatePerturbationOperator_R: workC corrupted");
979 fft_3d_complex_to_real(plan,LevS->LevelNo, FFTNFUp, tempdestRC , workC);
980 //if (tempdestRC != (fftw_complex *)Dens0->DensityArray[TempDensity]) Error(SomeError,"CalculatePerturbationOperator_R: tempdestRC corrupted");
981 //if (TempPsiR != (fftw_real *)Dens0->DensityCArray[Temp2Density]) Error(SomeError,"CalculatePerturbationOperator_R: TempPsiR corrupted");
982 DensityRTransformPos(LevS,(fftw_real*)tempdestRC ,TempPsiR );
983 UnLockDensityArray(Dens0,TempDensity,real); // TempdestRC
984
985 //result = 0.;
986 // for every point on the real grid multiply with component of position vector
987 for (n0=0; n0<N0; n0++)
988 for (n[1]=0; n[1]<N[1]; n[1]++)
989 for (n[2]=0; n[2]<N[2]; n[2]++) {
990 n[0] = n0 + N0 * myPE;
991 fac[0] = (double)(n[0])/(double)((N[0]));
992 fac[1] = (double)(n[1])/(double)((N[1]));
993 fac[2] = (double)(n[2])/(double)((N[2]));
994 RMat33Vec3(x,Lat->RealBasis,fac);
995 iS = n[2] + N[2]*(n[1] + N[1]*n0); // mind splitting of x axis due to multiple processes
996 i0 = n[2]*NUp[2]+N[2]*NUp[2]*(n[1]*NUp[1]+N[1]*NUp[1]*n0*NUp[0]);
997 //PsiCR[iS] = ((double)n[0]/(double)N[0]*Lat->RealBasis[0] - fabs(Wcentre[0]))*TempPsiR[i0] - ((double)n[1]/(double)N[1]*Lat->RealBasis[4] - fabs(Wcentre[1]))*TempPsi2R[i0];
998 //fprintf(stderr,"(%i) R[%i] = (%lg,%lg,%lg)\n",P->Par.me, i0, x[0], x[1], x[2]);
999 //else fprintf(stderr,"(%i) WCentre[%i] = %e \n",P->Par.me, index_r, Wcentre[index_r]);
1000 vector = sawtooth(Lat,MinImageConv(Lat,x[index_r],Wcentre[index_r],index_r),index_r);
1001 //vector = 1.;//sin((double)(n[index_r])/(double)((N[index_r]))*2*PI);
1002 PsiCR[iS] = vector * TempPsiR[i0];
1003 //fprintf(stderr,"(%i) vector(%i/%i,%i/%i,%i/%i): %lg\tx[%i] = %e\tWcentre[%i] = %e\tTempPsiR[%i] = %e\tPsiCR[%i] = %e\n",P->Par.me, n[0], N[0], n[1], N[1], n[2], N[2], vector, index_r, x[index_r],index_r, Wcentre[index_r],i0,TempPsiR[i0],iS,PsiCR[iS]);
1004
1005 //truedist(Lat,x[cross(index_r,2)],Wcentre[cross(index_r,2)],cross(index_r,2)) * TempPsiR[i0];
1006 //tmp += truedist(Lat,x[index_r],WCentre[index_r],index_r) * RealPhiR[i0];
1007 //tmp += sawtooth(Lat,truedist(Lat,x[index_r],WCentre[index_r],index_r), index_r)*RealPhiR[i0];
1008 //(Fehler mit falschem Ort ist vor dieser Stelle!): ueber result = RealPhiR[i0] * (x[index_r]) * RealPhiR[i0]; gecheckt
1009 //result += TempPsiR[i0] * PsiCR[iS];
1010 }
1011 UnLockDensityArray(Dens0,Temp2Density,imag); // TempPsi
1012 //MPI_Allreduce( &result, &Result, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi);
1013 //if (P->Par.me == 0) fprintf(stderr,"(%i) PerturbationOpertator_R: %e\n",P->Par.me, Result/LevS->MaxN);
1014 // inverse fourier transform
1015 fft_3d_real_to_complex(plan,LevS->LevelNo, FFTNF1, PsiC, workC);
1016 //fft_3d_real_to_complex(plan,LevS->LevelNo, FFTNF1, Psi2C, workC);
1017
1018 // copy to destination array
1019 for (g=0; g<LevS->MaxG; g++) {
1020 Index = LevS->GArray[g].Index;
1021 dest[g].re = ( PsiC[Index].re)*FFTFactor;
1022 dest[g].im = ( PsiC[Index].im)*FFTFactor;
1023 }
1024 UnLockDensityArray(Dens0,ActualPsiDensity,imag); //PsiC
1025 //if (LevS->GArray[0].GSq == 0)
1026 // dest[0].im = 0; // imaginary of G=0 is zero
1027}
1028/*
1029{
1030 struct RunStruct *R = &P->R;
1031 struct LatticeLevel *Lev0 = R->Lev0;
1032 struct LatticeLevel *LevS = R->LevS;
1033 struct Lattice *Lat = &P->Lat;
1034 struct fft_plan_3d *plan = Lat->plan;
1035 struct Density *Dens0 = Lev0->Dens;
1036 fftw_complex *tempdestRC = Dens0->DensityCArray[TempDensity];
1037 fftw_real *tempdestR = (fftw_real *) tempdestRC;
1038 fftw_complex *work = Dens0->DensityCArray[Temp2Density];
1039 fftw_complex *PsiC = (fftw_complex *) Dens0->DensityCArray[ActualPsiDensity];;
1040 fftw_real *PsiCR = (fftw_real *) PsiC;
1041 fftw_real *RealPhiR = (fftw_real *) Dens0->DensityArray[Temp2Density];
1042 fftw_complex *posfac, *destsnd, *destrcv;
1043 double x[NDIM], fac[NDIM], WCentre[NDIM];
1044 int n[NDIM], N0, n0, g, Index, pos, iS, i0;
1045
1046 // init pointers and values
1047 int myPE = P->Par.me_comm_ST_Psi;
1048 double FFTFactor = 1./LevS->MaxN;
1049 int N[NDIM], NUp[NDIM];
1050 N[0] = LevS->Plan0.plan->N[0];
1051 N[1] = LevS->Plan0.plan->N[1];
1052 N[2] = LevS->Plan0.plan->N[2];
1053 NUp[0] = LevS->NUp[0];
1054 NUp[1] = LevS->NUp[1];
1055 NUp[2] = LevS->NUp[2];
1056 N0 = LevS->Plan0.plan->local_nx;
1057 wavenr = Lat->Psi.TypeStartIndex[Occupied] + (wavenr - Lat->Psi.TypeStartIndex[R->CurrentMin]);
1058 Wcentre[0] = Lat->Psi.AddData[wavenr].WannierCentre[0];
1059 Wcentre[1] = Lat->Psi.AddData[wavenr].WannierCentre[1];
1060 Wcentre[2] = Lat->Psi.AddData[wavenr].WannierCentre[2];
1061
1062 // blow up source coefficients
1063 SetArrayToDouble0((double *)tempdestRC,Dens0->TotalSize*2);
1064 SetArrayToDouble0((double *)RealPhiR,Dens0->TotalSize*2);
1065 SetArrayToDouble0((double *)PsiC,Dens0->TotalSize*2);
1066 for (g=0; g<LevS->MaxG; g++) {
1067 Index = LevS->GArray[g].Index;
1068 posfac = &LevS->PosFactorUp[LevS->MaxNUp*g];
1069 destrcv = &tempdestRC[LevS->MaxNUp*Index];
1070 for (pos=0; pos<LevS->MaxNUp; pos++) {
1071 destrcv[pos].re = (( source[g].re)*posfac[pos].re-( source[g].im)*posfac[pos].im);
1072 destrcv[pos].im = (( source[g].re)*posfac[pos].im+( source[g].im)*posfac[pos].re);
1073 }
1074 }
1075 for (g=0; g<LevS->MaxDoubleG; g++) {
1076 destsnd = &tempdestRC[LevS->DoubleG[2*g]*LevS->MaxNUp];
1077 destrcv = &tempdestRC[LevS->DoubleG[2*g+1]*LevS->MaxNUp];
1078 for (pos=0; pos<LevS->MaxNUp; pos++) {
1079 destrcv[pos].re = destsnd[pos].re;
1080 destrcv[pos].im = -destsnd[pos].im;
1081 }
1082 }
1083
1084 // fourier transform blown up wave function
1085 fft_3d_complex_to_real(plan,LevS->LevelNo, FFTNFUp, tempdestRC, work);
1086 DensityRTransformPos(LevS,tempdestR,RealPhiR);
1087
1088 //fft_Psi(P,source,RealPhiR,0,0);
1089
1090 // for every point on the real grid multiply with component of position vector
1091 for (n0=0; n0<N0; n0++)
1092 for (n[1]=0; n[1]<N[1]; n[1]++)
1093 for (n[2]=0; n[2]<N[2]; n[2]++) {
1094 n[0] = n0 + N0 * myPE;
1095 fac[0] = (double)(n[0])/(double)((N[0]));
1096 fac[1] = (double)(n[1])/(double)((N[1]));
1097 fac[2] = (double)(n[2])/(double)((N[2]));
1098 RMat33Vec3(x,Lat->RealBasis,fac);
1099 iS = n[2] + N[2]*(n[1] + N[1]*n0); // mind splitting of x axis due to multiple processes
1100 i0 = n[2]*NUp[2]+N[2]*NUp[2]*(n[1]*NUp[1]+N[1]*NUp[1]*n0*NUp[0]);
1101 //PsiCR[iS] = (x[index_r]) * RealPhiR[i0]; //- WCentre[index_r]
1102 PsiCR[iS] = truedist(Lat,x[index_r],WCentre[index_r],index_r) * RealPhiR[i0];
1103 //PsiCR[iS] = truedist(Lat,x[index_r],0.,index_r) * RealPhiR[i0];
1104 //PsiCR[iS] = sawtooth(Lat,truedist(Lat,x[index_r],WCentre[index_r],index_r), index_r)*RealPhiR[i0];
1105 //(Fehler mit falschem Ort ist vor dieser Stelle!): ueber result = RealPhiR[i0] * (x[index_r]) * RealPhiR[i0]; gecheckt
1106 }
1107
1108 // inverse fourier transform
1109 fft_3d_real_to_complex(plan,LevS->LevelNo, FFTNF1, PsiC, work);
1110
1111 // copy to destination array
1112 for (g=0; g<LevS->MaxG; g++) {
1113 Index = LevS->GArray[g].Index;
1114 dest[g].re = ( PsiC[Index].re)*FFTFactor;
1115 dest[g].im = ( PsiC[Index].im)*FFTFactor;
1116 if (LevS->GArray[g].GSq == 0)
1117 dest[g].im = 0; // imaginary of G=0 is zero
1118 }
1119}*/
1120
1121/** Prints the positions of all unperturbed orbitals to screen.
1122 * \param *P Problem at hand
1123 * \param type PsiTypeTag specifying group of orbitals
1124 * \sa CalculatePerturbationOperator_R()
1125 */
1126void OutputOrbitalPositions(struct Problem *P, const enum PsiTypeTag type)
1127{
1128 struct Lattice *Lat = &P->Lat;
1129 struct Psis *Psi = &Lat->Psi;
1130 struct RunStruct *R = &P->R;
1131 struct LatticeLevel *LevS = R->LevS;
1132 fftw_complex *temp = LevS->LPsi->TempPsi;
1133 fftw_complex *source;
1134 int wavenr, index;
1135 double result[NDIM], Result[NDIM];
1136 //double imsult[NDIM], Imsult[NDIM];
1137 double norm[NDIM], Norm[NDIM];
1138 //double imnorm[NDIM], imNorm[NDIM];
1139 double Wcentre[NDIM];
1140
1141 // for every unperturbed wave function
1142 for (wavenr=Psi->TypeStartIndex[type]; wavenr<Psi->TypeStartIndex[type+1]; wavenr++) {
1143 source = LevS->LPsi->LocalPsi[wavenr];
1144 Wcentre[0] = Psi->AddData[wavenr].WannierCentre[0];
1145 Wcentre[1] = Psi->AddData[wavenr].WannierCentre[1];
1146 Wcentre[2] = Psi->AddData[wavenr].WannierCentre[2];
1147 for (index=0; index<NDIM; index++) {
1148 SetArrayToDouble0((double *)temp,2*R->InitLevS->MaxG);
1149 // apply position operator
1150 CalculatePerturbationOperator_R(P,source,temp,source,index, wavenr + Psi->TypeStartIndex[R->CurrentMin]);
1151 // take scalar product
1152 result[index] = GradSP(P,LevS,source,temp);
1153 //imsult[index] = GradImSP(P,LevS,source,temp);
1154 norm[index] = GradSP(P,LevS,source,source);
1155 //imnorm[index] = GradImSP(P,LevS,source,source);
1156 MPI_Allreduce( result, Result, NDIM, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi);
1157 //MPI_Allreduce( imsult, Imsult, NDIM, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi);
1158 MPI_Allreduce( norm, Norm, NDIM, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi);
1159 //MPI_Allreduce( imnorm, imNorm, NDIM, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi);
1160 }
1161 // print output to stderr
1162 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Position of Orbital %i: (%e,%e,%e)\n",P->Par.me, wavenr, Result[0]/Norm[0]+Wcentre[0], Result[1]/Norm[1]+Wcentre[1], Result[2]/Norm[2]+Wcentre[2]);
1163 //fprintf(stderr,"(%i) Position of Orbital %i wrt Wannier: (%e,%e,%e)\n",P->Par.me, wavenr, Result[0]/Norm[0], Result[1]/Norm[1], Result[2]/Norm[2]);
1164 //fprintf(stderr,"(%i) with Norm: (%e,%e,%e) + i (%e,%e,%e)\n",P->Par.me, Norm[0], Norm[1], Norm[2], imNorm[0], imNorm[1], imNorm[2]);
1165 //if (P->Par.me == 0) fprintf(stderr,"(%i) Position of Orbital %i: (%e,%e,%e)\n",P->Par.me, wavenr, Result[0]/Norm[0], Result[1]/Norm[1], Result[2]/Norm[2]);
1166 }
1167}
1168
1169#define borderstart 0.9
1170
1171/** Applies perturbation operator \f$(\widehat{r} \times \nabla)_{index}\f$ to \a *source.
1172 * The source is fourier-transformed by transforming it to a density (on the next higher level RunStruct#Lev0)
1173 * and at the same time multiply it with the respective component of the reciprocal G vector - the momentum. This
1174 * is done by callinf fft_Psi(). Thus we get \f$\nabla_k | \varphi (R) \rangle\f$.
1175 *
1176 * Next, we apply the two of three components of the position operator r, which ones stated by cross(), while going
1177 * in a loop through every point of the grid. In order to do this sensibly, truedist() is used to map the coordinates
1178 * onto -L/2...L/2, by subtracting the OneElementPsiAddData#WannierCentre R and wrapping. Also, due to the breaking up
1179 * of the x axis into equally sized chunks for each coefficient sharing process, we need to step only over local
1180 * x-axis grid points, however shift them to the global position when being used as position. In the end, we get
1181 * \f$\epsilon_{index,j,k} (\widehat{r}-R)_j \nabla_k | \varphi (R) \rangle\f$.
1182 *
1183 * One last fft brings the wave function back to reciprocal basis and it is copied to \a *dest.
1184 * \param *P Problem at hand
1185 * \param *source complex coefficients of wave function \f$\varphi(G)\f$
1186 * \param *dest returned complex coefficients of wave function \f$(\widehat{r} \times \widehat{p})_{index}|\varphi(G)\rangle\f$
1187 * \param phi0nr number within LocalPsi of the unperturbed pendant of the given perturbed wavefunction \a *source.
1188 * \param index_rxp index desired of the vector product
1189 * \sa CalculateConDirHConDir() - the procedure of fft and inverse fft is very similar.
1190 */
1191void CalculatePerturbationOperator_RxP(struct Problem *P, const fftw_complex *source, fftw_complex *dest, const int phi0nr, const int index_rxp)
1192
1193{
1194 struct Lattice *Lat = &P->Lat;
1195 struct RunStruct *R = &P->R;
1196 struct LatticeLevel *Lev0 = R->Lev0;
1197 struct LatticeLevel *LevS = R->LevS;
1198 struct Density *Dens0 = Lev0->Dens;
1199 struct fft_plan_3d *plan = Lat->plan;
1200 fftw_complex *TempPsi = Dens0->DensityCArray[Temp2Density];
1201 fftw_real *TempPsiR = (fftw_real *) TempPsi;
1202 fftw_complex *TempPsi2 = (fftw_complex *)Dens0->DensityArray[Temp2Density];
1203 fftw_real *TempPsi2R = (fftw_real *) TempPsi2;
1204 fftw_complex *workC = Dens0->DensityCArray[TempDensity];
1205 fftw_complex *PsiC = Dens0->DensityCArray[ActualPsiDensity];
1206 fftw_real *PsiCR = (fftw_real *) PsiC;
1207 double x[NDIM], fac[NDIM], Wcentre[NDIM];
1208 int n[NDIM], n0, g, Index, iS, i0; //pos,
1209 int N[NDIM], NUp[NDIM];
1210 const int N0 = LevS->Plan0.plan->local_nx;
1211 N[0] = LevS->Plan0.plan->N[0];
1212 N[1] = LevS->Plan0.plan->N[1];
1213 N[2] = LevS->Plan0.plan->N[2];
1214 NUp[0] = LevS->NUp[0];
1215 NUp[1] = LevS->NUp[1];
1216 NUp[2] = LevS->NUp[2];
1217 Wcentre[0] = Lat->Psi.AddData[phi0nr].WannierCentre[0];
1218 Wcentre[1] = Lat->Psi.AddData[phi0nr].WannierCentre[1];
1219 Wcentre[2] = Lat->Psi.AddData[phi0nr].WannierCentre[2];
1220 // init pointers and values
1221 const int myPE = P->Par.me_comm_ST_Psi;
1222 const double FFTFactor = 1./LevS->MaxN; //
1223// double max[NDIM], max_psi[NDIM];
1224// double max_n[NDIM];
1225 int index[4];
1226// double smooth, wall[NDIM];
1227// for (g=0;g<NDIM;g++) {
1228// max[g] = 0.;
1229// max_psi[g] = 0.;
1230// max_n[g] = -1.;
1231// }
1232
1233 //fprintf(stderr,"(%i) Wannier[%i] (%2.13e, %2.13e, %2.13e)\n", P->Par.me, phi0nr, 10.-Wcentre[0], 10.-Wcentre[1], 10.-Wcentre[2]);
1234 for (g=0;g<4;g++)
1235 index[g] = cross(index_rxp,g);
1236
1237 // blow up source coefficients
1238 LockDensityArray(Dens0,Temp2Density,imag); // TempPsi
1239 LockDensityArray(Dens0,Temp2Density,real); // TempPsi2
1240 LockDensityArray(Dens0,ActualPsiDensity,imag); // PsiC
1241
1242 fft_Psi(P,source,TempPsiR ,index[1],7);
1243 fft_Psi(P,source,TempPsi2R,index[3],7);
1244
1245 //result = 0.;
1246 // for every point on the real grid multiply with component of position vector
1247 for (n0=0; n0<N0; n0++)
1248 for (n[1]=0; n[1]<N[1]; n[1]++)
1249 for (n[2]=0; n[2]<N[2]; n[2]++) {
1250 n[0] = n0 + N0 * myPE;
1251 fac[0] = (double)(n[0])/(double)((N[0]));
1252 fac[1] = (double)(n[1])/(double)((N[1]));
1253 fac[2] = (double)(n[2])/(double)((N[2]));
1254 RMat33Vec3(x,Lat->RealBasis,fac);
1255// fac[0] = (fac[0] > .9) ? fac[0]-0.9 : 0.;
1256// fac[1] = (fac[1] > .9) ? fac[1]-0.9 : 0.;
1257// fac[2] = (fac[2] > .9) ? fac[2]-0.9 : 0.;
1258// RMat33Vec3(wall,Lat->RealBasis,fac);
1259// smooth = exp(wall[0]*wall[0]+wall[1]*wall[1]+wall[2]*wall[2]); // smoothing near the borders of the virtual cell
1260 iS = n[2] + N[2]*(n[1] + N[1]*n0); // mind splitting of x axis due to multiple processes
1261 i0 = n[2]*NUp[2]+N[2]*NUp[2]*(n[1]*NUp[1]+N[1]*NUp[1]*n0*NUp[0]);
1262
1263// if (fabs(truedist(Lat,x[index[1]],Wcentre[index[1]],index[1])) >= borderstart * sqrt(Lat->RealBasisSQ[index[1]])/2.)
1264// if (max[index[1]] < sawtooth(Lat,truedist(Lat,x[index[1]],Wcentre[index[1]],index[1]),index[1]) * TempPsiR [i0]) {
1265// max[index[1]] = sawtooth(Lat,truedist(Lat,x[index[1]],Wcentre[index[1]],index[1]),index[1]) * TempPsiR [i0];
1266// max_psi[index[1]] = TempPsiR [i0];
1267// max_n[index[1]] = truedist(Lat,x[index[1]],Wcentre[index[1]],index[1]);
1268// }
1269//
1270// if (fabs(truedist(Lat,x[index[3]],Wcentre[index[3]],index[3])) >= borderstart * sqrt(Lat->RealBasisSQ[index[3]])/2.)
1271// if (max[index[3]] < sawtooth(Lat,truedist(Lat,x[index[3]],Wcentre[index[3]],index[3]),index[3]) * TempPsiR [i0]) {
1272// max[index[3]] = sawtooth(Lat,truedist(Lat,x[index[3]],Wcentre[index[3]],index[3]),index[3]) * TempPsiR [i0];
1273// max_psi[index[3]] = TempPsiR [i0];
1274// max_n[index[3]] = truedist(Lat,x[index[3]],Wcentre[index[3]],index[3]);
1275// }
1276
1277 PsiCR[iS] = //vector * TempPsiR[i0];
1278 sawtooth(Lat,MinImageConv(Lat,x[index[0]],Wcentre[index[0]],index[0]),index[0]) * TempPsiR [i0]
1279 -sawtooth(Lat,MinImageConv(Lat,x[index[2]],Wcentre[index[2]],index[2]),index[2]) * TempPsi2R[i0];
1280// ShiftGaugeOrigin(P,truedist(Lat,x[index[0]],Wcentre[index[0]],index[0]),index[0]) * TempPsiR [i0]
1281// -ShiftGaugeOrigin(P,truedist(Lat,x[index[2]],Wcentre[index[2]],index[2]),index[2]) * TempPsi2R[i0];
1282// PsiCR[iS] = (x[index[0]] - Wcentre[index[0]]) * TempPsiR [i0] - (x[index[2]] - Wcentre[index[2]]) * TempPsi2R[i0];
1283 }
1284 //if (P->Par.me == 0) fprintf(stderr,"(%i) PerturbationOpertator_R(xP): %e\n",P->Par.me, Result/LevS->MaxN);
1285 UnLockDensityArray(Dens0,Temp2Density,imag); // TempPsi
1286 UnLockDensityArray(Dens0,Temp2Density,real); // TempPsi2
1287
1288// // print maximum values
1289// fprintf (stderr,"(%i) RxP: Maximum values = (",P->Par.me);
1290// for (g=0;g<NDIM;g++)
1291// fprintf(stderr,"%lg\t", max[g]);
1292// fprintf(stderr,"\b)\t(");
1293// for (g=0;g<NDIM;g++)
1294// fprintf(stderr,"%lg\t", max_psi[g]);
1295// fprintf(stderr,"\b)\t");
1296// fprintf (stderr,"at (");
1297// for (g=0;g<NDIM;g++)
1298// fprintf(stderr,"%lg\t", max_n[g]);
1299// fprintf(stderr,"\b)\n");
1300
1301 // inverse fourier transform
1302 //if (PsiC != Dens0->DensityCArray[ActualPsiDensity]) Error(SomeError,"CalculatePerturbationOperator_RxP: PsiC corrupted");
1303 fft_3d_real_to_complex(plan,LevS->LevelNo, FFTNF1, PsiC, workC);
1304
1305 // copy to destination array
1306 SetArrayToDouble0((double *)dest, 2*R->InitLevS->MaxG);
1307 for (g=0; g<LevS->MaxG; g++) {
1308 Index = LevS->GArray[g].Index;
1309 dest[g].re += ( PsiC[Index].re)*FFTFactor; // factor confirmed, see grad.c:CalculateConDirHConDir()
1310 dest[g].im += ( PsiC[Index].im)*FFTFactor;
1311 //fprintf(stderr,"(%i) PsiC[(%lg,%lg,%lg)] = %lg +i %lg\n", P->Par.me, LevS->GArray[g].G[0], LevS->GArray[g].G[1], LevS->GArray[g].G[2], dest[g].re, dest[g].im);
1312 }
1313 UnLockDensityArray(Dens0,ActualPsiDensity,imag); // PsiC
1314 //if (LevS->GArray[0].GSq == 0.)
1315 //dest[0].im = 0.; // don't do this, see ..._P()
1316}
1317
1318/** Applies perturbation operator \f$-(\nabla \times \widehat{r})_{index}\f$ to \a *source.
1319 * Is analogous to CalculatePerturbationOperator_RxP(), only the order is reversed, first position operator, then
1320 * momentum operator
1321 * \param *P Problem at hand
1322 * \param *source complex coefficients of wave function \f$\varphi(G)\f$
1323 * \param *dest returned complex coefficients of wave function \f$(\widehat{r} \times \widehat{p})_{index}|\varphi(G)\rangle\f$
1324 * \param phi0nr number within LocalPsi of the unperturbed pendant of the given perturbed wavefunction \a *source.
1325 * \param index_pxr index of position operator
1326 * \note Only third component is important due to initial rotiation of cell such that B field is aligned with z axis.
1327 * \sa CalculateConDirHConDir() - the procedure of fft and inverse fft is very similar.
1328 * \bug routine is not tested (but should work), as it offers no advantage over CalculatePerturbationOperator_RxP()
1329 */
1330void CalculatePerturbationOperator_PxR(struct Problem *P, const fftw_complex *source, fftw_complex *dest, const int phi0nr, const int index_pxr)
1331
1332{
1333 struct Lattice *Lat = &P->Lat;
1334 struct RunStruct *R = &P->R;
1335 struct LatticeLevel *Lev0 = R->Lev0;
1336 struct LatticeLevel *LevS = R->LevS;
1337 struct Density *Dens0 = Lev0->Dens;
1338 struct fft_plan_3d *plan = Lat->plan;
1339 fftw_complex *TempPsi = Dens0->DensityCArray[Temp2Density];
1340 fftw_real *TempPsiR = (fftw_real *) TempPsi;
1341 fftw_complex *workC = Dens0->DensityCArray[TempDensity];
1342 fftw_complex *PsiC = Dens0->DensityCArray[ActualPsiDensity];
1343 fftw_real *PsiCR = (fftw_real *) PsiC;
1344 fftw_complex *Psi2C = Dens0->DensityCArray[ActualDensity];
1345 fftw_real *Psi2CR = (fftw_real *) Psi2C;
1346 fftw_complex *tempdestRC = (fftw_complex *)Dens0->DensityArray[Temp2Density];
1347 fftw_complex *posfac, *destsnd, *destrcv;
1348 double x[NDIM], fac[NDIM], Wcentre[NDIM];
1349 int n[NDIM], n0, g, Index, pos, iS, i0;
1350 int N[NDIM], NUp[NDIM];
1351 const int N0 = LevS->Plan0.plan->local_nx;
1352 N[0] = LevS->Plan0.plan->N[0];
1353 N[1] = LevS->Plan0.plan->N[1];
1354 N[2] = LevS->Plan0.plan->N[2];
1355 NUp[0] = LevS->NUp[0];
1356 NUp[1] = LevS->NUp[1];
1357 NUp[2] = LevS->NUp[2];
1358 Wcentre[0] = Lat->Psi.AddData[phi0nr].WannierCentre[0];
1359 Wcentre[1] = Lat->Psi.AddData[phi0nr].WannierCentre[1];
1360 Wcentre[2] = Lat->Psi.AddData[phi0nr].WannierCentre[2];
1361 // init pointers and values
1362 const int myPE = P->Par.me_comm_ST_Psi;
1363 const double FFTFactor = 1./LevS->MaxN;
1364
1365 // blow up source coefficients
1366 SetArrayToDouble0((double *)tempdestRC ,Dens0->TotalSize*2);
1367 SetArrayToDouble0((double *)TempPsi ,Dens0->TotalSize*2);
1368 SetArrayToDouble0((double *)PsiC,Dens0->TotalSize*2);
1369 SetArrayToDouble0((double *)Psi2C,Dens0->TotalSize*2);
1370 for (g=0; g<LevS->MaxG; g++) {
1371 Index = LevS->GArray[g].Index;
1372 posfac = &LevS->PosFactorUp[LevS->MaxNUp*g];
1373 destrcv = &tempdestRC[LevS->MaxNUp*Index];
1374 for (pos=0; pos < LevS->MaxNUp; pos++) {
1375 destrcv [pos].re = (( source[g].re)*posfac[pos].re-( source[g].im)*posfac[pos].im);
1376 destrcv [pos].im = (( source[g].re)*posfac[pos].im+( source[g].im)*posfac[pos].re);
1377 }
1378 }
1379 for (g=0; g<LevS->MaxDoubleG; g++) {
1380 destsnd = &tempdestRC [LevS->DoubleG[2*g]*LevS->MaxNUp];
1381 destrcv = &tempdestRC [LevS->DoubleG[2*g+1]*LevS->MaxNUp];
1382 for (pos=0; pos<LevS->MaxNUp; pos++) {
1383 destrcv [pos].re = destsnd [pos].re;
1384 destrcv [pos].im = -destsnd [pos].im;
1385 }
1386 }
1387 // fourier transform blown up wave function
1388 fft_3d_complex_to_real(plan,LevS->LevelNo, FFTNFUp, tempdestRC , workC);
1389 DensityRTransformPos(LevS,(fftw_real*)tempdestRC ,TempPsiR );
1390
1391 //fft_Psi(P,source,TempPsiR ,cross(index_pxr,1),7);
1392 //fft_Psi(P,source,TempPsi2R,cross(index_pxr,3),7);
1393
1394 //result = 0.;
1395 // for every point on the real grid multiply with component of position vector
1396 for (n0=0; n0<N0; n0++)
1397 for (n[1]=0; n[1]<N[1]; n[1]++)
1398 for (n[2]=0; n[2]<N[2]; n[2]++) {
1399 n[0] = n0 + N0 * myPE;
1400 fac[0] = (double)(n[0])/(double)((N[0]));
1401 fac[1] = (double)(n[1])/(double)((N[1]));
1402 fac[2] = (double)(n[2])/(double)((N[2]));
1403 RMat33Vec3(x,Lat->RealBasis,fac);
1404 iS = n[2] + N[2]*(n[1] + N[1]*n0); // mind splitting of x axis due to multiple processes
1405 i0 = n[2]*NUp[2]+N[2]*NUp[2]*(n[1]*NUp[1]+N[1]*NUp[1]*n0*NUp[0]);
1406// PsiCR[iS] = sawtooth(Lat,truedist(Lat,x[cross(index_pxr,1)],Wcentre[cross(index_pxr,1)],cross(index_pxr,1)),cross(index_pxr,1)) * TempPsiR[i0];
1407// Psi2CR[iS] = sawtooth(Lat,truedist(Lat,x[cross(index_pxr,3)],Wcentre[cross(index_pxr,3)],cross(index_pxr,3)),cross(index_pxr,3)) * TempPsiR[i0];
1408 PsiCR[iS] = ShiftGaugeOrigin(P,MinImageConv(Lat,x[cross(index_pxr,1)],Wcentre[cross(index_pxr,1)],cross(index_pxr,1)),cross(index_pxr,1)) * TempPsiR[i0];
1409 Psi2CR[iS] = ShiftGaugeOrigin(P,MinImageConv(Lat,x[cross(index_pxr,3)],Wcentre[cross(index_pxr,3)],cross(index_pxr,3)),cross(index_pxr,3)) * TempPsiR[i0];
1410 }
1411
1412 // inverse fourier transform
1413 fft_3d_real_to_complex(plan,LevS->LevelNo, FFTNF1, PsiC, workC);
1414 fft_3d_real_to_complex(plan,LevS->LevelNo, FFTNF1, Psi2C, workC);
1415
1416 // copy to destination array
1417 for (g=0; g<LevS->MaxG; g++) {
1418 Index = LevS->GArray[g].Index;
1419 dest[g].re = -LevS->GArray[g].G[cross(index_pxr,0)]*( PsiC[Index].im)*FFTFactor;
1420 dest[g].im = -LevS->GArray[g].G[cross(index_pxr,0)]*(-PsiC[Index].re)*FFTFactor;
1421 dest[g].re -= -LevS->GArray[g].G[cross(index_pxr,2)]*( Psi2C[Index].im)*FFTFactor;
1422 dest[g].im -= -LevS->GArray[g].G[cross(index_pxr,2)]*(-Psi2C[Index].re)*FFTFactor;
1423 }
1424 if (LevS->GArray[0].GSq == 0.)
1425 dest[0].im = 0.; // don't do this, see ..._P()
1426}
1427
1428/** Evaluates first derivative of perturbed energy functional with respect to minimisation parameter \f$\Theta\f$.
1429 * \f[
1430 * \frac{\delta {\cal E}^{(2)}} {\delta \Theta} =
1431 * 2 {\cal R} \langle \widetilde{\varphi}_i^{(1)} | {\cal H}^{(0)} | \varphi_i^{(1)} \rangle
1432 * - \sum_l \lambda_{il} \langle \widetilde{\varphi}_i^{(1)} | \varphi_l^{(1)} \rangle
1433 * - \sum_k \lambda_{ki} \langle \varphi_k^{(1)} | \widetilde{\varphi}_i^{(1)} \rangle
1434 * + 2 {\cal R} \langle \widetilde{\varphi}_i^{(1)} | {\cal H}^{(1)} | \varphi_i^{(0)} \rangle
1435 * \f]
1436 *
1437 * The summation over all Psis has again to be done with an MPI exchange of non-local coefficients, as the conjugate
1438 * directions are not the same in situations where PePGamma > 1 (Psis split up among processes = multiple minimisation)
1439 * \param *P Problem at hand
1440 * \param source0 unperturbed wave function \f$\varphi_l^{(0)}\f$
1441 * \param source perturbed wave function \f$\varphi_l^{(1)} (G)\f$
1442 * \param ConDir normalized conjugate direction \f$\widetilde{\varphi}_l^{(1)} (G)\f$
1443 * \param Hc_grad complex coefficients of \f$H^{(0)} | \varphi_l^{(1)} (G) \rangle\f$, see GradientArray#HcGradient
1444 * \param H1c_grad complex coefficients of \f$H^{(1)} | \varphi_l^{(0)} (G) \rangle\f$, see GradientArray#H1cGradient
1445 * \sa CalculateLineSearch() - used there, \sa CalculateConDirHConDir() - same principles
1446 * \warning The MPI_Allreduce for the scalar product in the end has not been done and must not have been done for given
1447 * parameters yet!
1448 */
1449double Calculate1stPerturbedDerivative(struct Problem *P, const fftw_complex *source0, const fftw_complex *source, const fftw_complex *ConDir, const fftw_complex *Hc_grad, const fftw_complex *H1c_grad)
1450{
1451 struct RunStruct *R = &P->R;
1452 struct Psis *Psi = &P->Lat.Psi;
1453 struct LatticeLevel *LevS = R->LevS;
1454 double result = 0., E0 = 0., Elambda = 0., E1 = 0.;//, E2 = 0.;
1455 int i,m,j;
1456 const int state = R->CurrentMin;
1457 //const int l_normal = R->ActualLocalPsiNo - Psi->TypeStartIndex[state] + Psi->TypeStartIndex[Occupied];
1458 const int ActNum = R->ActualLocalPsiNo - Psi->TypeStartIndex[state] + Psi->TypeStartIndex[1] * Psi->LocalPsiStatus[R->ActualLocalPsiNo].my_color_comm_ST_Psi;
1459 //int l = R->ActualLocalPsiNo;
1460 //int l_normal = Psi->TypeStartIndex[Occupied] + (l - Psi->TypeStartIndex[state]); // offset l to \varphi_l^{(0)}
1461 struct OnePsiElement *OnePsiB, *LOnePsiB;
1462 //fftw_complex *HConGrad = LevS->LPsi->TempPsi;
1463 fftw_complex *LPsiDatB=NULL;
1464 const int ElementSize = (sizeof(fftw_complex) / sizeof(double));
1465 int RecvSource;
1466 MPI_Status status;
1467
1468 //CalculateCDfnl(P,ConDir,PP->CDfnl);
1469 //ApplyTotalHamiltonian(P,ConDir,HConDir, PP->CDfnl, 1, 0);
1470 //E0 = (GradSP(P, LevS, ConDir, Hc_grad) + GradSP(P, LevS, source, HConDir)) * Psi->LocalPsiStatus[R->ActualLocalPsiNo].PsiFactor;
1471 E0 = 2.*GradSP(P, LevS, ConDir, Hc_grad) * Psi->LocalPsiStatus[R->ActualLocalPsiNo].PsiFactor;
1472 result = E0;
1473 //fprintf(stderr,"(%i) 1st: E0 = \t\t%lg\n", P->Par.me, E0);
1474
1475 m = -1;
1476 for (j=0; j < Psi->MaxPsiOfType+P->Par.Max_me_comm_ST_PsiT; j++) { // go through all wave functions
1477 OnePsiB = &Psi->AllPsiStatus[j]; // grab OnePsiB
1478 if (OnePsiB->PsiType == state) { // drop all but the ones of current min state
1479 m++; // increase m if it is type-specific wave function
1480 if (OnePsiB->my_color_comm_ST_Psi == P->Par.my_color_comm_ST_Psi) // local?
1481 LOnePsiB = &Psi->LocalPsiStatus[OnePsiB->MyLocalNo];
1482 else
1483 LOnePsiB = NULL;
1484 if (LOnePsiB == NULL) { // if it's not local ... receive it from respective process into TempPsi
1485 RecvSource = OnePsiB->my_color_comm_ST_Psi;
1486 MPI_Recv( LevS->LPsi->TempPsi, LevS->MaxG*ElementSize, MPI_DOUBLE, RecvSource, PerturbedTag, P->Par.comm_ST_PsiT, &status );
1487 LPsiDatB=LevS->LPsi->TempPsi;
1488 } else { // .. otherwise send it to all other processes (Max_me... - 1)
1489 for (i=0;i<P->Par.Max_me_comm_ST_PsiT;i++)
1490 if (i != OnePsiB->my_color_comm_ST_Psi)
1491 MPI_Send( LevS->LPsi->LocalPsi[OnePsiB->MyLocalNo], LevS->MaxG*ElementSize, MPI_DOUBLE, i, PerturbedTag, P->Par.comm_ST_PsiT);
1492 LPsiDatB=LevS->LPsi->LocalPsi[OnePsiB->MyLocalNo];
1493 } // LPsiDatB is now set to the coefficients of OnePsi either stored or MPI_Received
1494
1495 Elambda -= 2.*Psi->lambda[ActNum][m]*GradSP(P, LevS, ConDir, LPsiDatB) * OnePsiB->PsiFactor; // lambda is symmetric
1496 }
1497 }
1498 result += Elambda;
1499 //fprintf(stderr,"(%i) 1st: Elambda = \t%lg\n", P->Par.me, Elambda);
1500
1501 E1 = 2.*GradSP(P,LevS,ConDir,H1c_grad) * sqrt(Psi->AllPsiStatus[ActNum].PsiFactor*Psi->LocalPsiStatus[R->ActualLocalPsiNo].PsiFactor);
1502 result += E1;
1503 //fprintf(stderr,"(%i) 1st: E1 = \t\t%lg\n", P->Par.me, E1);
1504
1505 return result;
1506}
1507
1508
1509/** Evaluates second derivative of perturbed energy functional with respect to minimisation parameter \f$\Theta\f$.
1510 * \f[
1511 * \frac{\delta^2 {\cal E}^{(2)}} {\delta \Theta^2} =
1512 * 2 \bigl( \langle \widetilde{\varphi}_l^{(1)} | {\cal H}^{(0)} | \widetilde{\varphi}_l^{(1)} \rangle
1513 * - \langle \varphi_l^{(1)} | {\cal H}^{(0)} | \varphi_l^{(1)} \rangle \bigr )
1514 * + 2 \sum_{i,i \neq l } \lambda_{il} \langle \varphi_i^{(1)} | \varphi_l^{(1)} \rangle
1515 * - 2 {\cal R} \langle \varphi_l^{(1)} | {\cal H}^{(1)} | \varphi_l^{(0)} \rangle
1516 * \f]
1517 *
1518 * The energy eigenvalues of \a ConDir and \a source must be supplied, they can be calculated via CalculateConDirHConDir() and/or
1519 * by the due to CalculatePerturbedEnergy() already present OnePsiElementAddData#Lambda eigenvalue. The summation over the
1520 * unperturbed lambda within the scalar product of perturbed wave functions is evaluated with Psis#lambda and Psis#Overlap.
1521 * Afterwards, the ConDir density is calculated and also the i-th perturbed density to first degree. With these in a sum over
1522 * all real mesh points the exchange-correlation first and second derivatives and also the Hartree potential ones can be calculated
1523 * and summed up.
1524 * \param *P Problem at hand
1525 * \param source0 unperturbed wave function \f$\varphi_l^{(0)}\f$
1526 * \param source wave function \f$\varphi_l^{(1)}\f$
1527 * \param ConDir conjugated direction \f$\widetilde{\varphi}_l^{(1)}\f$
1528 * \param sourceHsource eigenvalue of wave function \f$\langle \varphi_l^{(1)} | H^{(0)} | \varphi_l^{(1)}\rangle\f$
1529 * \param ConDirHConDir perturbed eigenvalue of conjugate direction \f$\langle \widetilde{\varphi}_l^{(1)} | H^{(0)} | \widetilde{\varphi}_l^{(1)}\rangle\f$
1530 * \param ConDirConDir norm of conjugate direction \f$\langle \widetilde{\varphi}_l^{(1)} | \widetilde{\varphi}_l^{(1)}\rangle\f$
1531 * \warning No MPI_AllReduce() takes place, parameters have to be reduced already.
1532 */
1533double Calculate2ndPerturbedDerivative(struct Problem *P, const fftw_complex *source0,const fftw_complex *source, const fftw_complex *ConDir,const double sourceHsource, const double ConDirHConDir, const double ConDirConDir)
1534{
1535 struct RunStruct *R = &P->R;
1536 struct Psis *Psi = &P->Lat.Psi;
1537 //struct Lattice *Lat = &P->Lat;
1538 //struct Energy *E = Lat->E;
1539 double result = 0.;
1540 double Con0 = 0., Elambda = 0.;//, E0 = 0., E1 = 0.;
1541 //int i;
1542 const int state = R->CurrentMin;
1543 //const int l_normal = R->ActualLocalPsiNo - Psi->TypeStartIndex[state] + Psi->TypeStartIndex[Occupied];
1544 const int ActNum = R->ActualLocalPsiNo - Psi->TypeStartIndex[state] + Psi->TypeStartIndex[1] * Psi->LocalPsiStatus[R->ActualLocalPsiNo].my_color_comm_ST_Psi;
1545
1546 Con0 = 2.*ConDirHConDir;
1547 result += Con0;
1548 ////E0 = -2.*sourceHsource;
1549 ////result += E0;
1550 ////E1 = -E->PsiEnergy[Perturbed1_0Energy][R->ActualLocalPsiNo] - E->PsiEnergy[Perturbed0_1Energy][R->ActualLocalPsiNo];
1551 ////result += E1;
1552 //fprintf(stderr,"(%i) 2nd: E1 = \t%lg\n", P->Par.me, E1);
1553
1554 ////for (i=0;i<Lat->Psi.NoOfPsis;i++) {
1555 //// if (i != ActNum) Elambda += Psi->lambda[i][ActNum]*Psi->Overlap[i][ActNum]+ Psi->lambda[ActNum][i]*Psi->Overlap[ActNum][i]; // overlap contains PsiFactor
1556 ////}
1557 ////Elambda = Psi->lambda[ActNum][ActNum]*Psi->Overlap[ActNum][ActNum];
1558 Elambda = 2.*Psi->lambda[ActNum][ActNum]*ConDirConDir;
1559 result -= Elambda;
1560
1561 //fprintf(stderr,"(%i) 2ndPerturbedDerivative: Result = Con0 + E0 + E1 + Elambda + dEdt0_XC + ddEddt0_XC + dEdt0_H + ddEddt0_H = %lg + %lg + %lg + %lg + %lg + %lg + %lg + %lg = %lg\n", P->Par.me, Con0, E0, E1, Elambda, VolumeFactorR*dEdt0_XC, VolumeFactorR*ddEddt0_XC, dEdt0_H, ddEddt0_H, result);
1562
1563 return (result);
1564}
1565
1566/** Returns index of specific component in 3x3 cross product.
1567 * \param i vector product component index, ranging from 0..NDIM
1568 * \param j index specifies which one of the four vectors in x*y - y*x, ranging from 0..3 (0,1 positive sign, 2,3 negative sign)
1569 * \return Component 0..2 of vector to be taken to evaluate a vector product
1570 * \sa crossed() - is the same but vice versa, return value must be specified, \a i is returned.
1571 */
1572inline int cross(int i, int j)
1573{
1574 const int matrix[NDIM*4] = {1,2,2,1,2,0,0,2,0,1,1,0};
1575 if (i>=0 && i<NDIM && j>=0 && j<4)
1576 return (matrix[i*4+j]);
1577 else {
1578 Error(SomeError,"cross: i or j out of range!");
1579 return (0);
1580 }
1581}
1582
1583/** Returns index of resulting vector component in 3x3 cross product.
1584 * In the column specified by the \a j index \a i is looked for and the found row index returned.
1585 * \param i vector component index, ranging from 0..NDIM
1586 * \param j index specifies which one of the four vectors in x*y - y*x, ranging from 0..3 (0,1 positive sign, 2,3 negative sign)
1587 * \return Component 0..2 of resulting vector
1588 * \sa cross() - is the same but vice versa, return value must be specified, \a i is returned.
1589 */
1590inline int crossed(int i, int j)
1591{
1592 const int matrix[NDIM*4] = {1,2,2,1,2,0,0,2,0,1,1,0};
1593 int k;
1594 if (i>=0 && i<NDIM && j>=0 && j<4) {
1595 for (k=0;k<NDIM;k++)
1596 if (matrix[4*k+j] == i) return(k);
1597 Error(SomeError,"crossed: given component not found!");
1598 return(-1);
1599 } else {
1600 Error(SomeError,"crossed: i or j out of range!");
1601 return (-1);
1602 }
1603}
1604
1605#define Nsin 16 //!< should be dependent on MaxG/MaxN per axis!
1606
1607/** Returns sawtooth shaped profile for position operator within cell.
1608 * This is a mapping from -L/2...L/2 (L = length of unit cell derived from Lattice#RealBasisSQ) to -L/2 to L/2 with a smooth transition:
1609 * \f[
1610 * f(x): x \rightarrow \left \{
1611 * \begin{array}{l}
1612 * -\frac{L}{2} \cdot \sin \left ( \frac{x}{0,05\cdot L} \cdot \frac{\pi}{2} \right ), 0<x<0,05\cdot L \\
1613 * (x - 0,05\cdot L) \cdot \frac{10}{9} - \frac{L}{2}, 0,05\cdot L \leq x<0,95\cdot L \\
1614 * \frac{L}{2} \cdot \cos \left ( \frac{x-0,95\cdot L}{0,05\cdot L} \cdot \frac{\pi}{2} \right), 0,95\cdot L<x<L
1615 * \end{array} \right \}
1616 * \f]
1617 * \param *Lat pointer to Lattice structure for Lattice#RealBasisSQ
1618 * \param L parameter x
1619 * \param index component index for Lattice#RealBasisSQ
1620 */
1621inline double sawtooth(struct Lattice *Lat, double L, const int index)
1622{
1623 double axis = sqrt(Lat->RealBasisSQ[index]);
1624 double sawstart = Lat->SawtoothStart;
1625 double sawend = 1. - sawstart;
1626 double sawfactor = (sawstart+sawend)/(sawend-sawstart);
1627 //return(L);
1628
1629 //fprintf(stderr, "sawstart: %e\tsawend: %e\tsawfactor: %e\tL: %e\n", sawstart, sawend, sawfactor, L);
1630 // transform and return (sawtooth profile checked, 04.08.06)
1631 L += axis/2.; // transform to 0 ... L
1632 if (L < (sawstart*axis)) return (-axis/(2*sawfactor)*sin(L/(sawstart*axis)*PI/2.)); // first smooth transition from 0 ... -L/2
1633 if (L > (sawend*axis)) return ( axis/(2*sawfactor)*cos((L-sawend*axis)/(sawstart*axis)*PI/2.)); // second smooth transition from +L/2 ... 0
1634 //fprintf(stderr,"L %e\t sawstart %e\t sawend %e\t sawfactor %e\t axis%e\n", L, sawstart, sawend, sawfactor, axis);
1635 //return ((L - sawstart*axis) - axis/(2*sawfactor)); // area in between scale to -L/2 ... +L/2
1636 return (L - axis/2); // area in between return as it was
1637}
1638
1639/** Shifts the origin of the gauge according to the CSDGT method.
1640 * \f[
1641 * d(r) = r - \sum_{I_s,I_a} (r-R_{I_s,I_a}) exp{(-\alpha_{I_s,I_a}(r-R_{I_s,I_a})^4)}
1642 * \f]
1643 * This trafo is necessary as the current otherweise (CSGT) sensitively depends on the current around
1644 * the core region inadequately/only moderately well approximated by a plane-wave-pseudo-potential-method.
1645 * \param *P Problem at hand, containing Lattice and Ions
1646 * \param r parameter r
1647 * \param index index of the basis vector
1648 * \return \f$d(r)\f$
1649 * \note Continuous Set of Damped Gauge Transformations according to Keith and Bader
1650 */
1651inline double ShiftGaugeOrigin(struct Problem *P, double r, const int index)
1652{
1653 struct Ions *I = &P->Ion;
1654 struct Lattice *Lat = &P->Lat;
1655 double x, tmp;
1656 int is,ia;
1657
1658 // loop over all ions to calculate the sum
1659 x = r;
1660 for (is=0; is < I->Max_Types; is++)
1661 for (ia=0; ia < I->I[is].Max_IonsOfType; ia++) {
1662 tmp = (r - I->I[is].R[NDIM*ia]);
1663 x -= tmp*exp(- I->I[is].alpha[ia] * tpow(tmp,4));
1664 }
1665
1666 return(sawtooth(Lat,x,index)); // still use sawtooth due to the numerical instability around the border region of the cell
1667}
1668
1669/** Print sawtooth() for each node along one axis.
1670 * \param *P Problem at hand, containing RunStruct, Lattice and LatticeLevel RunStruct#LevS
1671 * \param index index of axis
1672 */
1673void TestSawtooth(struct Problem *P, const int index)
1674{
1675 struct RunStruct *R = &P->R;
1676 struct LatticeLevel *LevS = R->LevS;
1677 struct Lattice *Lat =&P->Lat;
1678 double x;
1679 int n;
1680 int N[NDIM];
1681 N[0] = LevS->Plan0.plan->N[0];
1682 N[1] = LevS->Plan0.plan->N[1];
1683 N[2] = LevS->Plan0.plan->N[2];
1684
1685 for (n=0;n<N[index];n++) {
1686 x = (double)n/(double)N[index] * sqrt(Lat->RealBasisSQ[index]);
1687 //fprintf(stderr,"(%i) x %e\t Axis/2 %e\n",P->Par.me, x, sqrt(Lat->RealBasisSQ[index])/2. );
1688 x = MinImageConv(Lat, x, sqrt(Lat->RealBasisSQ[index])/2., index);
1689 fprintf(stderr,"%e\t%e\n", x, sawtooth(Lat,x,index));
1690 }
1691}
1692
1693/** Secures minimum image convention between two given points \a R[] and \a r[] within periodic boundary.
1694 * Each distance component within a periodic boundary must always be between -L/2 ... L/2
1695 * \param *Lat pointer to Lattice structure
1696 * \param R[] first vector, NDIM, each must be between 0...L
1697 * \param r[] second vector, NDIM, each must be between 0...L
1698 * \param index of component
1699 * \return component between -L/2 ... L/2
1700 */
1701inline double MinImageConv(struct Lattice *Lat, const double R, const double r, const int index)
1702{
1703 double axis = sqrt(Lat->RealBasisSQ[index]);
1704 double result = 0.;
1705
1706 if (fabs(result = R - r + axis) < axis/2.) { }
1707 else if (fabs(result = R - r) <= axis/2.) { }
1708 else if (fabs(result = R - r - axis) < axis/2.) { }
1709 else Error(SomeError, "MinImageConv: None of the three cases applied!");
1710 return (result);
1711}
1712
1713
1714/** Fouriertransforms given \a source.
1715 * By the use of the symmetry parameter an additional imaginary unit and/or the momentum operator can
1716 * be applied at the same time.
1717 * \param *P Problem at hand
1718 * \param *Psi source array of reciprocal coefficients
1719 * \param *PsiR destination array, becoming filled with real coefficients
1720 * \param index_g component of G vector (only needed for symmetry=4..7)
1721 * \param symmetry 0 - do nothing, 1 - factor by "-1", 2 - factor by "i", 3 - factor by "1/i = -i", from 4 to 7 the same
1722 * but additionally with momentum operator
1723 */
1724void fft_Psi(struct Problem *P, const fftw_complex *Psi, fftw_real *PsiR, const int index_g, const int symmetry)
1725{
1726 struct Lattice *Lat = &P->Lat;
1727 struct RunStruct *R = &P->R;
1728 struct LatticeLevel *Lev0 = R->Lev0;
1729 struct LatticeLevel *LevS = R->LevS;
1730 struct Density *Dens0 = Lev0->Dens;
1731 struct fft_plan_3d *plan = Lat->plan;
1732 fftw_complex *tempdestRC = (fftw_complex *)Dens0->DensityArray[TempDensity];
1733 fftw_complex *work = Dens0->DensityCArray[TempDensity];
1734 fftw_complex *posfac, *destpos, *destRCS, *destRCD;
1735 int i, Index, pos;
1736
1737 LockDensityArray(Dens0,TempDensity,imag); // tempdestRC
1738 SetArrayToDouble0((double *)tempdestRC, Dens0->TotalSize*2);
1739 SetArrayToDouble0((double *)PsiR, Dens0->TotalSize*2);
1740 switch (symmetry) {
1741 case 0:
1742 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is positive
1743 Index = LevS->GArray[i].Index;
1744 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1745 destpos = &tempdestRC[LevS->MaxNUp*Index];
1746 for (pos=0; pos < LevS->MaxNUp; pos++) {
1747 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1748 destpos[pos].re = (Psi[i].re)*posfac[pos].re-(Psi[i].im)*posfac[pos].im;
1749 destpos[pos].im = (Psi[i].re)*posfac[pos].im+(Psi[i].im)*posfac[pos].re;
1750 }
1751 }
1752 break;
1753 case 1:
1754 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is - positive
1755 Index = LevS->GArray[i].Index;
1756 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1757 destpos = &tempdestRC[LevS->MaxNUp*Index];
1758 for (pos=0; pos < LevS->MaxNUp; pos++) {
1759 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1760 destpos[pos].re = -((Psi[i].re)*posfac[pos].re-(Psi[i].im)*posfac[pos].im);
1761 destpos[pos].im = -((Psi[i].re)*posfac[pos].im+(Psi[i].im)*posfac[pos].re);
1762 }
1763 }
1764 break;
1765 case 2:
1766 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is negative
1767 Index = LevS->GArray[i].Index;
1768 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1769 destpos = &tempdestRC[LevS->MaxNUp*Index];
1770 for (pos=0; pos < LevS->MaxNUp; pos++) {
1771 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1772 destpos[pos].re = (-Psi[i].im)*posfac[pos].re-(Psi[i].re)*posfac[pos].im;
1773 destpos[pos].im = (-Psi[i].im)*posfac[pos].im+(Psi[i].re)*posfac[pos].re;
1774 }
1775 }
1776 break;
1777 case 3:
1778 for (i=0;i<LevS->MaxG;i++) { // incoming is negative, outgoing is positive
1779 Index = LevS->GArray[i].Index;
1780 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1781 destpos = &tempdestRC[LevS->MaxNUp*Index];
1782 for (pos=0; pos < LevS->MaxNUp; pos++) {
1783 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1784 destpos[pos].re = (Psi[i].im)*posfac[pos].re-(-Psi[i].re)*posfac[pos].im;
1785 destpos[pos].im = (Psi[i].im)*posfac[pos].im+(-Psi[i].re)*posfac[pos].re;
1786 }
1787 }
1788 break;
1789 case 4:
1790 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is positive
1791 Index = LevS->GArray[i].Index;
1792 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1793 destpos = &tempdestRC[LevS->MaxNUp*Index];
1794 for (pos=0; pos < LevS->MaxNUp; pos++) {
1795 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1796 destpos[pos].re = LevS->GArray[i].G[index_g]*((Psi[i].re)*posfac[pos].re-(Psi[i].im)*posfac[pos].im);
1797 destpos[pos].im = LevS->GArray[i].G[index_g]*((Psi[i].re)*posfac[pos].im+(Psi[i].im)*posfac[pos].re);
1798 }
1799 }
1800 break;
1801 case 5:
1802 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is - positive
1803 Index = LevS->GArray[i].Index;
1804 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1805 destpos = &tempdestRC[LevS->MaxNUp*Index];
1806 for (pos=0; pos < LevS->MaxNUp; pos++) {
1807 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1808 destpos[pos].re = -LevS->GArray[i].G[index_g]*((Psi[i].re)*posfac[pos].re-(Psi[i].im)*posfac[pos].im);
1809 destpos[pos].im = -LevS->GArray[i].G[index_g]*((Psi[i].re)*posfac[pos].im+(Psi[i].im)*posfac[pos].re);
1810 }
1811 }
1812 break;
1813 case 6:
1814 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is negative
1815 Index = LevS->GArray[i].Index;
1816 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1817 destpos = &tempdestRC[LevS->MaxNUp*Index];
1818 for (pos=0; pos < LevS->MaxNUp; pos++) {
1819 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1820 destpos[pos].re = LevS->GArray[i].G[index_g]*((-Psi[i].im)*posfac[pos].re-(Psi[i].re)*posfac[pos].im);
1821 destpos[pos].im = LevS->GArray[i].G[index_g]*((-Psi[i].im)*posfac[pos].im+(Psi[i].re)*posfac[pos].re);
1822 }
1823 }
1824 break;
1825 case 7:
1826 for (i=0;i<LevS->MaxG;i++) { // incoming is negative, outgoing is positive
1827 Index = LevS->GArray[i].Index;
1828 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1829 destpos = &tempdestRC[LevS->MaxNUp*Index];
1830 for (pos=0; pos < LevS->MaxNUp; pos++) {
1831 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1832 destpos[pos].re = LevS->GArray[i].G[index_g]*((Psi[i].im)*posfac[pos].re-(-Psi[i].re)*posfac[pos].im);
1833 destpos[pos].im = LevS->GArray[i].G[index_g]*((Psi[i].im)*posfac[pos].im+(-Psi[i].re)*posfac[pos].re);
1834 }
1835 }
1836 break;
1837 }
1838 for (i=0; i<LevS->MaxDoubleG; i++) {
1839 destRCS = &tempdestRC[LevS->DoubleG[2*i]*LevS->MaxNUp];
1840 destRCD = &tempdestRC[LevS->DoubleG[2*i+1]*LevS->MaxNUp];
1841 for (pos=0; pos < LevS->MaxNUp; pos++) {
1842 //if (destRCD != &tempdestRC[LevS->DoubleG[2*i+1]*LevS->MaxNUp] || LevS->DoubleG[2*i+1]*LevS->MaxNUp+pos<0 || LevS->DoubleG[2*i+1]*LevS->MaxNUp+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destRCD corrupted");
1843 destRCD[pos].re = destRCS[pos].re;
1844 destRCD[pos].im = -destRCS[pos].im;
1845 }
1846 }
1847 fft_3d_complex_to_real(plan, LevS->LevelNo, FFTNFUp, tempdestRC, work);
1848 DensityRTransformPos(LevS,(fftw_real*)tempdestRC, PsiR);
1849 UnLockDensityArray(Dens0,TempDensity,imag); // tempdestRC
1850}
1851
1852/** Locks all NDIM_NDIM current density arrays
1853 * \param Dens0 Density structure to be locked (in the current parts)
1854 */
1855void AllocCurrentDensity(struct Density *Dens0) {
1856 // real
1857 LockDensityArray(Dens0,CurrentDensity0,real); // CurrentDensity[B_index]
1858 LockDensityArray(Dens0,CurrentDensity1,real); // CurrentDensity[B_index]
1859 LockDensityArray(Dens0,CurrentDensity2,real); // CurrentDensity[B_index]
1860 LockDensityArray(Dens0,CurrentDensity3,real); // CurrentDensity[B_index]
1861 LockDensityArray(Dens0,CurrentDensity4,real); // CurrentDensity[B_index]
1862 LockDensityArray(Dens0,CurrentDensity5,real); // CurrentDensity[B_index]
1863 LockDensityArray(Dens0,CurrentDensity6,real); // CurrentDensity[B_index]
1864 LockDensityArray(Dens0,CurrentDensity7,real); // CurrentDensity[B_index]
1865 LockDensityArray(Dens0,CurrentDensity8,real); // CurrentDensity[B_index]
1866 // imaginary
1867 LockDensityArray(Dens0,CurrentDensity0,imag); // CurrentDensity[B_index]
1868 LockDensityArray(Dens0,CurrentDensity1,imag); // CurrentDensity[B_index]
1869 LockDensityArray(Dens0,CurrentDensity2,imag); // CurrentDensity[B_index]
1870 LockDensityArray(Dens0,CurrentDensity3,imag); // CurrentDensity[B_index]
1871 LockDensityArray(Dens0,CurrentDensity4,imag); // CurrentDensity[B_index]
1872 LockDensityArray(Dens0,CurrentDensity5,imag); // CurrentDensity[B_index]
1873 LockDensityArray(Dens0,CurrentDensity6,imag); // CurrentDensity[B_index]
1874 LockDensityArray(Dens0,CurrentDensity7,imag); // CurrentDensity[B_index]
1875 LockDensityArray(Dens0,CurrentDensity8,imag); // CurrentDensity[B_index]
1876}
1877
1878/** Reset and unlocks all NDIM_NDIM current density arrays
1879 * \param Dens0 Density structure to be unlocked/resetted (in the current parts)
1880 */
1881void DisAllocCurrentDensity(struct Density *Dens0) {
1882 //int i;
1883 // real
1884// for(i=0;i<NDIM*NDIM;i++)
1885// SetArrayToDouble0((double *)Dens0->DensityArray[i], Dens0->TotalSize*2);
1886 UnLockDensityArray(Dens0,CurrentDensity0,real); // CurrentDensity[B_index]
1887 UnLockDensityArray(Dens0,CurrentDensity1,real); // CurrentDensity[B_index]
1888 UnLockDensityArray(Dens0,CurrentDensity2,real); // CurrentDensity[B_index]
1889 UnLockDensityArray(Dens0,CurrentDensity3,real); // CurrentDensity[B_index]
1890 UnLockDensityArray(Dens0,CurrentDensity4,real); // CurrentDensity[B_index]
1891 UnLockDensityArray(Dens0,CurrentDensity5,real); // CurrentDensity[B_index]
1892 UnLockDensityArray(Dens0,CurrentDensity6,real); // CurrentDensity[B_index]
1893 UnLockDensityArray(Dens0,CurrentDensity7,real); // CurrentDensity[B_index]
1894 UnLockDensityArray(Dens0,CurrentDensity8,real); // CurrentDensity[B_index]
1895 // imaginary
1896// for(i=0;i<NDIM*NDIM;i++)
1897// SetArrayToDouble0((double *)Dens0->DensityCArray[i], Dens0->TotalSize*2);
1898 UnLockDensityArray(Dens0,CurrentDensity0,imag); // CurrentDensity[B_index]
1899 UnLockDensityArray(Dens0,CurrentDensity1,imag); // CurrentDensity[B_index]
1900 UnLockDensityArray(Dens0,CurrentDensity2,imag); // CurrentDensity[B_index]
1901 UnLockDensityArray(Dens0,CurrentDensity3,imag); // CurrentDensity[B_index]
1902 UnLockDensityArray(Dens0,CurrentDensity4,imag); // CurrentDensity[B_index]
1903 UnLockDensityArray(Dens0,CurrentDensity5,imag); // CurrentDensity[B_index]
1904 UnLockDensityArray(Dens0,CurrentDensity6,imag); // CurrentDensity[B_index]
1905 UnLockDensityArray(Dens0,CurrentDensity7,imag); // CurrentDensity[B_index]
1906 UnLockDensityArray(Dens0,CurrentDensity8,imag); // CurrentDensity[B_index]
1907}
1908
1909// these defines safe-guard same symmetry for same kind of wave function
1910#define Psi0symmetry 0 // //0 //0 //0 // regard psi0 as real
1911#define Psi1symmetry 0 // //3 //0 //0 // regard psi0 as real
1912#define Psip0symmetry 6 //6 //6 //6 //6 // momentum times "i" due to operation on left hand
1913#define Psip1symmetry 7 //7 //4 //6 //7 // momentum times "-i" as usual (right hand)
1914
1915/** Evaluates the 3x3 current density arrays.
1916 * The formula we want to evaluate is as follows
1917 * \f[
1918 * j_k(r) = \langle \psi_k^{(0)} | \Bigl ( p|r'\rangle\langle r' | + | r' \rangle \langle r' | p \Bigr )
1919 \Bigl [ | \psi_k^{(r\times p )} \rangle - r' \times | \psi_k^{(p)} \rangle \Bigr ] \cdot B.
1920 * \f]
1921 * Most of the DensityTypes-arrays are locked for temporary use. Pointers are set to their
1922 * start address and afterwards the current density arrays locked and reset'ed. Then for every
1923 * unperturbed wave function we do:
1924 * -# FFT unperturbed p-perturbed and rxp-perturbed wave function
1925 * -# FFT wave function with applied momentum operator for all three indices
1926 * -# For each index of the momentum operator:
1927 * -# FFT p-perturbed wave function
1928 * -# For every index of the external field:
1929 * -# FFT rxp-perturbed wave function
1930 * -# Evaluate current density for these momentum index and external field indices
1931 *
1932 * Afterwards the temporary densities are unlocked and the density ones gathered from all Psi-
1933 * sharing processes.
1934 *
1935 * \param *P Problem at hand, containing Lattice and RunStruct
1936 */
1937void FillCurrentDensity(struct Problem *P)
1938{
1939 struct Lattice *Lat = &P->Lat;
1940 struct RunStruct *R = &P->R;
1941 struct Psis *Psi = &Lat->Psi;
1942 struct LatticeLevel *LevS = R->LevS;
1943 struct LatticeLevel *Lev0 = R->Lev0;
1944 struct Density *Dens0 = Lev0->Dens;
1945 fftw_complex *Psi0;
1946 fftw_real *Psi0R, *Psip0R;
1947 fftw_real *CurrentDensity[NDIM*NDIM];
1948 fftw_real *Psi1R;
1949 fftw_real *Psip1R;
1950 fftw_real *tempArray; // intendedly the same
1951 double r_bar[NDIM], x[NDIM], fac[NDIM];
1952 double Current;//, current;
1953 const double UnitsFactor = 1.; ///LevS->MaxN; // 1/N (from ff-backtransform)
1954 int i, index, B_index;
1955 int k, j, i0;
1956 int n[NDIM], n0;
1957 int N[NDIM];
1958 N[0] = Lev0->Plan0.plan->N[0];
1959 N[1] = Lev0->Plan0.plan->N[1];
1960 N[2] = Lev0->Plan0.plan->N[2];
1961 const int N0 = Lev0->Plan0.plan->local_nx;
1962 //int ActNum;
1963 const int myPE = P->Par.me_comm_ST_Psi;
1964 const int type = R->CurrentMin;
1965 MPI_Status status;
1966 int cross_lookup_1[4], cross_lookup_3[4], l_1 = 0, l_3 = 0;
1967
1968 //fprintf(stderr,"(%i) FactoR %e\n", P->Par.me, R->FactorDensityR);
1969
1970 // Init values and pointers
1971 if (P->Call.out[PsiOut]) {
1972 fprintf(stderr,"(%i) LockArray: ", P->Par.me);
1973 for(i=0;i<MaxDensityTypes;i++)
1974 fprintf(stderr,"(%i,%i) ",Dens0->LockArray[i],Dens0->LockCArray[i]);
1975 fprintf(stderr,"\n");
1976 }
1977 LockDensityArray(Dens0,Temp2Density,real); // Psi1R
1978 LockDensityArray(Dens0,Temp2Density,imag); // Psip1R and tempArray
1979 LockDensityArray(Dens0,GapDensity,real); // Psi0R
1980 LockDensityArray(Dens0,GapLocalDensity,real); // Psip0R
1981
1982 Psi0R = (fftw_real *)Dens0->DensityArray[GapDensity];
1983 Psip0R = (fftw_real *)Dens0->DensityArray[GapLocalDensity];
1984 Psi1R = (fftw_real *)Dens0->DensityArray[Temp2Density];
1985 tempArray = Psip1R = (fftw_real *)Dens0->DensityCArray[Temp2Density];
1986 SetArrayToDouble0((double *)Psi0R,Dens0->TotalSize*2);
1987 SetArrayToDouble0((double *)Psip0R,Dens0->TotalSize*2);
1988 SetArrayToDouble0((double *)Psi1R,Dens0->TotalSize*2);
1989 SetArrayToDouble0((double *)Psip1R,Dens0->TotalSize*2);
1990
1991 if (P->Call.out[PsiOut]) {
1992 fprintf(stderr,"(%i) LockArray: ", P->Par.me);
1993 for(i=0;i<MaxDensityTypes;i++)
1994 fprintf(stderr,"(%i,%i) ",Dens0->LockArray[i],Dens0->LockCArray[i]);
1995 fprintf(stderr,"\n");
1996 }
1997
1998 // don't put the following stuff into a for loop, they might not be continuous! (preprocessor values: CurrentDensity...)
1999 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
2000 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
2001 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
2002 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
2003 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
2004 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
2005 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
2006 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
2007 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
2008
2009 // initialize the array if it is the first of all six perturbation run
2010 if ((R->DoFullCurrent == 0) && (R->CurrentMin == Perturbed_P0)) { // reset if FillDelta...() hasn't done it before
2011 debug(P,"resetting CurrentDensity...");
2012 for (B_index=0; B_index<NDIM*NDIM; B_index++) // initialize current density array
2013 SetArrayToDouble0((double *)CurrentDensity[B_index],Dens0->TotalSize*2); // DensityArray is fftw_real, no 2*LocalSizeR here!
2014 }
2015
2016 switch(type) { // set j (which is linked to the index from derivation wrt to B^{ext})
2017 case Perturbed_P0:
2018 case Perturbed_P1:
2019 case Perturbed_P2:
2020 j = type - Perturbed_P0;
2021 l_1 = crossed(j,1);
2022 l_3 = crossed(j,3);
2023 for(k=0;k<4;k++) {
2024 cross_lookup_1[k] = cross(l_1,k);
2025 cross_lookup_3[k] = cross(l_3,k);
2026 }
2027 break;
2028 case Perturbed_RxP0:
2029 case Perturbed_RxP1:
2030 case Perturbed_RxP2:
2031 j = type - Perturbed_RxP0;
2032 break;
2033 default:
2034 j = 0;
2035 Error(SomeError,"FillCurrentDensity() called while not in perturbed minimisation!");
2036 break;
2037 }
2038
2039 int wished = -1;
2040 FILE *file = fopen(P->Call.MainParameterFile,"r");
2041 if (!ParseForParameter(1,file,"Orbital",0,1,1,int_type,&wished, 1, optional)) {
2042 fprintf(stderr,"Desired Orbital missing!\n");
2043 wished = -1;
2044 } else if (wished != -1) {
2045 fprintf(stderr,"Desired Orbital is: %i.\n", wished);
2046 } else {
2047 fprintf(stderr,"Desired Orbital is: All.\n");
2048 }
2049 fclose(file);
2050
2051 // Commence grid filling
2052 for (k=Psi->TypeStartIndex[Occupied];k<Psi->TypeStartIndex[Occupied+1];k++) // every local wave functions adds up its part of the current
2053 if ((k + P->Par.me_comm_ST_PsiT*(Psi->TypeStartIndex[UnOccupied]-Psi->TypeStartIndex[Occupied]) == wished) || (wished == -1)) { // compare with global number
2054 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i)Calculating Current Density Summand of type %s for Psi (%i/%i) ... \n", P->Par.me, R->MinimisationName[type], Psi->LocalPsiStatus[k].MyGlobalNo, k);
2055 //ActNum = k - Psi->TypeStartIndex[Occupied] + Psi->TypeStartIndex[1] * Psi->LocalPsiStatus[k].my_color_comm_ST_Psi; // global number of unperturbed Psi
2056 Psi0 = LevS->LPsi->LocalPsi[k]; // Local unperturbed psi
2057
2058 // now some preemptive ffts for the whole grid
2059 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Bringing |Psi0> one level up and fftransforming\n", P->Par.me);
2060 fft_Psi(P, Psi0, Psi0R, 0, Psi0symmetry); //0 // 0 //0
2061
2062 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Bringing |Psi1> one level up and fftransforming\n", P->Par.me);
2063 fft_Psi(P, LevS->LPsi->LocalPsi[Psi->TypeStartIndex[type]+k], Psi1R, 0, Psi1symmetry); //3 //0 //0
2064
2065 for (index=0;index<NDIM;index++) { // for all NDIM components of momentum operator
2066
2067 if ((P->Call.out[StepLeaderOut]) && (!index)) fprintf(stderr,"(%i) Bringing p|Psi0> one level up and fftransforming\n", P->Par.me);
2068 fft_Psi(P, Psi0, Psip0R, index, Psip0symmetry); //6 //6 //6
2069
2070 if ((P->Call.out[StepLeaderOut]) && (!index)) fprintf(stderr,"(%i) Bringing p|Psi1> one level up and fftransforming\n", P->Par.me);
2071 fft_Psi(P, LevS->LPsi->LocalPsi[Psi->TypeStartIndex[type]+k], Psip1R, index, Psip1symmetry); //4 //6 //7
2072
2073 // then for every point on the grid in real space ...
2074
2075 //if (Psi1R != (fftw_real *)Dens0->DensityArray[Temp2Density] || i0<0 || i0>=Dens0->LocalSizeR) Error(SomeError,"fft_Psi: Psi1R corrupted");
2076 //Psi1R[i0] = (Psi1_rxp_R[j])[i0] - (r_bar[cross(j,0)] * (Psi1_p_R[cross(j,1)])[i0] - r_bar[cross(j,2)] * (Psi1_p_R[cross(j,3)])[i0]); //
2077 //if (Psip1R != (fftw_real *)Dens0->DensityCArray[Temp2Density] || i0<0 || i0>=Dens0->LocalSizeR) Error(SomeError,"fft_Psi: Psip1R corrupted");
2078 //Psip1R[i0] = Psi1_rxp_pR[i0] - (r_bar[cross(j,0)] * (Psi1_p_pR[cross(j,1)])[i0] - r_bar[cross(j,2)] * (Psi1_p_pR[cross(j,3)])[i0]); //
2079
2080 switch(type) {
2081 case Perturbed_P0:
2082 case Perturbed_P1:
2083 case Perturbed_P2:
2084 for (n0=0;n0<N0;n0++) // only local points on x axis
2085 for (n[1]=0;n[1]<N[1];n[1]++)
2086 for (n[2]=0;n[2]<N[2];n[2]++) {
2087 i0 = n[2]+N[2]*(n[1]+N[1]*n0);
2088 n[0]=n0 + N0*myPE; // global relative coordinate: due to partitoning of x-axis in PEPGamma>1 case
2089 fac[0] = (double)n[0]/(double)N[0];
2090 fac[1] = (double)n[1]/(double)N[1];
2091 fac[2] = (double)n[2]/(double)N[2];
2092 RMat33Vec3(x, Lat->RealBasis, fac); // relative coordinate times basis matrix gives absolute ones
2093 for (i=0;i<NDIM;i++) // build gauge-translated r_bar evaluation point
2094 r_bar[i] =
2095 sawtooth(Lat,MinImageConv(Lat, x[i], Psi->AddData[k].WannierCentre[i], i),i);
2096// ShiftGaugeOrigin(P,truedist(Lat, x[i], Psi->AddData[k].WannierCentre[i], i),i);
2097 //truedist(Lat, x[i], Psi->AddData[k].WannierCentre[i], i);
2098
2099 Current = Psip0R[i0] * (r_bar[cross_lookup_1[0]] * Psi1R[i0]);
2100 Current += (Psi0R[i0] * r_bar[cross_lookup_1[0]] * Psip1R[i0]);
2101 Current *= .5 * UnitsFactor * Psi->LocalPsiStatus[k].PsiFactor * R->FactorDensityR; // factor confirmed, see CalculateOneDensityR() and InitDensityCalculation()
2102 ////if (CurrentDensity[index+j*NDIM] != (fftw_real *) Dens0->DensityArray[CurrentDensity0 + index+j*NDIM] || i0<0 || i0>=Dens0->LocalSizeR || (index+j*NDIM)<0 || (index+j*NDIM)>=NDIM*NDIM) Error(SomeError,"FillCurrentDensity: CurrentDensity[] corrupted");
2103 CurrentDensity[index+l_1*NDIM][i0] -= Current; // note: sign of cross product resides in Current itself (here: plus)
2104
2105 Current = - Psip0R[i0] * (r_bar[cross_lookup_3[2]] * Psi1R[i0]);
2106 Current += - (Psi0R[i0] * r_bar[cross_lookup_3[2]] * Psip1R[i0]);
2107 Current *= .5 * UnitsFactor * Psi->LocalPsiStatus[k].PsiFactor * R->FactorDensityR; // factor confirmed, see CalculateOneDensityR() and InitDensityCalculation()
2108 ////if (CurrentDensity[index+j*NDIM] != (fftw_real *) Dens0->DensityArray[CurrentDensity0 + index+j*NDIM] || i0<0 || i0>=Dens0->LocalSizeR || (index+j*NDIM)<0 || (index+j*NDIM)>=NDIM*NDIM) Error(SomeError,"FillCurrentDensity: CurrentDensity[] corrupted");
2109 CurrentDensity[index+l_3*NDIM][i0] -= Current; // note: sign of cross product resides in Current itself (here: minus)
2110 }
2111 break;
2112 case Perturbed_RxP0:
2113 case Perturbed_RxP1:
2114 case Perturbed_RxP2:
2115 for (n0=0;n0<N0;n0++) // only local points on x axis
2116 for (n[1]=0;n[1]<N[1];n[1]++)
2117 for (n[2]=0;n[2]<N[2];n[2]++) {
2118 i0 = n[2]+N[2]*(n[1]+N[1]*n0);
2119 Current = (Psip0R[i0] * Psi1R[i0] + Psi0R[i0] * Psip1R[i0]);
2120 Current *= .5 * UnitsFactor * Psi->LocalPsiStatus[k].PsiFactor * R->FactorDensityR; // factor confirmed, see CalculateOneDensityR() and InitDensityCalculation()
2121 ////if (CurrentDensity[index+j*NDIM] != (fftw_real *) Dens0->DensityArray[CurrentDensity0 + index+j*NDIM] || i0<0 || i0>=Dens0->LocalSizeR || (index+j*NDIM)<0 || (index+j*NDIM)>=NDIM*NDIM) Error(SomeError,"FillCurrentDensity: CurrentDensity[] corrupted");
2122 CurrentDensity[index+j*NDIM][i0] += Current;
2123 }
2124 break;
2125 default:
2126 break;
2127 }
2128 }
2129 //OutputCurrentDensity(P);
2130 }
2131
2132 //debug(P,"Unlocking arrays");
2133 //debug(P,"GapDensity");
2134 UnLockDensityArray(Dens0,GapDensity,real); // Psi0R
2135 //debug(P,"GapLocalDensity");
2136 UnLockDensityArray(Dens0,GapLocalDensity,real); // Psip0R
2137 //debug(P,"Temp2Density");
2138 UnLockDensityArray(Dens0,Temp2Density,real); // Psi1R
2139
2140// if (P->Call.out[StepLeaderOut])
2141// fprintf(stderr,"\n\n");
2142
2143 //debug(P,"MPI operation");
2144 // and in the end gather partial densities from other processes
2145 if (type == Perturbed_RxP2) // exchange all (due to shared wave functions) only after last pertubation run
2146 for (index=0;index<NDIM*NDIM;index++) {
2147 //if (tempArray != (fftw_real *)Dens0->DensityCArray[Temp2Density]) Error(SomeError,"FillCurrentDensity: tempArray corrupted");
2148 //debug(P,"tempArray to zero");
2149 SetArrayToDouble0((double *)tempArray, Dens0->TotalSize*2);
2150 ////if (CurrentDensity[index] != (fftw_real *) Dens0->DensityArray[CurrentDensity0 + index]) Error(SomeError,"FillCurrentDensity: CurrentDensity[] corrupted");
2151 //debug(P,"CurrentDensity exchange");
2152 MPI_Allreduce( CurrentDensity[index], tempArray, Dens0->LocalSizeR, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_PsiT); // gather results from all wave functions ...
2153 switch(Psi->PsiST) { // ... and also from SpinUp/Downs
2154 default:
2155 //debug(P,"CurrentDensity = tempArray");
2156 for (i=0;i<Dens0->LocalSizeR;i++) {
2157 ////if (CurrentDensity[index] != (fftw_real *) Dens0->DensityArray[CurrentDensity0 + index] || i<0 || i>=Dens0->LocalSizeR) Error(SomeError,"FillCurrentDensity: CurrentDensity[] corrupted");
2158 CurrentDensity[index][i] = tempArray[i];
2159 }
2160 break;
2161 case SpinUp:
2162 //debug(P,"CurrentDensity exchange spinup");
2163 MPI_Sendrecv(tempArray, Dens0->LocalSizeR, MPI_DOUBLE, P->Par.me_comm_ST, CurrentTag1,
2164 CurrentDensity[index], Dens0->LocalSizeR, MPI_DOUBLE, P->Par.me_comm_ST, CurrentTag2, P->Par.comm_STInter, &status );
2165 //debug(P,"CurrentDensity += tempArray");
2166 for (i=0;i<Dens0->LocalSizeR;i++) {
2167 ////if (CurrentDensity[index] != (fftw_real *) Dens0->DensityArray[CurrentDensity0 + index] || i<0 || i>=Dens0->LocalSizeR) Error(SomeError,"FillCurrentDensity: CurrentDensity[] corrupted");
2168 CurrentDensity[index][i] += tempArray[i];
2169 }
2170 break;
2171 case SpinDown:
2172 //debug(P,"CurrentDensity exchange spindown");
2173 MPI_Sendrecv(tempArray, Dens0->LocalSizeR, MPI_DOUBLE, P->Par.me_comm_ST, CurrentTag2,
2174 CurrentDensity[index], Dens0->LocalSizeR, MPI_DOUBLE, P->Par.me_comm_ST, CurrentTag1, P->Par.comm_STInter, &status );
2175 //debug(P,"CurrentDensity += tempArray");
2176 for (i=0;i<Dens0->LocalSizeR;i++) {
2177 ////if (CurrentDensity[index] != (fftw_real *) Dens0->DensityArray[CurrentDensity0 + index] || i<0 || i>=Dens0->LocalSizeR) Error(SomeError,"FillCurrentDensity: CurrentDensity[] corrupted");
2178 CurrentDensity[index][i] += tempArray[i];
2179 }
2180 break;
2181 }
2182 }
2183 //debug(P,"Temp2Density");
2184 UnLockDensityArray(Dens0,Temp2Density,imag); // Psip1R and tempArray
2185 //debug(P,"CurrentDensity end");
2186}
2187
2188/** Structure holding Problem at hand and two indices, defining the greens function to be inverted.
2189 */
2190struct params
2191{
2192 struct Problem *P;
2193 int *k;
2194 int *l;
2195 int *iter;
2196 fftw_complex *x_l;
2197};
2198
2199/** Wrapper function to solve G_kl x = b for x.
2200 * \param *x above x
2201 * \param *param additional parameters, here Problem at hand
2202 * \return evaluated to be minimized functional \f$\frac{1}{2}x \cdot Ax - xb\f$ at \a x on return
2203 */
2204static double DeltaCurrent_f(const gsl_vector * x, void * param)
2205{
2206 struct Problem *P = ((struct params *)param)->P;
2207 struct RunStruct *R = &P->R;
2208 struct LatticeLevel *LevS = R->LevS;
2209 struct Psis *Psi = &P->Lat.Psi;
2210 struct PseudoPot *PP = &P->PP;
2211 const double PsiFactor = Psi->AllPsiStatus[*((struct params *)param)->k].PsiFactor;
2212 double result = 0.;
2213 fftw_complex *TempPsi = LevS->LPsi->TempPsi;
2214 fftw_complex *TempPsi2 = LevS->LPsi->TempPsi2;
2215 int u;
2216
2217 //fprintf(stderr,"Evaluating f(%i,%i) for %i-th time\n", *((struct params *)param)->k, *((struct params *)param)->l, *((struct params *)param)->iter);
2218
2219 // extract gsl_vector
2220 for (u=0;u<LevS->MaxG;u++) {
2221 TempPsi[u].re = gsl_vector_get(x, 2*u);
2222 TempPsi[u].im = gsl_vector_get(x, 2*u+1);
2223 }
2224 // generate fnl
2225 CalculateCDfnl(P, TempPsi, PP->CDfnl); // calculate needed non-local form factors
2226 // Apply Hamiltonian to x
2227 ApplyTotalHamiltonian(P,TempPsi,TempPsi2, PP->CDfnl,PsiFactor,0);
2228 // take scalar product to get eigen value
2229 result = .5 * PsiFactor * (((*((struct params *)param)->k == *((struct params *)param)->l ? GradSP(P,LevS,TempPsi,TempPsi2) : 0.) - Psi->lambda[*((struct params *)param)->k][*((struct params *)param)->l])) - GradSP(P,LevS,TempPsi,LevS->LPsi->LocalPsi[*((struct params *)param)->l]);
2230 return result;
2231}
2232
2233/** Wrapper function to solve G_kl x = b for x.
2234 * \param *x above x
2235 * \param *param additional parameters, here Problem at hand
2236 * \param *g gradient vector on return
2237 * \return error code
2238 */
2239static void DeltaCurrent_df(const gsl_vector * x, void * param, gsl_vector * g)
2240{
2241 struct Problem *P = ((struct params *)param)->P;
2242 struct RunStruct *R = &P->R;
2243 struct LatticeLevel *LevS = R->LevS;
2244 struct Psis *Psi = &P->Lat.Psi;
2245 struct PseudoPot *PP = &P->PP;
2246 const double PsiFactor = Psi->AllPsiStatus[*((struct params *)param)->k].PsiFactor;
2247 fftw_complex *TempPsi = LevS->LPsi->TempPsi;
2248 fftw_complex *TempPsi2 = LevS->LPsi->TempPsi2;
2249 fftw_complex *x_l = ((struct params *)param)->x_l;
2250 int u;
2251
2252 //fprintf(stderr,"Evaluating df(%i,%i) for %i-th time\n", *((struct params *)param)->k, *((struct params *)param)->l, *((struct params *)param)->iter);
2253
2254 // extract gsl_vector
2255 for (u=0;u<LevS->MaxG;u++) {
2256 TempPsi[u].re = gsl_vector_get(x, 2*u);
2257 TempPsi[u].im = gsl_vector_get(x, 2*u+1);
2258 }
2259 // generate fnl
2260 CalculateCDfnl(P, TempPsi, PP->CDfnl); // calculate needed non-local form factors
2261 // Apply Hamiltonian to x
2262 ApplyTotalHamiltonian(P,TempPsi,TempPsi2, PP->CDfnl,PsiFactor,0);
2263 // put into returning vector
2264 for (u=0;u<LevS->MaxG;u++) {
2265 gsl_vector_set(g, 2*u, TempPsi2[u].re - x_l[u].re);
2266 gsl_vector_set(g, 2*u+1, TempPsi2[u].im - x_l[u].im);
2267 }
2268}
2269
2270/** Wrapper function to solve G_kl x = b for x.
2271 * \param *x above x
2272 * \param *param additional parameters, here Problem at hand
2273 * \param *f evaluated to be minimized functional \f$\frac{1}{2}x \cdot Ax - xb\f$ at \a x on return
2274 * \param *g gradient vector on return
2275 * \return error code
2276 */
2277static void DeltaCurrent_fdf(const gsl_vector * x, void * param, double * f, gsl_vector * g)
2278{
2279 struct Problem *P = ((struct params *)param)->P;
2280 struct RunStruct *R = &P->R;
2281 struct LatticeLevel *LevS = R->LevS;
2282 struct Psis *Psi = &P->Lat.Psi;
2283 struct PseudoPot *PP = &P->PP;
2284 const double PsiFactor = Psi->AllPsiStatus[*((struct params *)param)->k].PsiFactor;
2285 fftw_complex *TempPsi = LevS->LPsi->TempPsi;
2286 fftw_complex *TempPsi2 = LevS->LPsi->TempPsi2;
2287 fftw_complex *x_l = ((struct params *)param)->x_l;
2288 int u;
2289
2290 //fprintf(stderr,"Evaluating fdf(%i,%i) for %i-th time\n", *((struct params *)param)->k, *((struct params *)param)->l, *((struct params *)param)->iter);
2291
2292 // extract gsl_vector
2293 for (u=0;u<LevS->MaxG;u++) {
2294 TempPsi[u].re = gsl_vector_get(x, 2*u);
2295 TempPsi[u].im = gsl_vector_get(x, 2*u+1);
2296 }
2297 // generate fnl
2298 CalculateCDfnl(P, TempPsi, PP->CDfnl); // calculate needed non-local form factors
2299 // Apply Hamiltonian to x
2300 ApplyTotalHamiltonian(P,TempPsi,TempPsi2, PP->CDfnl,PsiFactor,0);
2301 // put into returning vector
2302 for (u=0;u<LevS->MaxG;u++) {
2303 gsl_vector_set(g, 2*u, TempPsi[u].re - x_l[u].re);
2304 gsl_vector_set(g, 2*u+1, TempPsi[u].im - x_l[u].im);
2305 }
2306
2307 *f = .5 * PsiFactor * (((*((struct params *)param)->k == *((struct params *)param)->l ? GradSP(P,LevS,TempPsi,TempPsi2) : 0.) - Psi->lambda[*((struct params *)param)->k][*((struct params *)param)->l])) - GradSP(P,LevS,TempPsi,LevS->LPsi->LocalPsi[*((struct params *)param)->l]);
2308}
2309
2310/** Evaluates the \f$\Delta j_k(r')\f$ component of the current density.
2311 * \f[
2312 * \Delta j_k(r') = \frac{e}{m} \sum_l \langle \varphi^{(0)}_k | \left ( p |r'\rangle \langle r'| + | r'\rangle\langle r'|p \right ) {\cal G}_{kl} (d_k - d_l) \times p | \varphi^{(1)}_l \rangle \cdot B
2313 * \f]
2314 * \param *P Problem at hand
2315 * \note result has not yet been MPI_Allreduced for ParallelSimulationData#comm_ST_inter or ParallelSimulationData#comm_ST_PsiT groups!
2316 * \warning the routine is checked but does not yet produce sensible results.
2317 */
2318void FillDeltaCurrentDensity(struct Problem *P)
2319{
2320 struct Lattice *Lat = &P->Lat;
2321 struct RunStruct *R = &P->R;
2322 struct Psis *Psi = &Lat->Psi;
2323 struct LatticeLevel *Lev0 = R->Lev0;
2324 struct LatticeLevel *LevS = R->LevS;
2325 struct Density *Dens0 = Lev0->Dens;
2326 int i,j,s;
2327 int k,l,u, in, dex, index,i0;
2328 //const int Num = Psi->NoOfPsis;
2329 int RecvSource;
2330 MPI_Status status;
2331 struct OnePsiElement *OnePsiB, *LOnePsiB, *OnePsiA, *LOnePsiA;
2332 const int ElementSize = (sizeof(fftw_complex) / sizeof(double));
2333 int n[NDIM], n0;
2334 int N[NDIM];
2335 N[0] = Lev0->Plan0.plan->N[0];
2336 N[1] = Lev0->Plan0.plan->N[1];
2337 N[2] = Lev0->Plan0.plan->N[2];
2338 const int N0 = Lev0->Plan0.plan->local_nx;
2339 fftw_complex *LPsiDatB;
2340 fftw_complex *Psi0, *Psi1;
2341 fftw_real *Psi0R, *Psip0R;
2342 fftw_real *Psi1R, *Psip1R;
2343 fftw_complex *x_l = LevS->LPsi->TempPsi;//, **x_l_bak;
2344 fftw_real *CurrentDensity[NDIM*NDIM];
2345 int mem_avail, MEM_avail;
2346 double Current;
2347 const double UnitsFactor = 1.;
2348 int cross_lookup[4];
2349 struct params param;
2350 double factor; // temporary factor in Psi1 pre-evaluation
2351
2352 LockDensityArray(Dens0,GapDensity,real); // Psi0R
2353 LockDensityArray(Dens0,GapLocalDensity,real); // Psip0R
2354 LockDensityArray(Dens0,Temp2Density,imag); // Psi1
2355 LockDensityArray(Dens0,GapUpDensity,real); // Psi1R
2356 LockDensityArray(Dens0,GapDownDensity,real); // Psip1R
2357
2358 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
2359 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
2360 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
2361 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
2362 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
2363 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
2364 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
2365 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
2366 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
2367
2368 Psi0R = (fftw_real *)Dens0->DensityArray[GapDensity];
2369 Psip0R = (fftw_real *)Dens0->DensityArray[GapLocalDensity];
2370 Psi1 = (fftw_complex *) Dens0->DensityCArray[Temp2Density];
2371 Psi1R = (fftw_real *)Dens0->DensityArray[GapUpDensity];
2372 Psip1R = (fftw_real *)Dens0->DensityArray[GapDownDensity];
2373
2374// if (R->CurrentMin == Perturbed_P0)
2375// for (B_index=0; B_index<NDIM*NDIM; B_index++) { // initialize current density array
2376// debug(P,"resetting CurrentDensity...");
2377// SetArrayToDouble0((double *)CurrentDensity[B_index],Dens0->TotalSize*2); // DensityArray is fftw_real, no 2*LocalSizeR here!
2378// }
2379 //if (Psi1 != (fftw_complex *) Dens0->DensityCArray[Temp2Density]) Error(SomeError,"FillDeltaCurrentDensity: Psi1 corrupted");
2380 SetArrayToDouble0((double *)Psi1,2*Dens0->TotalSize);
2381
2382// gsl_vector *x = gsl_vector_alloc(Num);
2383// gsl_matrix *G = gsl_matrix_alloc(Num,Num);
2384// gsl_permutation *p = gsl_permutation_alloc(Num);
2385 //int signum;
2386 // begin of GSL linearer CG solver stuff
2387 int iter, Status;
2388
2389 const gsl_multimin_fdfminimizer_type *T;
2390 gsl_multimin_fdfminimizer *minset;
2391
2392 /* Position of the minimum (1,2). */
2393 //double par[2] = { 1.0, 2.0 };
2394
2395 gsl_vector *x;
2396 gsl_multimin_function_fdf my_func;
2397
2398 param.P = P;
2399 param.k = &k;
2400 param.l = &l;
2401 param.iter = &iter;
2402 param.x_l = x_l;
2403
2404 my_func.f = &DeltaCurrent_f;
2405 my_func.df = &DeltaCurrent_df;
2406 my_func.fdf = &DeltaCurrent_fdf;
2407 my_func.n = 2*LevS->MaxG;
2408 my_func.params = (void *)&param;
2409
2410 T = gsl_multimin_fdfminimizer_conjugate_pr;
2411 minset = gsl_multimin_fdfminimizer_alloc (T, 2*LevS->MaxG);
2412 x = gsl_vector_alloc (2*LevS->MaxG);
2413 // end of GSL CG stuff
2414
2415
2416// // construct G_kl = - (H^{(0)} \delta_{kl} -\langle \varphi^{(0)}_k |H^{(0)}| \varphi^{(0)}_l|rangle)^{-1} = A^{-1}
2417// for (k=0;k<Num;k++)
2418// for (l=0;l<Num;l++)
2419// gsl_matrix_set(G, k, l, k == l ? 0. : Psi->lambda[k][l]);
2420// // and decompose G_kl = L U
2421
2422 mem_avail = MEM_avail = 0;
2423// x_l_bak = x_l = (fftw_complex **) Malloc(sizeof(fftw_complex *)*Num,"FillDeltaCurrentDensity: *x_l");
2424// for (i=0;i<Num;i++) {
2425// x_l[i] = NULL;
2426// x_l[i] = (fftw_complex *) malloc(sizeof(fftw_complex)*LevS->MaxG);
2427// if (x_l[i] == NULL) {
2428// mem_avail = 1; // there was not enough memory for this node
2429// fprintf(stderr,"(%i) FillDeltaCurrentDensity: x_l[%i] ... insufficient memory.\n",P->Par.me,i);
2430// }
2431// }
2432// MPI_Allreduce(&mem_avail,&MEM_avail,1,MPI_INT,MPI_SUM,P->Par.comm_ST); // sum results from all processes
2433
2434 if (MEM_avail != 0) { // means at least node couldn't allocate sufficient memory, skipping...
2435 fprintf(stderr,"(%i) FillDeltaCurrentDensity: x_l[], not enough memory: %i! Skipping FillDeltaCurrentDensity evaluation.", P->Par.me, MEM_avail);
2436 } else {
2437 // sum over k and calculate \Delta j_k(r')
2438 k=-1;
2439 for (i=0; i < Psi->MaxPsiOfType+P->Par.Max_me_comm_ST_PsiT; i++) { // go through all wave functions
2440 //fprintf(stderr,"(%i) GlobalNo: %d\tLocalNo: %d\n", P->Par.me,Psi->AllPsiStatus[i].MyGlobalNo,Psi->AllPsiStatus[i].MyLocalNo);
2441 OnePsiA = &Psi->AllPsiStatus[i]; // grab OnePsiA
2442 if (OnePsiA->PsiType == Occupied) { // drop the extra and perturbed ones
2443 k++;
2444 if (OnePsiA->my_color_comm_ST_Psi == P->Par.my_color_comm_ST_Psi) // local?
2445 LOnePsiA = &Psi->LocalPsiStatus[OnePsiA->MyLocalNo];
2446 else
2447 LOnePsiA = NULL;
2448 if (LOnePsiA != NULL) {
2449 Psi0=LevS->LPsi->LocalPsi[OnePsiA->MyLocalNo];
2450
2451 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Bringing |Psi0> one level up and fftransforming\n", P->Par.me);
2452 //if (Psi0R != (fftw_real *)Dens0->DensityArray[GapDensity]) Error(SomeError,"FillDeltaCurrentDensity: Psi0R corrupted");
2453 fft_Psi(P,Psi0,Psi0R, 0, Psi0symmetry); //0 // 0 //0
2454
2455 for (in=0;in<NDIM;in++) { // in is the index from derivation wrt to B^{ext}
2456 l = -1;
2457 for (j=0; j < Psi->MaxPsiOfType+P->Par.Max_me_comm_ST_PsiT; j++) { // go through all wave functions
2458 OnePsiB = &Psi->AllPsiStatus[j]; // grab OnePsiA
2459 if (OnePsiB->PsiType == Occupied)
2460 l++;
2461 if ((OnePsiB != OnePsiA) && (OnePsiB->PsiType == Occupied)) { // drop the same and the extra ones
2462 if (OnePsiB->my_color_comm_ST_Psi == P->Par.my_color_comm_ST_Psi) // local?
2463 LOnePsiB = &Psi->LocalPsiStatus[OnePsiB->MyLocalNo];
2464 else
2465 LOnePsiB = NULL;
2466 if (LOnePsiB == NULL) { // if it's not local ... receive x from respective process
2467 RecvSource = OnePsiB->my_color_comm_ST_Psi;
2468 MPI_Recv( x_l, LevS->MaxG*ElementSize, MPI_DOUBLE, RecvSource, HamiltonianTag, P->Par.comm_ST_PsiT, &status );
2469 } else { // .. otherwise setup wave function as x ...
2470 // Evaluate cross product: \epsilon_{ijm} (d_k - d_l)_j p_m | \varphi^{(0)} \rangle = b_i ... and
2471 LPsiDatB=LevS->LPsi->LocalPsi[OnePsiB->MyLocalNo];
2472 //LPsiDatx=LevS->LPsi->LocalPsi[OnePsiB->MyLocalNo+Psi->TypeStartIndex[Perturbed_P0]];
2473 //CalculatePerturbationOperator_P(P,LPsiDatB,LPsiDatB_p0,cross(in,1),0);
2474 //CalculatePerturbationOperator_P(P,LPsiDatB,LPsiDatB_p1,cross(in,3),0);
2475 for (dex=0;dex<4;dex++)
2476 cross_lookup[dex] = cross(in,dex);
2477 for(s=0;s<LevS->MaxG;s++) {
2478 //if (x_l != x_l_bak || s<0 || s>LevS->MaxG) Error(SomeError,"FillDeltaCurrentDensity: x_l[] corrupted");
2479 factor =
2480 (MinImageConv(Lat,Psi->AddData[LOnePsiA->MyLocalNo].WannierCentre[cross_lookup[0]],
2481 Psi->AddData[LOnePsiB->MyLocalNo].WannierCentre[cross_lookup[0]],cross_lookup[0]) * LevS->GArray[s].G[cross_lookup[1]] -
2482 MinImageConv(Lat,Psi->AddData[LOnePsiA->MyLocalNo].WannierCentre[cross_lookup[2]],
2483 Psi->AddData[LOnePsiB->MyLocalNo].WannierCentre[cross_lookup[2]],cross_lookup[2]) * LevS->GArray[s].G[cross_lookup[3]]);
2484 x_l[s].re = factor * (-LPsiDatB[s].im); // switched due to factorization with "-i G"
2485 x_l[s].im = factor * (LPsiDatB[s].re);
2486 }
2487 // ... and send it to all other processes (Max_me... - 1)
2488 for (u=0;u<P->Par.Max_me_comm_ST_PsiT;u++)
2489 if (u != OnePsiB->my_color_comm_ST_Psi)
2490 MPI_Send( x_l, LevS->MaxG*ElementSize, MPI_DOUBLE, u, HamiltonianTag, P->Par.comm_ST_PsiT);
2491 } // x_l row is now filled (either by receiving result or evaluating it on its own)
2492 // Solve Ax = b by minimizing 1/2 xAx -xb (gradient is residual Ax - b) with conjugate gradient polak-ribiere
2493
2494 debug(P,"fill starting point x with values from b");
2495 /* Starting point, x = b */
2496 for (u=0;u<LevS->MaxG;u++) {
2497 gsl_vector_set (x, 2*u, x_l[u].re);
2498 gsl_vector_set (x, 2*u+1, x_l[u].im);
2499 }
2500
2501 gsl_multimin_fdfminimizer_set (minset, &my_func, x, 0.01, 1e-4);
2502
2503 fprintf(stderr,"(%i) Start solving for (%i,%i) and index %i\n",P->Par.me, k,l,in);
2504 // start solving
2505 iter = 0;
2506 do
2507 {
2508 iter++;
2509 Status = gsl_multimin_fdfminimizer_iterate (minset);
2510
2511 if (Status)
2512 break;
2513
2514 Status = gsl_multimin_test_gradient (minset->gradient, 1e-3);
2515
2516 if (Status == GSL_SUCCESS)
2517 fprintf (stderr,"(%i) Minimum found after %i iterations.\n", P->Par.me, iter);
2518
2519 } while (Status == GSL_CONTINUE && iter < 100);
2520
2521 debug(P,"Put solution into Psi1");
2522 // ... and what do we do now? Put solution into Psi1!
2523 for(s=0;s<LevS->MaxG;s++) {
2524 //if (Psi1 != (fftw_complex *) Dens0->DensityCArray[Temp2Density] || s<0 || s>LevS->MaxG) Error(SomeError,"FillDeltaCurrentDensity: Psi1 corrupted");
2525 Psi1[s].re = gsl_vector_get (minset->x, 2*s);
2526 Psi1[s].im = gsl_vector_get (minset->x, 2*s+1);
2527 }
2528
2529 // // Solve A^{-1} b_i = x
2530 // for(s=0;s<LevS->MaxG;s++) {
2531 // // REAL PART
2532 // // retrieve column from gathered matrix
2533 // for(u=0;u<Num;u++)
2534 // gsl_vector_set(x,u,x_l[u][s].re);
2535 //
2536 // // solve: sum_l A_{kl}^(-1) b_l (s) = x_k (s)
2537 // gsl_linalg_LU_svx (G, p, x);
2538 //
2539 // // put solution back into x_l[s]
2540 // for(u=0;u<Num;u++) {
2541 // //if (x_l != x_l_bak || s<0 || s>=LevS->MaxG) Error(SomeError,"FillDeltaCurrentDensity: x_l[] corrupted");
2542 // x_l[u][s].re = gsl_vector_get(x,u);
2543 // }
2544 //
2545 // // IMAGINARY PART
2546 // // retrieve column from gathered matrix
2547 // for(u=0;u<Num;u++)
2548 // gsl_vector_set(x,u,x_l[u][s].im);
2549 //
2550 // // solve: sum_l A_{kl}^(-1) b_l (s) = x_k (s)
2551 // gsl_linalg_LU_svx (G, p, x);
2552 //
2553 // // put solution back into x_l[s]
2554 // for(u=0;u<Num;u++) {
2555 // //if (x_l != x_l_bak || s<0 || s>=LevS->MaxG) Error(SomeError,"FillDeltaCurrentDensity: x_l[] corrupted");
2556 // x_l[u][s].im = gsl_vector_get(x,u);
2557 // }
2558 // } // now we have in x_l a vector similar to "Psi1" which we use to evaluate the current density
2559 //
2560 // // evaluate \Delta J_k ... mind the minus sign from G_kl!
2561 // // fill Psi1
2562 // for(s=0;s<LevS->MaxG;s++) {
2563 // //if (Psi1 != (fftw_complex *) Dens0->DensityCArray[Temp2Density] || s<0 || s>LevS->MaxG) Error(SomeError,"FillDeltaCurrentDensity: Psi1 corrupted");
2564 // Psi1[s].re = x_l[k][s].re;
2565 // Psi1[s].im = x_l[k][s].im;
2566 // }
2567
2568 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Bringing |Psi1> one level up and fftransforming\n", P->Par.me);
2569 //if (Psi1R != (fftw_real *)Dens0->DensityArray[GapUpDensity]) Error(SomeError,"FillDeltaCurrentDensity: Psi1R corrupted");
2570 fft_Psi(P,Psi1,Psi1R, 0, Psi1symmetry); //2 // 0 //0
2571
2572 for (index=0;index<NDIM;index++) { // for all NDIM components of momentum operator
2573
2574 if ((P->Call.out[StepLeaderOut]) && (!index)) fprintf(stderr,"(%i) Bringing p|Psi0> one level up and fftransforming\n", P->Par.me);
2575 //if (Psip0R != (fftw_real *)Dens0->DensityArray[GapLocalDensity]) Error(SomeError,"FillDeltaCurrentDensity: Psip0R corrupted");
2576 fft_Psi(P,Psi0,Psip0R, index, Psip0symmetry); //6 //6 //6
2577
2578 if ((P->Call.out[StepLeaderOut]) && (!index)) fprintf(stderr,"(%i) Bringing p|Psi1> one level up and fftransforming\n", P->Par.me);
2579 //if (Psip1R != (fftw_real *)Dens0->DensityArray[GapDownDensity]) Error(SomeError,"FillDeltaCurrentDensity: Psip1R corrupted");
2580 fft_Psi(P,Psi1,Psip1R, index, Psip1symmetry); //4 //6 //6
2581
2582 // then for every point on the grid in real space ...
2583 for (n0=0;n0<N0;n0++) // only local points on x axis
2584 for (n[1]=0;n[1]<N[1];n[1]++)
2585 for (n[2]=0;n[2]<N[2];n[2]++) {
2586 i0 = n[2]+N[2]*(n[1]+N[1]*n0);
2587 // and take the product
2588 Current = (Psip0R[i0] * Psi1R[i0] + Psi0R[i0] * Psip1R[i0]);
2589 Current *= 0.5 * UnitsFactor * Psi->AllPsiStatus[OnePsiA->MyGlobalNo].PsiFactor * R->FactorDensityR;
2590 ////if (CurrentDensity[index+in*NDIM] != (fftw_real *) Dens0->DensityArray[CurrentDensity0 + index+in*NDIM]) Error(SomeError,"FillCurrentDensity: CurrentDensity[] corrupted");
2591 //if (i0<0 || i0>=Dens0->LocalSizeR) Error(SomeError,"FillDeltaCurrentDensity: i0 out of range");
2592 //if ((index+in*NDIM)<0 || (index+in*NDIM)>=NDIM*NDIM) Error(SomeError,"FillDeltaCurrentDensity: index out of range");
2593 CurrentDensity[index+in*NDIM][i0] += Current; // minus sign is from G_kl
2594 }
2595 }
2596 }
2597 }
2598 }
2599 }
2600 }
2601 }
2602 }
2603 UnLockDensityArray(Dens0,GapDensity,real); // Psi0R
2604 UnLockDensityArray(Dens0,GapLocalDensity,real); // Psip0R
2605 UnLockDensityArray(Dens0,Temp2Density,imag); // Psi1
2606 UnLockDensityArray(Dens0,GapUpDensity,real); // Psi1R
2607 UnLockDensityArray(Dens0,GapDownDensity,real); // Psip1R
2608// for (i=0;i<Num;i++)
2609// if (x_l[i] != NULL) Free(x_l[i], "bla", "bla");
2610// Free(x_l, "bla");
2611 gsl_multimin_fdfminimizer_free (minset);
2612 gsl_vector_free (x);
2613// gsl_matrix_free(G);
2614// gsl_permutation_free(p);
2615// gsl_vector_free(x);
2616}
2617
2618
2619/** Evaluates the overlap integral between \a state wave functions.
2620 * \f[
2621 * S_{kl} = \langle \varphi_k^{(1)} | \varphi_l^{(1)} \rangle
2622 * \f]
2623 * The scalar product is calculated via GradSP(), MPI_Allreduced among comm_ST_Psi and the result
2624 * stored in Psis#Overlap. The rows have to be MPI exchanged, as otherwise processes will add
2625 * to the TotalEnergy overlaps calculated with old wave functions - they have been minimised after
2626 * the product with exchanged coefficients was taken.
2627 * \param *P Problem at hand
2628 * \param l local number of perturbed wave function.
2629 * \param state PsiTypeTag minimisation state of wave functions to be overlapped
2630 */
2631void CalculateOverlap(struct Problem *P, const int l, const enum PsiTypeTag state)
2632{
2633 struct RunStruct *R = &P->R;
2634 struct Lattice *Lat = &(P->Lat);
2635 struct Psis *Psi = &Lat->Psi;
2636 struct LatticeLevel *LevS = R->LevS;
2637 struct OnePsiElement *OnePsiB, *LOnePsiB;
2638 fftw_complex *LPsiDatB=NULL, *LPsiDatA=NULL;
2639 const int ElementSize = (sizeof(fftw_complex) / sizeof(double));
2640 int RecvSource;
2641 MPI_Status status;
2642 int i,j,m,p;
2643 //const int l_normal = l - Psi->TypeStartIndex[state] + Psi->TypeStartIndex[Occupied];
2644 const int ActNum = l - Psi->TypeStartIndex[state] + Psi->TypeStartIndex[1] * Psi->LocalPsiStatus[l].my_color_comm_ST_Psi;
2645 double *sendbuf, *recvbuf;
2646 double tmp,TMP;
2647 const int gsize = P->Par.Max_me_comm_ST_PsiT; //number of processes in PsiT
2648 int p_num; // number of wave functions (for overlap)
2649
2650 // update overlap table after wave function has changed
2651 LPsiDatA = LevS->LPsi->LocalPsi[l];
2652 m = -1; // to access U matrix element (0..Num-1)
2653 for (j=0; j < Psi->MaxPsiOfType+P->Par.Max_me_comm_ST_PsiT; j++) { // go through all wave functions
2654 OnePsiB = &Psi->AllPsiStatus[j]; // grab OnePsiB
2655 if (OnePsiB->PsiType == state) { // drop all but the ones of current min state
2656 m++; // increase m if it is non-extra wave function
2657 if (OnePsiB->my_color_comm_ST_Psi == P->Par.my_color_comm_ST_Psi) // local?
2658 LOnePsiB = &Psi->LocalPsiStatus[OnePsiB->MyLocalNo];
2659 else
2660 LOnePsiB = NULL;
2661 if (LOnePsiB == NULL) { // if it's not local ... receive it from respective process into TempPsi
2662 RecvSource = OnePsiB->my_color_comm_ST_Psi;
2663 MPI_Recv( LevS->LPsi->TempPsi, LevS->MaxG*ElementSize, MPI_DOUBLE, RecvSource, OverlapTag, P->Par.comm_ST_PsiT, &status );
2664 LPsiDatB=LevS->LPsi->TempPsi;
2665 } else { // .. otherwise send it to all other processes (Max_me... - 1)
2666 for (p=0;p<P->Par.Max_me_comm_ST_PsiT;p++)
2667 if (p != OnePsiB->my_color_comm_ST_Psi)
2668 MPI_Send( LevS->LPsi->LocalPsi[OnePsiB->MyLocalNo], LevS->MaxG*ElementSize, MPI_DOUBLE, p, OverlapTag, P->Par.comm_ST_PsiT);
2669 LPsiDatB=LevS->LPsi->LocalPsi[OnePsiB->MyLocalNo];
2670 } // LPsiDatB is now set to the coefficients of OnePsi either stored or MPI_Received
2671
2672 tmp = GradSP(P, LevS, LPsiDatA, LPsiDatB) * sqrt(Psi->LocalPsiStatus[l].PsiFactor * OnePsiB->PsiFactor);
2673 MPI_Allreduce ( &tmp, &TMP, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi);
2674 //fprintf(stderr,"(%i) Setting Overlap [%i][%i] = %lg\n",P->Par.me, ActNum,m,TMP);
2675 Psi->Overlap[ActNum][m] = TMP; //= Psi->Overlap[m][ActNum]
2676 }
2677 }
2678
2679 // exchange newly calculated rows among PsiT
2680 p_num = (m+1) + 1; // number of Psis: one more due to ActNum
2681 sendbuf = (double *) Malloc(p_num * sizeof(double), "CalculateOverlap: sendbuf");
2682 sendbuf[0] = ActNum; // first entry is the global row number
2683 for (i=1;i<p_num;i++)
2684 sendbuf[i] = Psi->Overlap[ActNum][i-1]; // then follow up each entry of overlap row
2685 recvbuf = (double *) Malloc(gsize * p_num * sizeof(double), "CalculateOverlap: recvbuf");
2686 MPI_Allgather(sendbuf, p_num, MPI_DOUBLE, recvbuf, p_num, MPI_DOUBLE, P->Par.comm_ST_PsiT);
2687 Free(sendbuf, "bla");
2688 for (i=0;i<gsize;i++) {// extract results from other processes out of receiving buffer
2689 m = recvbuf[i*p_num]; // m is ActNum of the process whose results we've just received
2690 //fprintf(stderr,"(%i) Received row %i from process %i\n", P->Par.me, m, i);
2691 for (j=1;j<p_num;j++)
2692 Psi->Overlap[m][j-1] = Psi->Overlap[j-1][m] = recvbuf[i*p_num+j]; // put each entry into correspondent Overlap row
2693 }
2694 Free(recvbuf, "bla");
2695}
2696
2697
2698/** Calculates magnetic susceptibility from known current density.
2699 * The bulk susceptibility tensor can be expressed as a function of the current density.
2700 * \f[
2701 * \chi_{ij} = \frac{\mu_0}{2\Omega} \frac{\delta}{\delta B_i^{ext}} \int_\Omega d^3 r \left (r \times j(r) \right )_j
2702 * \f]
2703 * Thus the integral over real space and subsequent MPI_Allreduce() over results from ParallelSimulationData#comm_ST_Psi is
2704 * straightforward. Tensor is diagonalized afterwards and split into its various sub-tensors of lower rank (e.g., isometric
2705 * value is tensor of rank 0) which are printed to screen and the tensorial elements to file '....chi.csv'
2706 * \param *P Problem at hand
2707 */
2708void CalculateMagneticSusceptibility(struct Problem *P)
2709{
2710 struct RunStruct *R = &P->R;
2711 struct Lattice *Lat = &P->Lat;
2712 struct LatticeLevel *Lev0 = R->Lev0;
2713 struct Density *Dens0 = R->Lev0->Dens;
2714 struct Ions *I = &P->Ion;
2715 fftw_real *CurrentDensity[NDIM*NDIM];
2716 int in, dex, i, i0, n0;
2717 int n[NDIM];
2718 const int N0 = Lev0->Plan0.plan->local_nx;
2719 int N[NDIM];
2720 N[0] = Lev0->Plan0.plan->N[0];
2721 N[1] = Lev0->Plan0.plan->N[1];
2722 N[2] = Lev0->Plan0.plan->N[2];
2723 double chi[NDIM*NDIM],Chi[NDIM*NDIM], x[NDIM], fac[NDIM];
2724 const double discrete_factor = Lat->Volume/Lev0->MaxN;
2725 const int myPE = P->Par.me_comm_ST_Psi;
2726 double eta, delta_chi, S, A, iso;
2727 int cross_lookup[4];
2728 char filename[256];
2729 FILE *ChiFile;
2730 time_t seconds;
2731 time(&seconds); // get current time
2732
2733 // set pointers onto current density
2734 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
2735 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
2736 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
2737 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
2738 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
2739 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
2740 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
2741 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
2742 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
2743 //for(i=0;i<NDIM;i++) {
2744// field[i] = Dens0->DensityArray[TempDensity+i];
2745 //LockDensityArray(Dens0,TempDensity+i,real);
2746// SetArrayToDouble0((double *)field[i],Dens0->TotalSize*2);
2747 //}
2748 gsl_matrix_complex *H = gsl_matrix_complex_calloc(NDIM,NDIM);
2749
2750
2751 if (P->Call.out[ValueOut]) fprintf(stderr,"(%i) magnetic susceptibility tensor \\Chi_ij = \n",P->Par.me);
2752 for (in=0; in<NDIM; in++) { // index i of integrand vector component
2753 for(dex=0;dex<4;dex++) // initialise cross lookup
2754 cross_lookup[dex] = cross(in,dex);
2755 for (dex=0; dex<NDIM; dex++) { // index j of derivation wrt B field
2756 chi[in+dex*NDIM] = 0.;
2757 // do the integration over real space
2758 for(n0=0;n0<N0;n0++)
2759 for(n[1]=0;n[1]<N[1];n[1]++)
2760 for(n[2]=0;n[2]<N[2];n[2]++) {
2761 n[0]=n0 + N0*myPE; // global relative coordinate: due to partitoning of x-axis in PEPGamma>1 case
2762 fac[0] = (double)(n[0])/(double)N[0];
2763 fac[1] = (double)(n[1])/(double)N[1];
2764 fac[2] = (double)(n[2])/(double)N[2];
2765 RMat33Vec3(x, Lat->RealBasis, fac);
2766 i0 = n[2]+N[2]*(n[1]+N[1]*(n0)); // the index of current density must match LocalSizeR!
2767 chi[in+dex*NDIM] += MinImageConv(Lat,x[cross_lookup[0]], sqrt(Lat->RealBasisSQ[cross_lookup[0]])/2.,cross_lookup[0]) * CurrentDensity[dex*NDIM+cross_lookup[1]][i0]; // x[cross(in,0)], sqrt(Lat->RealBasisSQ[cross_lookup[0]])/2.
2768 chi[in+dex*NDIM] -= MinImageConv(Lat,x[cross_lookup[2]], sqrt(Lat->RealBasisSQ[cross_lookup[2]])/2.,cross_lookup[2]) * CurrentDensity[dex*NDIM+cross_lookup[3]][i0]; // x[cross(in,2)], sqrt(Lat->RealBasisSQ[cross_lookup[2]])/2.
2769// if (in == dex) field[in][i0] =
2770// truedist(Lat,x[cross_lookup[0]], sqrt(Lat->RealBasisSQ[c[0]])/2.,cross_lookup[0]) * CurrentDensity[dex*NDIM+cross_lookup[1]][i0]
2771// - truedist(Lat,x[cross_lookup[2]], sqrt(Lat->RealBasisSQ[c[2]])/2.,cross_lookup[2]) * CurrentDensity[dex*NDIM+cross_lookup[3]][i0];
2772 //fprintf(stderr,"(%i) temporary susceptiblity \\chi[%i][%i] += %e * %e = r[%i] * CurrDens[%i][%i] = %e\n",P->Par.me,in,dex,(double)n[cross_lookup[0]]/(double)N[cross_lookup[0]]*(sqrt(Lat->RealBasisSQ[cross_lookup[0]])),CurrentDensity[dex*NDIM+cross_lookup[1]][i0],cross_lookup[0],dex*NDIM+cross_lookup[1],i0,chi[in*NDIM+dex]);
2773 }
2774 chi[in+dex*NDIM] *= mu0*discrete_factor/(2.*Lat->Volume); // integral factor
2775 chi[in+dex*NDIM] *= (-1625.); // empirical gauge factor ... sigh
2776 MPI_Allreduce ( &chi[in+dex*NDIM], &Chi[in+dex*NDIM], 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum "LocalSize to TotalSize"
2777 I->I[0].chi[in+dex*NDIM] = Chi[in+dex*NDIM];
2778 Chi[in+dex*NDIM] *= Lat->Volume*loschmidt_constant; // factor for _molar_ susceptibility
2779 if (P->Call.out[ValueOut]) {
2780 fprintf(stderr,"%e\t", Chi[in+dex*NDIM]);
2781 if (dex == NDIM-1) fprintf(stderr,"\n");
2782 }
2783 }
2784 }
2785 // store symmetrized matrix
2786 for (in=0;in<NDIM;in++)
2787 for (dex=0;dex<NDIM;dex++)
2788 gsl_matrix_complex_set(H,in,dex,gsl_complex_rect((Chi[in+dex*NDIM]+Chi[dex+in*NDIM])/2.,0));
2789 // output tensor to file
2790 if (P->Par.me == 0) {
2791 sprintf(filename, ".chi.L%i.csv", Lev0->LevelNo);
2792 OpenFile(P, &ChiFile, filename, "a", P->Call.out[ReadOut]);
2793 fprintf(ChiFile,"# magnetic susceptibility tensor chi[01,02,03,10,11,12,20,21,22], seed %i, config %s, run on %s", R->Seed, P->Files.default_path, ctime(&seconds));
2794 fprintf(ChiFile,"%lg\t", P->Lat.ECut/(Lat->LevelSizes[0]*Lat->LevelSizes[0]));
2795 for (in=0;in<NDIM*NDIM;in++)
2796 fprintf(ChiFile,"%e\t", Chi[in]);
2797 fprintf(ChiFile,"\n");
2798 fclose(ChiFile);
2799 }
2800 // diagonalize chi
2801 gsl_vector *eval = gsl_vector_alloc(NDIM);
2802 gsl_eigen_herm_workspace *w = gsl_eigen_herm_alloc(NDIM);
2803 gsl_eigen_herm(H, eval, w);
2804 gsl_eigen_herm_free(w);
2805 gsl_sort_vector(eval); // sort eigenvalues
2806 // print eigenvalues
2807 iso = 0;
2808 for (i=0;i<NDIM;i++) {
2809 I->I[0].chi_PAS[i] = gsl_vector_get(eval,i);
2810 iso += Chi[i+i*NDIM]/3.;
2811 }
2812 eta = (gsl_vector_get(eval,1)-gsl_vector_get(eval,0))/(gsl_vector_get(eval,2)-iso);
2813 delta_chi = gsl_vector_get(eval,2) - 0.5*(gsl_vector_get(eval,0)+gsl_vector_get(eval,1));
2814 S = (delta_chi*delta_chi)*(1+1./3.*eta*eta);
2815 A = 0.;
2816 for (i=0;i<NDIM;i++) {
2817 in = cross(i,0);
2818 dex = cross(i,1);
2819 A += pow(-1,i)*pow(0.5*(Chi[in+dex*NDIM]-Chi[dex+in*NDIM]),2);
2820 }
2821 if (P->Call.out[ValueOut]) {
2822 fprintf(stderr,"(%i) converted to Principal Axis System\n==================\nDiagonal entries:", P->Par.me);
2823 for (i=0;i<NDIM;i++)
2824 fprintf(stderr,"\t%lg",gsl_vector_get(eval,i));
2825 fprintf(stderr,"\nsusceptib. : %e\n", iso);
2826 fprintf(stderr,"anisotropy : %e\n", delta_chi);
2827 fprintf(stderr,"asymmetry : %e\n", eta);
2828 fprintf(stderr,"S : %e\n", S);
2829 fprintf(stderr,"A : %e\n", A);
2830 fprintf(stderr,"==================\n");
2831 }
2832 //for(i=0;i<NDIM;i++)
2833 //UnLockDensityArray(Dens0,TempDensity+i,real);
2834 gsl_vector_free(eval);
2835 gsl_matrix_complex_free(H);
2836}
2837
2838/** Fouriertransforms all nine current density components and calculates shielding tensor.
2839 * \f[
2840 * \sigma_{ij} = \left ( \frac{G}{|G|^2} \times J_i(G) \right )_j
2841 * \f]
2842 * The CurrentDensity has to be fouriertransformed to reciprocal subspace in order to be useful, and the final
2843 * product \f$\sigma_{ij}(G)\f$ has to be back-transformed to real space. However, the shielding is the only evaluated
2844 * at the grid points and not where the real ion position is. The shieldings there are interpolated between the eight
2845 * adjacent grid points by a simple linear weighting. Afterwards follows the same analaysis and printout of the rank-2-tensor
2846 * as in the case of CalculateMagneticShielding().
2847 * \param *P Problem at hand
2848 * \note Lots of arrays are used temporarily during the routine for the fft'ed Current density tensor.
2849 * \note MagneticSusceptibility is needed for G=0-component and thus has to be computed beforehand
2850 */
2851void CalculateChemicalShieldingByReciprocalCurrentDensity(struct Problem *P)
2852{
2853 struct RunStruct *R = &P->R;
2854 struct Lattice *Lat = &P->Lat;
2855 struct LatticeLevel *Lev0 = R->Lev0;
2856 struct Ions *I = &P->Ion;
2857 struct Density *Dens0 = Lev0->Dens;
2858 struct OneGData *GArray = Lev0->GArray;
2859 struct fft_plan_3d *plan = Lat->plan;
2860 fftw_real *CurrentDensity[NDIM*NDIM];
2861 fftw_complex *CurrentDensityC[NDIM*NDIM];
2862 fftw_complex *work = (fftw_complex *)Dens0->DensityCArray[TempDensity];
2863 //fftw_complex *sigma_imag = (fftw_complex *)Dens0->DensityCArray[Temp2Density];
2864 //fftw_real *sigma_real = (fftw_real *)sigma_imag;
2865 fftw_complex *sigma_imag[NDIM_NDIM];
2866 fftw_real *sigma_real[NDIM_NDIM];
2867 double sigma,Sigma;
2868 int it, ion, in, dex, g, n[2][NDIM], Index, i;
2869 //const double FFTfactor = 1.;///Lev0->MaxN;
2870 double eta, delta_sigma, S, A, iso, tmp;
2871 FILE *SigmaFile;
2872 char suffixsigma[255];
2873 double x[2][NDIM];
2874 const int myPE = P->Par.me_comm_ST_Psi;
2875 int N[NDIM];
2876 int cross_lookup[4]; // cross lookup table
2877 N[0] = Lev0->Plan0.plan->N[0];
2878 N[1] = Lev0->Plan0.plan->N[1];
2879 N[2] = Lev0->Plan0.plan->N[2];
2880 const int N0 = Lev0->Plan0.plan->local_nx;
2881 const double factorDC = R->FactorDensityC;
2882 gsl_matrix_complex *H = gsl_matrix_complex_calloc(NDIM,NDIM);
2883
2884 time_t seconds;
2885 time(&seconds); // get current time
2886
2887 // inverse Fourier transform current densities
2888 CurrentDensityC[0] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity0];
2889 CurrentDensityC[1] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity1];
2890 CurrentDensityC[2] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity2];
2891 CurrentDensityC[3] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity3];
2892 CurrentDensityC[4] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity4];
2893 CurrentDensityC[5] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity5];
2894 CurrentDensityC[6] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity6];
2895 CurrentDensityC[7] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity7];
2896 CurrentDensityC[8] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity8];
2897 // don't put the following stuff into a for loop, they are not continuous! (preprocessor values CurrentDensity.)
2898 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
2899 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
2900 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
2901 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
2902 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
2903 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
2904 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
2905 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
2906 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
2907
2908 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Checking J_{ij} (G=0) = 0 for each i,j ... \n",P->Par.me);
2909 for (in=0;in<NDIM*NDIM;in++) {
2910 CalculateOneDensityC(Lat, R->LevS, Dens0, CurrentDensity[in], CurrentDensityC[in], factorDC);
2911 tmp = sqrt(CurrentDensityC[in][0].re*CurrentDensityC[in][0].re+CurrentDensityC[in][0].im*CurrentDensityC[in][0].im);
2912 if (GArray[0].GSq < MYEPSILON) {
2913 if (in % NDIM == 0) fprintf(stderr,"(%i) ",P->Par.me);
2914 if (tmp > MYEPSILON) {
2915 fprintf(stderr,"J_{%i,%i} = |%e + i%e| < %e ? (%e)\t", in / NDIM, in%NDIM, CurrentDensityC[in][0].re, CurrentDensityC[in][0].im, MYEPSILON, tmp - MYEPSILON);
2916 } else {
2917 fprintf(stderr,"J_{%i,%i} ok\t", in / NDIM, in%NDIM);
2918 }
2919 if (in % NDIM == (NDIM-1)) fprintf(stderr,"\n");
2920 }
2921 }
2922
2923 for (in=0;in<NDIM*NDIM;in++) {
2924 LockDensityArray(Dens0,in,real); // Psi1R
2925 sigma_imag[in] = (fftw_complex *) Dens0->DensityArray[in];
2926 sigma_real[in] = (fftw_real *) sigma_imag[in];
2927 }
2928
2929 LockDensityArray(Dens0,TempDensity,imag); // work
2930 LockDensityArray(Dens0,Temp2Density,imag); // tempdestRC and field
2931 // go through reciprocal nodes and calculate shielding tensor sigma
2932 for (in=0; in<NDIM; in++) {// index i of vector component in integrand
2933 for(dex=0;dex<4;dex++) // initialise cross lookup
2934 cross_lookup[dex] = cross(in,dex);
2935 for (dex=0; dex<NDIM; dex++) { // index j of B component derivation in current density tensor
2936 //if (tempdestRC != (fftw_complex *)Dens0->DensityCArray[Temp2Density]) Error(SomeError,"CalculateChemicalShieldingByReciprocalCurrentDensity: tempdestRC corrupted");
2937 SetArrayToDouble0((double *)sigma_imag[in+dex*NDIM],Dens0->TotalSize*2);
2938 for (g=0; g < Lev0->MaxG; g++)
2939 if (GArray[g].GSq > MYEPSILON) { // skip due to divisor
2940 Index = GArray[g].Index; // re = im, im = -re due to "i" in formula
2941 //if (tempdestRC != (fftw_complex *)Dens0->DensityCArray[Temp2Density] || Index<0 || Index>=Dens0->LocalSizeC) Error(SomeError,"CalculateChemicalShieldingByReciprocalCurrentDensity: tempdestRC corrupted");
2942 sigma_imag[in+dex*NDIM][Index].re = GArray[g].G[cross_lookup[0]] * (-CurrentDensityC[dex*NDIM+cross_lookup[1]][Index].im)/GArray[g].GSq;//*FFTfactor;
2943 sigma_imag[in+dex*NDIM][Index].re -= GArray[g].G[cross_lookup[2]] * (-CurrentDensityC[dex*NDIM+cross_lookup[3]][Index].im)/GArray[g].GSq;//*FFTfactor;
2944 sigma_imag[in+dex*NDIM][Index].im = GArray[g].G[cross_lookup[0]] * ( CurrentDensityC[dex*NDIM+cross_lookup[1]][Index].re)/GArray[g].GSq;//*FFTfactor;
2945 sigma_imag[in+dex*NDIM][Index].im -= GArray[g].G[cross_lookup[2]] * ( CurrentDensityC[dex*NDIM+cross_lookup[3]][Index].re)/GArray[g].GSq;//*FFTfactor;
2946 } else { // G=0-component stems from magnetic susceptibility
2947 sigma_imag[in+dex*NDIM][GArray[g].Index].re = 2./3.*I->I[0].chi[in+dex*NDIM];//-4.*M_PI*(0.5*I->I[0].chi[0+0*NDIM]+0.5*I->I[0].chi[1+1*NDIM]+2./3.*I->I[0].chi[2+2*NDIM]);
2948 }
2949 for (g=0; g<Lev0->MaxDoubleG; g++) { // apply symmetry
2950 //if (tempdestRC != (fftw_complex *)Dens0->DensityCArray[Temp2Density] || Lev0->DoubleG[2*g+1]<0 || Lev0->DoubleG[2*g+1]>=Dens0->LocalSizeC) Error(SomeError,"CalculateChemicalShieldingByReciprocalCurrentDensity: tempdestRC corrupted");
2951 sigma_imag[in+dex*NDIM][Lev0->DoubleG[2*g+1]].re = sigma_imag[in+dex*NDIM][Lev0->DoubleG[2*g]].re;
2952 sigma_imag[in+dex*NDIM][Lev0->DoubleG[2*g+1]].im = -sigma_imag[in+dex*NDIM][Lev0->DoubleG[2*g]].im;
2953 }
2954 // fourier transformation of sigma
2955 //if (tempdestRC != (fftw_complex *)Dens0->DensityCArray[Temp2Density]) Error(SomeError,"CalculateChemicalShieldingByReciprocalCurrentDensity: tempdestRC corrupted");
2956 fft_3d_complex_to_real(plan, Lev0->LevelNo, FFTNF1, sigma_imag[in+dex*NDIM], work);
2957
2958 for (it=0; it < I->Max_Types; it++) { // integration over all types
2959 for (ion=0; ion < I->I[it].Max_IonsOfType; ion++) { // and each ion of type
2960 // read transformed sigma at core position and MPI_Allreduce
2961 for (g=0;g<NDIM;g++) {
2962 n[0][g] = floor(I->I[it].R[NDIM*ion+g]/sqrt(Lat->RealBasisSQ[g])*(double)N[g]);
2963 n[1][g] = ceil(I->I[it].R[NDIM*ion+g]/sqrt(Lat->RealBasisSQ[g])*(double)N[g]);
2964 x[1][g] = I->I[it].R[NDIM*ion+g]/sqrt(Lat->RealBasisSQ[g])*(double)N[g] - (double)n[0][g];
2965 x[0][g] = 1. - x[1][g];
2966 //fprintf(stderr,"(%i) n_floor[%i] = %i\tn_ceil[%i] = %i --- x_floor[%i] = %e\tx_ceil[%i] = %e\n",P->Par.me, g,n[0][g], g,n[1][g], g,x[0][g], g,x[1][g]);
2967 }
2968 sigma = 0.;
2969 for (i=0;i<2;i++) { // interpolate linearly between adjacent grid points per axis
2970 if ((n[i][0] >= N0*myPE) && (n[i][0] < N0*(myPE+1))) {
2971// fprintf(stderr,"(%i) field[%i]: sigma = %e\n", P->Par.me, n[i][2]+N[2]*(n[i][1]+N[1]*(n[i][0]-N0*myPE)), sigma);
2972 sigma += (x[i][0]*x[0][1]*x[0][2])*sigma_real[in+dex*NDIM][n[0][2]+N[2]*(n[0][1]+N[1]*(n[i][0]-N0*myPE))]*mu0; // if it's local and factor from inverse fft
2973 //fprintf(stderr,"(%i) field[%i]: sigma += %e * %e \n", P->Par.me, n[i][2]+N[2]*(n[i][1]+N[1]*(n[i][0]-N0*myPE)), (x[i][0]*x[0][1]*x[0][2]), field[n[0][2]+N[2]*(n[0][1]+N[1]*(n[i][0]-N0*myPE))]*mu0);
2974 sigma += (x[i][0]*x[0][1]*x[1][2])*sigma_real[in+dex*NDIM][n[1][2]+N[2]*(n[0][1]+N[1]*(n[i][0]-N0*myPE))]*mu0; // if it's local and factor from inverse fft
2975 //fprintf(stderr,"(%i) field[%i]: sigma += %e * %e \n", P->Par.me, n[i][2]+N[2]*(n[i][1]+N[1]*(n[i][0]-N0*myPE)), (x[i][0]*x[0][1]*x[1][2]), field[n[1][2]+N[2]*(n[0][1]+N[1]*(n[i][0]-N0*myPE))]*mu0);
2976 sigma += (x[i][0]*x[1][1]*x[0][2])*sigma_real[in+dex*NDIM][n[0][2]+N[2]*(n[1][1]+N[1]*(n[i][0]-N0*myPE))]*mu0; // if it's local and factor from inverse fft
2977 //fprintf(stderr,"(%i) field[%i]: sigma += %e * %e \n", P->Par.me, n[i][2]+N[2]*(n[i][1]+N[1]*(n[i][0]-N0*myPE)), (x[i][0]*x[1][1]*x[0][2]), field[n[0][2]+N[2]*(n[1][1]+N[1]*(n[i][0]-N0*myPE))]*mu0);
2978 sigma += (x[i][0]*x[1][1]*x[1][2])*sigma_real[in+dex*NDIM][n[1][2]+N[2]*(n[1][1]+N[1]*(n[i][0]-N0*myPE))]*mu0; // if it's local and factor from inverse fft
2979 //fprintf(stderr,"(%i) field[%i]: sigma += %e * %e \n", P->Par.me, n[i][2]+N[2]*(n[i][1]+N[1]*(n[i][0]-N0*myPE)), (x[i][0]*x[1][1]*x[1][2]), field[n[1][2]+N[2]*(n[1][1]+N[1]*(n[i][0]-N0*myPE))]*mu0);
2980 }
2981 }
2982 sigma *= -R->FactorDensityR; // factor from inverse fft? (and its defined as negative proportionaly factor)
2983 MPI_Allreduce ( &sigma, &Sigma, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum local to total
2984 I->I[it].sigma_rezi[ion][in+dex*NDIM] = Sigma;
2985 }
2986 }
2987 // fabs() all sigma values, as we need them as a positive density: OutputVis plots them in logarithmic scale and
2988 // thus cannot deal with negative values!
2989 for (i=0; i< Dens0->LocalSizeR; i++)
2990 sigma_real[in+dex*NDIM][i] = fabs(sigma_real[in+dex*NDIM][i]);
2991 }
2992 }
2993 UnLockDensityArray(Dens0,TempDensity,imag); // work
2994 UnLockDensityArray(Dens0,Temp2Density,imag); // tempdestRC and field
2995
2996 // output tensor to file
2997 if (P->Par.me == 0) {
2998 sprintf(&suffixsigma[0], ".sigma_chi_rezi.L%i.csv", Lev0->LevelNo);
2999 OpenFile(P, &SigmaFile, suffixsigma, "a", P->Call.out[ReadOut]);
3000 fprintf(SigmaFile,"# chemical shielding tensor sigma_rezi[01,02,03,10,11,12,20,21,22], seed %i, config %s, run on %s", R->Seed, P->Files.default_path, ctime(&seconds));
3001 fprintf(SigmaFile,"%lg\t", P->Lat.ECut/(Lat->LevelSizes[0]*Lat->LevelSizes[0]));
3002 for (in=0;in<NDIM;in++)
3003 for (dex=0;dex<NDIM;dex++)
3004 fprintf(SigmaFile,"%e\t", GSL_REAL(gsl_matrix_complex_get(H,in,dex)));
3005 fprintf(SigmaFile,"\n");
3006 fclose(SigmaFile);
3007 }
3008
3009 gsl_vector *eval = gsl_vector_alloc(NDIM);
3010 gsl_eigen_herm_workspace *w = gsl_eigen_herm_alloc(NDIM);
3011
3012 for (it=0; it < I->Max_Types; it++) { // integration over all types
3013 for (ion=0; ion < I->I[it].Max_IonsOfType; ion++) { // and each ion of type
3014 if (P->Call.out[ValueOut]) fprintf(stderr,"(%i) Shielding Tensor for Ion %i of element %s \\sigma_ij = \n",P->Par.me, ion, I->I[it].Name);
3015 for (in=0; in<NDIM; in++) { // index i of vector component in integrand
3016 for (dex=0; dex<NDIM; dex++) {// index j of B component derivation in current density tensor
3017 gsl_matrix_complex_set(H,in,dex,gsl_complex_rect((I->I[it].sigma_rezi[ion][in+dex*NDIM]+I->I[it].sigma_rezi[ion][dex+in*NDIM])/2.,0));
3018 if (P->Call.out[ValueOut]) fprintf(stderr,"%e\t", I->I[it].sigma_rezi[ion][in+dex*NDIM]);
3019 }
3020 if (P->Call.out[ValueOut]) fprintf(stderr,"\n");
3021 }
3022 // output tensor to file
3023 if (P->Par.me == 0) {
3024 sprintf(&suffixsigma[0], ".sigma_i%i_%s_rezi.L%i.csv", ion, I->I[it].Symbol, Lev0->LevelNo);
3025 OpenFile(P, &SigmaFile, suffixsigma, "a", P->Call.out[ReadOut]);
3026 fprintf(SigmaFile,"# chemical shielding tensor sigma_rezi[01,02,03,10,11,12,20,21,22], seed %i, config %s, run on %s", R->Seed, P->Files.default_path, ctime(&seconds));
3027 fprintf(SigmaFile,"%lg\t", P->Lat.ECut/(Lat->LevelSizes[0]*Lat->LevelSizes[0]));
3028 for (in=0;in<NDIM;in++)
3029 for (dex=0;dex<NDIM;dex++)
3030 fprintf(SigmaFile,"%e\t", I->I[it].sigma_rezi[ion][in+dex*NDIM]);
3031 fprintf(SigmaFile,"\n");
3032 fclose(SigmaFile);
3033 }
3034 // diagonalize sigma
3035 gsl_eigen_herm(H, eval, w);
3036 gsl_sort_vector(eval); // sort eigenvalues
3037// print eigenvalues
3038// if (P->Call.out[ValueOut]) {
3039// fprintf(stderr,"(%i) diagonal shielding for Ion %i of element %s:", P->Par.me, ion, I->I[it].Name);
3040// for (in=0;in<NDIM;in++)
3041// fprintf(stderr,"\t%lg",gsl_vector_get(eval,in));
3042// fprintf(stderr,"\n\n");
3043// }
3044 iso = 0.;
3045 for (i=0;i<NDIM;i++) {
3046 I->I[it].sigma_rezi_PAS[ion][i] = gsl_vector_get(eval,i);
3047 iso += I->I[it].sigma_rezi[ion][i+i*NDIM]/3.;
3048 }
3049 eta = (gsl_vector_get(eval,1)-gsl_vector_get(eval,0))/(gsl_vector_get(eval,2)-iso);
3050 delta_sigma = gsl_vector_get(eval,2) - 0.5*(gsl_vector_get(eval,0)+gsl_vector_get(eval,1));
3051 S = (delta_sigma*delta_sigma)*(1+1./3.*eta*eta);
3052 A = 0.;
3053 for (i=0;i<NDIM;i++) {
3054 in = cross(i,0);
3055 dex = cross(i,1);
3056 A += pow(-1,i)*pow(0.5*(I->I[it].sigma_rezi[ion][in+dex*NDIM]-I->I[it].sigma_rezi[ion][dex+in*NDIM]),2);
3057 }
3058 if (P->Call.out[ValueOut]) {
3059 fprintf(stderr,"(%i) converted to Principal Axis System\n==================\nDiagonal entries:", P->Par.me);
3060 for (i=0;i<NDIM;i++)
3061 fprintf(stderr,"\t%lg",gsl_vector_get(eval,i));
3062 fprintf(stderr,"\nshielding : %e\n", iso);
3063 fprintf(stderr,"anisotropy : %e\n", delta_sigma);
3064 fprintf(stderr,"asymmetry : %e\n", eta);
3065 fprintf(stderr,"S : %e\n", S);
3066 fprintf(stderr,"A : %e\n", A);
3067 fprintf(stderr,"==================\n");
3068
3069 }
3070 }
3071 }
3072
3073 // Output of magnetic field densities for each direction
3074 for (i=0;i<NDIM*NDIM;i++)
3075 OutputVis(P, sigma_real[i]);
3076 // Diagonalizing the tensor "field" B_ij [r]
3077 fprintf(stderr,"(%i) Diagonalizing B_ij [r] ... \n", P->Par.me);
3078 for (i=0; i< Dens0->LocalSizeR; i++) {
3079 for (in=0; in<NDIM; in++) // index i of vector component in integrand
3080 for (dex=0; dex<NDIM; dex++) { // index j of B component derivation in current density tensor
3081 //fprintf(stderr,"(%i) Setting B_(%i,%i)[%i] ... \n", P->Par.me, in,dex,i);
3082 gsl_matrix_complex_set(H,in,dex,gsl_complex_rect((sigma_real[in+dex*NDIM][i]+sigma_real[dex+in*NDIM][i])/2.,0));
3083 }
3084 gsl_eigen_herm(H, eval, w);
3085 gsl_sort_vector(eval); // sort eigenvalues
3086 for (in=0;in<NDIM;in++)
3087 sigma_real[in][i] = gsl_vector_get(eval,in);
3088 }
3089 // Output of diagonalized magnetic field densities for each direction
3090 for (i=0;i<NDIM;i++)
3091 OutputVis(P, sigma_real[i]);
3092 for (i=0;i<NDIM*NDIM;i++)
3093 UnLockDensityArray(Dens0,i,real); // sigma_imag/real free
3094
3095 gsl_eigen_herm_free(w);
3096 gsl_vector_free(eval);
3097 gsl_matrix_complex_free(H);
3098}
3099
3100
3101/** Calculates the chemical shielding tensor at the positions of the nuclei.
3102 * The chemical shielding tensor at position R is defined as the proportionality factor between the induced and
3103 * the externally applied field.
3104 * \f[
3105 * \sigma_{ij} (R) = \frac{\delta B_j^{ind} (R)}{\delta B_i^{ext}}
3106 * = \frac{\mu_0}{4 \pi} \int d^3 r' \left ( \frac{r'-r}{| r' - r |^3} \times J_i (r') \right )_j
3107 * \f]
3108 * One after another for each nuclear position is the tensor evaluated and the result printed
3109 * to screen. Tensor is diagonalized afterwards.
3110 * \param *P Problem at hand
3111 * \sa CalculateMagneticSusceptibility() - similar calculation, yet without translation to ion centers.
3112 * \warning This routine is out-dated due to being numerically unstable because of the singularity which is not
3113 * considered carefully, recommendend replacement is CalculateChemicalShieldingByReciprocalCurrentDensity().
3114 */
3115void CalculateChemicalShielding(struct Problem *P)
3116{
3117 struct RunStruct *R = &P->R;
3118 struct Lattice *Lat = &P->Lat;
3119 struct LatticeLevel *Lev0 = R->Lev0;
3120 struct Density *Dens0 = R->Lev0->Dens;
3121 struct Ions *I = &P->Ion;
3122 double sigma[NDIM*NDIM],Sigma[NDIM*NDIM];
3123 fftw_real *CurrentDensity[NDIM*NDIM];
3124 int it, ion, in, dex, i0, n[NDIM], n0, i;//, *NUp;
3125 double x,y,z;
3126 double dist;
3127 double r[NDIM], fac[NDIM];
3128 const double discrete_factor = Lat->Volume/Lev0->MaxN;
3129 double eta, delta_sigma, S, A, iso;
3130 const int myPE = P->Par.me_comm_ST_Psi;
3131 int N[NDIM];
3132 N[0] = Lev0->Plan0.plan->N[0];
3133 N[1] = Lev0->Plan0.plan->N[1];
3134 N[2] = Lev0->Plan0.plan->N[2];
3135 const int N0 = Lev0->Plan0.plan->local_nx;
3136 FILE *SigmaFile;
3137 char suffixsigma[255];
3138 time_t seconds;
3139 time(&seconds); // get current time
3140
3141 // set pointers onto current density
3142 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
3143 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
3144 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
3145 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
3146 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
3147 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
3148 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
3149 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
3150 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
3151 gsl_matrix_complex *H = gsl_matrix_complex_calloc(NDIM,NDIM);
3152
3153 for (it=0; it < I->Max_Types; it++) { // integration over all types
3154 for (ion=0; ion < I->I[it].Max_IonsOfType; ion++) { // and each ion of type
3155 if (P->Call.out[ValueOut]) fprintf(stderr,"(%i) Shielding Tensor for Ion %i of element %s \\sigma_ij = \n",P->Par.me, ion, I->I[it].Name);
3156 for (in=0; in<NDIM; in++) {// index i of vector component in integrand
3157 for (dex=0; dex<NDIM; dex++) { // index j of B component derivation in current density tensor
3158 sigma[in+dex*NDIM] = 0.;
3159
3160 for(n0=0;n0<N0;n0++) // do the integration over real space
3161 for(n[1]=0;n[1]<N[1];n[1]++)
3162 for(n[2]=0;n[2]<N[2];n[2]++) {
3163 n[0]=n0 + N0*myPE; // global relative coordinate: due to partitoning of x-axis in PEPGamma>1 case
3164 fac[0] = (double)n[0]/(double)N[0];
3165 fac[1] = (double)n[1]/(double)N[1];
3166 fac[2] = (double)n[2]/(double)N[2];
3167 RMat33Vec3(r, Lat->RealBasis, fac);
3168 i0 = n[2]+N[2]*(n[1]+N[1]*(n0)); // the index of current density must match LocalSizeR!
3169 x = MinImageConv(Lat,r[cross(in,0)], I->I[it].R[NDIM*ion+cross(in,0)],cross(in,0));
3170 y = MinImageConv(Lat,r[cross(in,2)], I->I[it].R[NDIM*ion+cross(in,2)],cross(in,2));
3171 z = MinImageConv(Lat,r[in], I->I[it].R[NDIM*ion+in],in); // "in" always is missing third component in cross product
3172 dist = pow(x*x + y*y + z*z, 3./2.);
3173 if ((dist < pow(2.,3.)) && (dist > MYEPSILON)) sigma[in+dex*NDIM] += (x * CurrentDensity[dex*NDIM+cross(in,1)][i0] - y * CurrentDensity[dex*NDIM+cross(in,3)][i0])/dist;
3174 //if (it == 0 && ion == 0) fprintf(stderr,"(%i) sigma[%i][%i] += (%e * %e - %e * %e)/%e = %e\n", P->Par.me, in, dex, x,CurrentDensity[dex*NDIM+cross(in,1)][i0],y,CurrentDensity[dex*NDIM+cross(in,3)][i0],dist,sigma[in+dex*NDIM]);
3175 }
3176 sigma[in+dex*NDIM] *= -mu0*discrete_factor/(4.*PI); // due to summation instead of integration
3177 MPI_Allreduce ( &sigma[in+dex*NDIM], &Sigma[in+dex*NDIM], 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum "LocalSize to TotalSize"
3178 I->I[it].sigma[ion][in+dex*NDIM] = Sigma[in+dex*NDIM];
3179 if (P->Call.out[ValueOut]) fprintf(stderr," %e", Sigma[in+dex*NDIM]);
3180 }
3181 if (P->Call.out[ValueOut]) fprintf(stderr,"\n");
3182 }
3183 // store symmetrized matrix
3184 for (in=0;in<NDIM;in++)
3185 for (dex=0;dex<NDIM;dex++)
3186 gsl_matrix_complex_set(H,in,dex,gsl_complex_rect((Sigma[in+dex*NDIM]+Sigma[dex+in*NDIM])/2.,0));
3187 // output tensor to file
3188 if (P->Par.me == 0) {
3189 sprintf(&suffixsigma[0], ".sigma_i%i_%s.L%i.csv", ion, I->I[it].Symbol, Lev0->LevelNo);
3190 OpenFile(P, &SigmaFile, suffixsigma, "a", P->Call.out[ReadOut]);
3191 fprintf(SigmaFile,"# chemical shielding tensor sigma[01,02,03,10,11,12,20,21,22], seed %i, config %s, run on %s", R->Seed, P->Files.default_path, ctime(&seconds));
3192 fprintf(SigmaFile,"%lg\t", P->Lat.ECut/(Lat->LevelSizes[0]*Lat->LevelSizes[0]));
3193 for (in=0;in<NDIM*NDIM;in++)
3194 fprintf(SigmaFile,"%e\t", Sigma[in]);
3195 fprintf(SigmaFile,"\n");
3196 fclose(SigmaFile);
3197 }
3198 // diagonalize sigma
3199 gsl_vector *eval = gsl_vector_alloc(NDIM);
3200 gsl_eigen_herm_workspace *w = gsl_eigen_herm_alloc(NDIM);
3201 gsl_eigen_herm(H, eval, w);
3202 gsl_eigen_herm_free(w);
3203 gsl_sort_vector(eval); // sort eigenvalues
3204 // print eigenvalues
3205// if (P->Call.out[ValueOut]) {
3206// fprintf(stderr,"(%i) diagonal shielding for Ion %i of element %s:", P->Par.me, ion, I->I[it].Name);
3207// for (in=0;in<NDIM;in++)
3208// fprintf(stderr,"\t%lg",gsl_vector_get(eval,in));
3209// fprintf(stderr,"\n\n");
3210// }
3211 // print eigenvalues
3212 iso = 0;
3213 for (i=0;i<NDIM;i++) {
3214 I->I[it].sigma[ion][i] = gsl_vector_get(eval,i);
3215 iso += Sigma[i+i*NDIM]/3.;
3216 }
3217 eta = (gsl_vector_get(eval,1)-gsl_vector_get(eval,0))/(gsl_vector_get(eval,2)-iso);
3218 delta_sigma = gsl_vector_get(eval,2) - 0.5*(gsl_vector_get(eval,0)+gsl_vector_get(eval,1));
3219 S = (delta_sigma*delta_sigma)*(1+1./3.*eta*eta);
3220 A = 0.;
3221 for (i=0;i<NDIM;i++) {
3222 in = cross(i,0);
3223 dex = cross(i,1);
3224 A += pow(-1,i)*pow(0.5*(Sigma[in+dex*NDIM]-Sigma[dex+in*NDIM]),2);
3225 }
3226 if (P->Call.out[ValueOut]) {
3227 fprintf(stderr,"(%i) converted to Principal Axis System\n==================\nDiagonal entries:", P->Par.me);
3228 for (i=0;i<NDIM;i++)
3229 fprintf(stderr,"\t%lg",gsl_vector_get(eval,i));
3230 fprintf(stderr,"\nshielding : %e\n", iso);
3231 fprintf(stderr,"anisotropy : %e\n", delta_sigma);
3232 fprintf(stderr,"asymmetry : %e\n", eta);
3233 fprintf(stderr,"S : %e\n", S);
3234 fprintf(stderr,"A : %e\n", A);
3235 fprintf(stderr,"==================\n");
3236
3237 }
3238 gsl_vector_free(eval);
3239 }
3240 }
3241
3242 gsl_matrix_complex_free(H);
3243}
3244
3245/** Test if integrated current over cell is 0.
3246 * In most cases we do not reach a numerical sensible zero as in MYEPSILON and remain satisfied as long
3247 * as the integrated current density is very small (e.g. compared to single entries in the current density array)
3248 * \param *P Problem at hand
3249 * \param index index of current component
3250 * \sa CalculateNativeIntDens() for integration of one current tensor component
3251 */
3252 void TestCurrent(struct Problem *P, const int index)
3253{
3254 struct RunStruct *R = &P->R;
3255 struct LatticeLevel *Lev0 = R->Lev0;
3256 struct Density *Dens0 = Lev0->Dens;
3257 fftw_real *CurrentDensity[NDIM*NDIM];
3258 int in;
3259 double result[NDIM*NDIM], res = 0.;
3260
3261 // set pointers onto current density array and get number of grid points in each direction
3262 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
3263 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
3264 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
3265 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
3266 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
3267 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
3268 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
3269 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
3270 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
3271 for(in=0;in<NDIM;in++) {
3272 result[in] = CalculateNativeIntDens(P,Lev0,CurrentDensity[in + NDIM*index],R->FactorDensityR);
3273 res += pow(result[in],2.);
3274 }
3275 res = sqrt(res);
3276 // if greater than 0, complain about it
3277 if ((res > MYEPSILON) && (P->Call.out[LeaderOut]))
3278 fprintf(stderr, "(%i) \\int_\\Omega d^3 r j_%i(r) = (%e,%e,%e), %e > %e!\n",P->Par.me, index, result[0], result[1], result[2], res, MYEPSILON);
3279}
3280
3281/** Testing whether re<->im switches (due to symmetry) confuses fft.
3282 * \param *P Problem at hand
3283 * \param l local wave function number
3284 */
3285void test_fft_symmetry(struct Problem *P, const int l)
3286{
3287 struct Lattice *Lat = &P->Lat;
3288 struct RunStruct *R = &P->R;
3289 struct LatticeLevel *LevS = R->LevS;
3290 struct LatticeLevel *Lev0 = R->Lev0;
3291 struct Density *Dens0 = Lev0->Dens;
3292 struct fft_plan_3d *plan = Lat->plan;
3293 fftw_complex *tempdestRC = (fftw_complex *)Dens0->DensityCArray[Temp2Density];
3294 fftw_complex *work = Dens0->DensityCArray[TempDensity];
3295 fftw_complex *workC = (fftw_complex *)Dens0->DensityArray[TempDensity];
3296 fftw_complex *posfac, *destpos, *destRCS, *destRCD;
3297 fftw_complex *PsiC = Dens0->DensityCArray[ActualPsiDensity];
3298 fftw_real *PsiCR = (fftw_real *) PsiC;
3299 fftw_complex *Psi0 = LevS->LPsi->LocalPsi[l];
3300 fftw_complex *dest = LevS->LPsi->TempPsi;
3301 fftw_real *Psi0R = (fftw_real *)Dens0->DensityArray[Temp2Density];
3302 int i,Index, pos, i0, iS,g; //, NoOfPsis = Psi->TypeStartIndex[UnOccupied] - Psi->TypeStartIndex[Occupied];
3303 int n[NDIM], n0;
3304 const int N0 = LevS->Plan0.plan->local_nx; // we don't want to build global density, but local
3305 int N[NDIM], NUp[NDIM];
3306 N[0] = LevS->Plan0.plan->N[0];
3307 N[1] = LevS->Plan0.plan->N[1];
3308 N[2] = LevS->Plan0.plan->N[2];
3309 NUp[0] = LevS->NUp[0];
3310 NUp[1] = LevS->NUp[1];
3311 NUp[2] = LevS->NUp[2];
3312 //const int k_normal = Lat->Psi.TypeStartIndex[Occupied] + (l - Lat->Psi.TypeStartIndex[R->CurrentMin]);
3313 //const double *Wcentre = Lat->Psi.AddData[k_normal].WannierCentre;
3314 //double x[NDIM], fac[NDIM];
3315 double result1=0., result2=0., result3=0., result4=0.;
3316 double Result1=0., Result2=0., Result3=0., Result4=0.;
3317 const double HGcRCFactor = 1./LevS->MaxN; // factor for inverse fft
3318
3319
3320 // fft to real space
3321 SetArrayToDouble0((double *)tempdestRC, Dens0->TotalSize*2);
3322 SetArrayToDouble0((double *)PsiC, Dens0->TotalSize*2);
3323 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is positive
3324 Index = LevS->GArray[i].Index;
3325 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
3326 destpos = &tempdestRC[LevS->MaxNUp*Index];
3327 for (pos=0; pos < LevS->MaxNUp; pos++) {
3328 destpos[pos].re = (Psi0[i].re)*posfac[pos].re-(Psi0[i].im)*posfac[pos].im;
3329 destpos[pos].im = (Psi0[i].re)*posfac[pos].im+(Psi0[i].im)*posfac[pos].re;
3330 //destpos[pos].re = (Psi0[i].im)*posfac[pos].re-(-Psi0[i].re)*posfac[pos].im;
3331 //destpos[pos].im = (Psi0[i].im)*posfac[pos].im+(-Psi0[i].re)*posfac[pos].re;
3332 }
3333 }
3334 for (i=0; i<LevS->MaxDoubleG; i++) {
3335 destRCS = &tempdestRC[LevS->DoubleG[2*i]*LevS->MaxNUp];
3336 destRCD = &tempdestRC[LevS->DoubleG[2*i+1]*LevS->MaxNUp];
3337 for (pos=0; pos < LevS->MaxNUp; pos++) {
3338 destRCD[pos].re = destRCS[pos].re;
3339 destRCD[pos].im = -destRCS[pos].im;
3340 }
3341 }
3342 fft_3d_complex_to_real(plan, LevS->LevelNo, FFTNFUp, tempdestRC, work);
3343 DensityRTransformPos(LevS,(fftw_real*)tempdestRC, Psi0R);
3344
3345 // apply position operator and do first result
3346 for (n0=0;n0<N0;n0++) // only local points on x axis
3347 for (n[1]=0;n[1]<N[1];n[1]++)
3348 for (n[2]=0;n[2]<N[2];n[2]++) {
3349 n[0]=n0 + LevS->Plan0.plan->start_nx; // global relative coordinate: due to partitoning of x-axis in PEPGamma>1 case
3350 i0 = n[2]*NUp[2]+N[2]*NUp[2]*(n[1]*NUp[1]+N[1]*NUp[1]*n0*NUp[0]);
3351 iS = n[2]+N[2]*(n[1]+N[1]*n0);
3352 //x[0] += 1; // shifting expectation value of x coordinate from 0 to 1
3353 PsiCR[iS] = Psi0R[i0]; // truedist(Lat, x[0], Wcentre[0],0) *
3354 result1 += PsiCR[iS] * Psi0R[i0];
3355 }
3356 result1 /= LevS->MaxN; // factor due to discrete integration
3357 MPI_Allreduce ( &result1, &Result1, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum "LocalSize to TotalSize"
3358 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) 1st result: %e\n",P->Par.me, Result1);
3359
3360 // fft to reciprocal space and do second result
3361 fft_3d_real_to_complex(plan, LevS->LevelNo, FFTNF1, PsiC, workC);
3362 SetArrayToDouble0((double *)dest, 2*R->InitLevS->MaxG);
3363 for (g=0; g < LevS->MaxG; g++) {
3364 Index = LevS->GArray[g].Index;
3365 dest[g].re = (Psi0[Index].re)*HGcRCFactor;
3366 dest[g].im = (Psi0[Index].im)*HGcRCFactor;
3367 }
3368 result2 = GradSP(P,LevS,Psi0,dest);
3369 MPI_Allreduce ( &result2, &Result2, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum "LocalSize to TotalSize"
3370 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) 2nd result: %e\n",P->Par.me, Result2);
3371
3372 // fft again to real space, this time change symmetry
3373 SetArrayToDouble0((double *)tempdestRC, Dens0->TotalSize*2);
3374 SetArrayToDouble0((double *)PsiC, Dens0->TotalSize*2);
3375 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is positive
3376 Index = LevS->GArray[i].Index;
3377 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
3378 destpos = &tempdestRC[LevS->MaxNUp*Index];
3379 for (pos=0; pos < LevS->MaxNUp; pos++) {
3380 destpos[pos].re = (Psi0[i].im)*posfac[pos].re-(-Psi0[i].re)*posfac[pos].im;
3381 destpos[pos].im = (Psi0[i].im)*posfac[pos].im+(-Psi0[i].re)*posfac[pos].re;
3382 }
3383 }
3384 for (i=0; i<LevS->MaxDoubleG; i++) {
3385 destRCS = &tempdestRC[LevS->DoubleG[2*i]*LevS->MaxNUp];
3386 destRCD = &tempdestRC[LevS->DoubleG[2*i+1]*LevS->MaxNUp];
3387 for (pos=0; pos < LevS->MaxNUp; pos++) {
3388 destRCD[pos].re = destRCS[pos].re;
3389 destRCD[pos].im = -destRCS[pos].im;
3390 }
3391 }
3392 fft_3d_complex_to_real(plan, LevS->LevelNo, FFTNFUp, tempdestRC, work);
3393 DensityRTransformPos(LevS,(fftw_real*)tempdestRC, Psi0R);
3394
3395 // bring down from Lev0 to LevS
3396 for (n0=0;n0<N0;n0++) // only local points on x axis
3397 for (n[1]=0;n[1]<N[1];n[1]++)
3398 for (n[2]=0;n[2]<N[2];n[2]++) {
3399 i0 = n[2]*NUp[2]+N[2]*NUp[2]*(n[1]*NUp[1]+N[1]*NUp[1]*n0*NUp[0]);
3400 iS = n[2]+N[2]*(n[1]+N[1]*n0);
3401 PsiCR[iS] = Psi0R[i0]; // truedist(Lat, x[0], Wcentre[0],0) *
3402 result3 += PsiCR[iS] * Psi0R[i0];
3403 }
3404 result3 /= LevS->MaxN; // factor due to discrete integration
3405 MPI_Allreduce ( &result3, &Result3, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum "LocalSize to TotalSize"
3406 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) 3rd result: %e\n",P->Par.me, Result3);
3407
3408 // fft back to reciprocal space, change symmetry back and do third result
3409 fft_3d_real_to_complex(plan, LevS->LevelNo, FFTNF1, PsiC, workC);
3410 SetArrayToDouble0((double *)dest, 2*R->InitLevS->MaxG);
3411 for (g=0; g < LevS->MaxG; g++) {
3412 Index = LevS->GArray[g].Index;
3413 dest[g].re = (-PsiC[Index].im)*HGcRCFactor;
3414 dest[g].im = ( PsiC[Index].re)*HGcRCFactor;
3415 }
3416 result4 = GradSP(P,LevS,Psi0,dest);
3417 MPI_Allreduce ( &result4, &Result4, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum "LocalSize to TotalSize"
3418 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) 4th result: %e\n",P->Par.me, Result4);
3419}
3420
3421
3422/** Test function to check RxP application.
3423 * Checks applied solution to an analytic for a specific and simple wave function -
3424 * where just one coefficient is unequal to zero.
3425 * \param *P Problem at hand
3426 exp(I b G) - I exp(I b G) b G - exp(I a G) + I exp(I a G) a G
3427 -------------------------------------------------------------
3428 2
3429 G
3430 */
3431void test_rxp(struct Problem *P)
3432{
3433 struct RunStruct *R = &P->R;
3434 struct Lattice *Lat = &P->Lat;
3435 //struct LatticeLevel *Lev0 = R->Lev0;
3436 struct LatticeLevel *LevS = R->LevS;
3437 struct OneGData *GA = LevS->GArray;
3438 //struct Density *Dens0 = Lev0->Dens;
3439 fftw_complex *Psi0 = LevS->LPsi->TempPsi;
3440 fftw_complex *Psi2 = P->Grad.GradientArray[GraSchGradient];
3441 fftw_complex *Psi3 = LevS->LPsi->TempPsi2;
3442 int g, g_bar, i, j, k, k_normal = 0;
3443 double tmp, a,b, G;
3444 //const double *Wcentre = Lat->Psi.AddData[k_normal].WannierCentre;
3445 const double discrete_factor = 1.;//Lat->Volume/LevS->MaxN;
3446 fftw_complex integral;
3447
3448 // reset coefficients
3449 debug (P,"Creating RxP test function.");
3450 SetArrayToDouble0((double *)Psi0,2*R->InitLevS->MaxG);
3451 SetArrayToDouble0((double *)Psi2,2*R->InitLevS->MaxG);
3452
3453 // pick one which becomes non-zero
3454 g = 3;
3455
3456 //for (g=0;g<LevS->MaxG;g++) {
3457 Psi0[g].re = 1.;
3458 Psi0[g].im = 0.;
3459 //}
3460 fprintf(stderr,"(%i) G[%i] = (%e,%e,%e) \n",P->Par.me, g, GA[g].G[0], GA[g].G[1], GA[g].G[2]);
3461 i = 0;
3462
3463 // calculate analytic result
3464 debug (P,"Calculating analytic solution.");
3465 for (g_bar=0;g_bar<LevS->MaxG;g_bar++) {
3466 for (g=0;g<LevS->MaxG;g++) {
3467 if (GA[g].G[i] == GA[g_bar].G[i]) {
3468 j = cross(i,0);
3469 k = cross(i,1);
3470 if (GA[g].G[k] == GA[g_bar].G[k]) {
3471 //b = truedist(Lat, sqrt(Lat->RealBasisSQ[j]), Wcentre[j], j);
3472 b = sqrt(Lat->RealBasisSQ[j]);
3473 //a = truedist(Lat, 0., Wcentre[j], j);
3474 a = 0.;
3475 G = 1; //GA[g].G[k];
3476 if (GA[g].G[j] == GA[g_bar].G[j]) {
3477 Psi2[g_bar].re += G*Psi0[g].re * (.5 * b * b - .5 * a * a) * discrete_factor;
3478 Psi2[g_bar].im += G*Psi0[g].im * (.5 * b * b - .5 * a * a) * discrete_factor;
3479 //if ((G != 0) && ((fabs(Psi0[g].re) > MYEPSILON) || (fabs(Psi0[g].im) > MYEPSILON)))
3480 //fprintf(stderr,"(%i) Psi[%i].re += %e +i %e\n",P->Par.me, g_bar, G*Psi0[g].re * (.5 * b * b - .5 * a * a) * discrete_factor, G*Psi0[g].im * (.5 * b * b - .5 * a * a) * discrete_factor);
3481 } else {
3482 tmp = GA[g].G[j]-GA[g_bar].G[j];
3483 integral.re = (cos(tmp*b)+sin(tmp*b)*b*tmp - cos(tmp*a)-sin(tmp*a)*a*tmp) / (tmp * tmp);
3484 integral.im = (sin(tmp*b)-cos(tmp*b)*b*tmp - sin(tmp*a)+cos(tmp*a)*a*tmp) / (tmp * tmp);
3485 Psi2[g_bar].re += G*(Psi0[g].re*integral.re - Psi0[g].im*integral.im) * discrete_factor;
3486 Psi2[g_bar].im += G*(Psi0[g].re*integral.im + Psi0[g].im*integral.re) * discrete_factor;
3487 //if ((G != 0) && ((fabs(Psi0[g].re) > MYEPSILON) || (fabs(Psi0[g].im) > MYEPSILON)))
3488 //fprintf(stderr,"(%i) Psi[%i].re += %e\tPsi[%i].im += %e \n",P->Par.me, g_bar, G*(Psi0[g].re*integral.re - Psi0[g].im*integral.im) * discrete_factor, g_bar, G*(Psi0[g].re*integral.im + Psi0[g].im*integral.re) * discrete_factor);
3489 }
3490 }
3491 j = cross(i,2);
3492 k = cross(i,3);
3493 if (GA[g].G[k] == GA[g_bar].G[k]) {
3494 //b = truedist(Lat, sqrt(Lat->RealBasisSQ[j]), Wcentre[j], j);
3495 b = sqrt(Lat->RealBasisSQ[j]);
3496 //a = truedist(Lat, 0., Wcentre[j], j);
3497 a = 0.;
3498 G = 1; //GA[g].G[k];
3499 if (GA[g].G[j] == GA[g_bar].G[j]) {
3500 Psi2[g_bar].re += G*Psi0[g].re * (.5 * b * b - .5 * a * a) * discrete_factor;
3501 Psi2[g_bar].im += G*Psi0[g].im * (.5 * b * b - .5 * a * a) * discrete_factor;
3502 //if ((G != 0) && ((fabs(Psi0[g].re) > MYEPSILON) || (fabs(Psi0[g].im) > MYEPSILON)))
3503 //fprintf(stderr,"(%i) Psi[%i].re += %e +i %e\n",P->Par.me, g_bar, G*Psi0[g].re * (.5 * b * b - .5 * a * a) * discrete_factor, G*Psi0[g].im * (.5 * b * b - .5 * a * a) * discrete_factor);
3504 } else {
3505 tmp = GA[g].G[j]-GA[g_bar].G[j];
3506 integral.re = (cos(tmp*b)+sin(tmp*b)*b*tmp - cos(tmp*a)-sin(tmp*a)*a*tmp) / (tmp * tmp);
3507 integral.im = (sin(tmp*b)-cos(tmp*b)*b*tmp - sin(tmp*a)+cos(tmp*a)*a*tmp) / (tmp * tmp);
3508 Psi2[g_bar].re += G*(Psi0[g].re*integral.re - Psi0[g].im*integral.im) * discrete_factor;
3509 Psi2[g_bar].im += G*(Psi0[g].re*integral.im + Psi0[g].im*integral.re) * discrete_factor;
3510 //if ((G != 0) && ((fabs(Psi0[g].re) > MYEPSILON) || (fabs(Psi0[g].im) > MYEPSILON)))
3511 //fprintf(stderr,"(%i) Psi[%i].re += %e\tPsi[%i].im += %e \n",P->Par.me, g_bar, G*(Psi0[g].re*integral.re - Psi0[g].im*integral.im) * discrete_factor, g_bar, G*(Psi0[g].re*integral.im + Psi0[g].im*integral.re) * discrete_factor);
3512 }
3513 }
3514 }
3515 }
3516 }
3517
3518 // apply rxp
3519 debug (P,"Applying RxP to test function.");
3520 CalculatePerturbationOperator_RxP(P,Psi0,Psi3,k_normal,i);
3521
3522 // compare both coefficient arrays
3523 debug(P,"Beginning comparison of analytic and Rxp applied solution.");
3524 for (g=0;g<LevS->MaxG;g++) {
3525 if ((fabs(Psi3[g].re-Psi2[g].re) >= MYEPSILON) || (fabs(Psi3[g].im-Psi2[g].im) >= MYEPSILON))
3526 fprintf(stderr,"(%i) Psi3[%i] = %e +i %e != Psi2[%i] = %e +i %e\n",P->Par.me, g, Psi3[g].re, Psi3[g].im, g, Psi2[g].re, Psi2[g].im);
3527 //else
3528 //fprintf(stderr,"(%i) Psi1[%i] == Psi2[%i] = %e +i %e\n",P->Par.me, g, g, Psi1[g].re, Psi1[g].im);
3529 }
3530 fprintf(stderr,"(%i) <0|1> = <0|r|0> == %e +i %e\n",P->Par.me, GradSP(P,LevS,Psi0,Psi3), GradImSP(P,LevS,Psi0,Psi3));
3531 fprintf(stderr,"(%i) <1|1> = |r|ᅵ == %e +i %e\n",P->Par.me, GradSP(P,LevS,Psi3,Psi3), GradImSP(P,LevS,Psi3,Psi3));
3532 fprintf(stderr,"(%i) <0|0> = %e +i %e\n",P->Par.me, GradSP(P,LevS,Psi0,Psi0), GradImSP(P,LevS,Psi0,Psi0));
3533 fprintf(stderr,"(%i) <0|2> = %e +i %e\n",P->Par.me, GradSP(P,LevS,Psi0,Psi2), GradImSP(P,LevS,Psi0,Psi2));
3534}
3535
3536
3537/** Output of a (X,Y,DX,DY) 2d-vector plot.
3538 * For a printable representation of the induced current two-dimensional vector plots are useful, as three-dimensional
3539 * isospheres are sometimes mis-leading or do not represent the desired flow direction. The routine simply extracts a
3540 * two-dimensional cut orthogonal to one of the lattice axis at a certain node.
3541 * \param *P Problem at hand
3542 * \param B_index direction of B field
3543 * \param n_orth grid node in B_index direction of the plane (the order in which the remaining two coordinate axis
3544 * appear is the same as in a cross product, which is used to determine orthogonality)
3545 */
3546void PlotVectorPlane(struct Problem *P, int B_index, int n_orth)
3547{
3548 struct RunStruct *R = &P->R;
3549 struct LatticeLevel *Lev0 = R->Lev0;
3550 struct Density *Dens0 = Lev0->Dens;
3551 char filename[255];
3552 char *suchpointer;
3553 FILE *PlotFile = NULL;
3554 const int myPE = P->Par.me_comm_ST;
3555 time_t seconds;
3556 fftw_real *CurrentDensity[NDIM*NDIM];
3557 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
3558 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
3559 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
3560 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
3561 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
3562 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
3563 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
3564 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
3565 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
3566 time(&seconds); // get current time
3567
3568 if (!myPE) { // only process 0 writes to file
3569 // open file
3570 sprintf(&filename[0], ".current.L%i.csv", Lev0->LevelNo);
3571 OpenFile(P, &PlotFile, filename, "w", P->Call.out[ReadOut]);
3572 strcpy(filename, ctime(&seconds));
3573 suchpointer = strchr(filename, '\n');
3574 if (suchpointer != NULL)
3575 *suchpointer = '\0';
3576 if (PlotFile != NULL) {
3577 fprintf(PlotFile,"# current vector plot of plane perpendicular to direction e_%i at node %i, seed %i, config %s, run on %s, #cpus %i", B_index, n_orth, R->Seed, P->Files.default_path, filename, P->Par.Max_me_comm_ST_Psi);
3578 fprintf(PlotFile,"\n");
3579 } else { Error(SomeError, "PlotVectorPlane: Opening Plot File"); }
3580 }
3581
3582 // plot density
3583 if (!P->Par.me_comm_ST_PsiT) // only first wave function group as current density of all psis was gathered
3584 PlotRealDensity(P, Lev0, PlotFile, B_index, n_orth, CurrentDensity[B_index*NDIM+cross(B_index,0)], CurrentDensity[B_index*NDIM+cross(B_index,1)]);
3585
3586 if (PlotFile != NULL) {
3587 // close file
3588 fclose(PlotFile);
3589 }
3590}
3591
3592
3593/** Reads psi coefficients of \a type from file and transforms to new level.
3594 * \param *P Problem at hand
3595 * \param type PsiTypeTag of which minimisation group to load from file
3596 * \sa ReadSrcPsiDensity() - reading the coefficients, ChangePsiAndDensToLevUp() - transformation to upper level
3597 */
3598void ReadSrcPerturbedPsis(struct Problem *P, enum PsiTypeTag type)
3599{
3600 struct RunStruct *R = &P->R;
3601 struct Lattice *Lat = &P->Lat;
3602 struct LatticeLevel *Lev0 = &P->Lat.Lev[R->Lev0No+1]; // one level higher than current (ChangeLevUp already occurred)
3603 struct LatticeLevel *LevS = &P->Lat.Lev[R->LevSNo+1];
3604 struct Density *Dens = Lev0->Dens;
3605 struct Psis *Psi = &Lat->Psi;
3606 struct fft_plan_3d *plan = Lat->plan;
3607 fftw_complex *work = (fftw_complex *)Dens->DensityCArray[TempDensity];
3608 fftw_complex *tempdestRC = (fftw_complex *)Dens->DensityArray[TempDensity];
3609 fftw_complex *posfac, *destpos, *destRCS, *destRCD;
3610 fftw_complex *source, *source0;
3611 int Index,i,pos;
3612 double factorC = 1./Lev0->MaxN;
3613 int p,g;
3614
3615 // ================= read coefficients from file to LocalPsi ============
3616 ReadSrcPsiDensity(P, type, 0, R->LevSNo+1);
3617
3618 // ================= transform to upper level ===========================
3619 // for all local Psis do the usual transformation (completing coefficients for all grid vectors, fft, permutation)
3620 LockDensityArray(Dens, TempDensity, real);
3621 LockDensityArray(Dens, TempDensity, imag);
3622 for (p=Psi->LocalNo-1; p >= 0; p--)
3623 if (Psi->LocalPsiStatus[p].PsiType == type) { // only for the desired type
3624 source = LevS->LPsi->LocalPsi[p];
3625 source0 = Lev0->LPsi->LocalPsi[p];
3626 //fprintf(stderr,"(%i) ReadSrcPerturbedPsis: LevSNo %i\t Lev0No %i\tp %i\t source %p\t source0 %p\n", P->Par.me, LevS->LevelNo, Lev0->LevelNo, p, source, source0);
3627 SetArrayToDouble0((double *)tempdestRC, Dens->TotalSize*2);
3628 for (i=0;i<LevS->MaxG;i++) {
3629 Index = LevS->GArray[i].Index;
3630 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
3631 destpos = &tempdestRC[LevS->MaxNUp*Index];
3632 //if (isnan(source[i].re)) { fprintf(stderr,"(%i) WARNING in ReadSrcPerturbedPsis(): source_%i[%i] = NaN!\n", P->Par.me, p, i); Error(SomeError, "NaN-Fehler!"); }
3633 for (pos=0; pos < LevS->MaxNUp; pos++) {
3634 destpos[pos].re = source[i].re*posfac[pos].re-source[i].im*posfac[pos].im;
3635 destpos[pos].im = source[i].re*posfac[pos].im+source[i].im*posfac[pos].re;
3636 }
3637 }
3638 for (i=0; i<LevS->MaxDoubleG; i++) {
3639 destRCS = &tempdestRC[LevS->DoubleG[2*i]*LevS->MaxNUp];
3640 destRCD = &tempdestRC[LevS->DoubleG[2*i+1]*LevS->MaxNUp];
3641 for (pos=0; pos < LevS->MaxNUp; pos++) {
3642 destRCD[pos].re = destRCS[pos].re;
3643 destRCD[pos].im = -destRCS[pos].im;
3644 }
3645 }
3646 fft_3d_complex_to_real(plan, LevS->LevelNo, FFTNFUp, tempdestRC, work);
3647 DensityRTransformPos(LevS,(fftw_real*)tempdestRC,(fftw_real *)Dens->DensityCArray[ActualPsiDensity]);
3648 // now we have density in the upper level, fft back to complex and store it as wave function coefficients
3649 fft_3d_real_to_complex(plan, Lev0->LevelNo, FFTNF1, Dens->DensityCArray[ActualPsiDensity], work);
3650 for (g=0; g < Lev0->MaxG; g++) {
3651 Index = Lev0->GArray[g].Index;
3652 source0[g].re = Dens->DensityCArray[ActualPsiDensity][Index].re*factorC;
3653 source0[g].im = Dens->DensityCArray[ActualPsiDensity][Index].im*factorC;
3654 //if (isnan(source0[g].re)) { fprintf(stderr,"(%i) WARNING in ReadSrcPerturbedPsis(): source0_%i[%i] = NaN!\n", P->Par.me, p, g); Error(SomeError, "NaN-Fehler!"); }
3655 }
3656 if (Lev0->GArray[0].GSq == 0.0)
3657 source0[g].im = 0.0;
3658 }
3659 UnLockDensityArray(Dens, TempDensity, real);
3660 UnLockDensityArray(Dens, TempDensity, imag);
3661 // finished.
3662}
3663
3664/** evaluates perturbed energy functional
3665 * \param norm norm of current Psi in functional
3666 * \param *params void-pointer to parameter array
3667 * \return evaluated functional at f(x) with \a norm
3668 */
3669double perturbed_function (double norm, void *params) {
3670 struct Problem *P = (struct Problem *)params;
3671 int i, n = P->R.LevS->MaxG;
3672 double old_norm = GramSchGetNorm2(P,P->R.LevS,P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo]);
3673 fftw_complex *currentPsi = P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo];
3674 fprintf(stderr,"(%i) perturbed_function: setting norm to %lg ...", P->Par.me, norm);
3675 // set desired norm for current Psi
3676 for (i=0; i< n; i++) {
3677 currentPsi[i].re *= norm/old_norm; // real part
3678 currentPsi[i].im *= norm/old_norm; // imaginary part
3679 }
3680 P->R.PsiStep = 0; // make it not advance to next Psi
3681
3682 //debug(P,"UpdateActualPsiNo");
3683 UpdateActualPsiNo(P, P->R.CurrentMin); // orthogonalize
3684 //debug(P,"UpdateEnergyArray");
3685 UpdateEnergyArray(P); // shift energy values in their array by one
3686 //debug(P,"UpdatePerturbedEnergyCalculation");
3687 UpdatePerturbedEnergyCalculation(P); // re-calc energies (which is hopefully lower)
3688 EnergyAllReduce(P); // gather from all processes and sum up to total energy
3689/*
3690 for (i=0; i< n; i++) {
3691 currentPsi[i].re /= norm/old_norm; // real part
3692 currentPsi[i].im /= norm/old_norm; // imaginary part
3693 }*/
3694
3695 fprintf(stderr,"%lg\n", P->Lat.E->TotalEnergy[0]);
3696 return P->Lat.E->TotalEnergy[0]; // and return evaluated functional
3697}
3698
3699/** evaluates perturbed energy functional.
3700 * \param *x current position in functional
3701 * \param *params void-pointer to parameter array
3702 * \return evaluated functional at f(x)
3703 */
3704double perturbed_f (const gsl_vector *x, void *params) {
3705 struct Problem *P = (struct Problem *)params;
3706 int i, n = P->R.LevS->MaxG*2;
3707 fftw_complex *currentPsi = P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo];
3708 //int diff = 0;
3709 //debug(P,"f");
3710 // put x into current Psi
3711 for (i=0; i< n; i+=2) {
3712 //if ((currentPsi[i/2].re != gsl_vector_get (x, i)) || (currentPsi[i/2].im != gsl_vector_get (x, i+1))) diff++;
3713 currentPsi[i/2].re = gsl_vector_get (x, i); // real part
3714 currentPsi[i/2].im = gsl_vector_get (x, i+1); // imaginary part
3715 }
3716 //if (diff) fprintf(stderr,"(%i) %i differences between old and new currentPsi.\n", P->Par.me, diff);
3717 P->R.PsiStep = 0; // make it not advance to next Psi
3718
3719 //debug(P,"UpdateActualPsiNo");
3720 UpdateActualPsiNo(P, P->R.CurrentMin); // orthogonalize
3721 //debug(P,"UpdateEnergyArray");
3722 UpdateEnergyArray(P); // shift energy values in their array by one
3723 //debug(P,"UpdatePerturbedEnergyCalculation");
3724 UpdatePerturbedEnergyCalculation(P); // re-calc energies (which is hopefully lower)
3725 EnergyAllReduce(P); // gather from all processes and sum up to total energy
3726
3727 return P->Lat.E->TotalEnergy[0]; // and return evaluated functional
3728}
3729
3730/** evaluates perturbed energy gradient.
3731 * \param *x current position in functional
3732 * \param *params void-pointer to parameter array
3733 * \param *g array for gradient vector on return
3734 */
3735void perturbed_df (const gsl_vector *x, void *params, gsl_vector *g) {
3736 struct Problem *P = (struct Problem *)params;
3737 int i, n = P->R.LevS->MaxG*2;
3738 fftw_complex *currentPsi = P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo];
3739 fftw_complex *gradient = P->Grad.GradientArray[ActualGradient];
3740 //int diff = 0;
3741 //debug(P,"df");
3742 // put x into current Psi
3743 for (i=0; i< n; i+=2) {
3744 //if ((currentPsi[i/2].re != gsl_vector_get (x, i)) || (currentPsi[i/2].im != gsl_vector_get (x, i+1))) diff++;
3745 currentPsi[i/2].re = gsl_vector_get (x, i); // real part
3746 currentPsi[i/2].im = gsl_vector_get (x, i+1); // imaginary part
3747 }
3748 //if (diff) fprintf(stderr,"(%i) %i differences between old and new currentPsi.\n", P->Par.me, diff);
3749 P->R.PsiStep = 0; // make it not advance to next Psi
3750
3751 //debug(P,"UpdateActualPsiNo");
3752 UpdateActualPsiNo(P, P->R.CurrentMin); // orthogonalize
3753 //debug(P,"UpdateEnergyArray");
3754 UpdateEnergyArray(P); // shift energy values in their array by one
3755 //debug(P,"UpdatePerturbedEnergyCalculation");
3756 UpdatePerturbedEnergyCalculation(P); // re-calc energies (which is hopefully lower)
3757 EnergyAllReduce(P); // gather from all processes and sum up to total energy
3758
3759 // checkout gradient
3760 //diff = 0;
3761 for (i=0; i< n; i+=2) {
3762 //if ((-gradient[i/2].re != gsl_vector_get (g, i)) || (-gradient[i/2].im != gsl_vector_get (g, i+1))) diff++;
3763 gsl_vector_set (g, i, -gradient[i/2].re); // real part
3764 gsl_vector_set (g, i+1, -gradient[i/2].im); // imaginary part
3765 }
3766 //if (diff) fprintf(stderr,"(%i) %i differences between old and new gradient.\n", P->Par.me, diff);
3767}
3768
3769/** evaluates perturbed energy functional and gradient.
3770 * \param *x current position in functional
3771 * \param *params void-pointer to parameter array
3772 * \param *f pointer to energy function value on return
3773 * \param *g array for gradient vector on return
3774 */
3775void perturbed_fdf (const gsl_vector *x, void *params, double *f, gsl_vector *g) {
3776 struct Problem *P = (struct Problem *)params;
3777 int i, n = P->R.LevS->MaxG*2;
3778 fftw_complex *currentPsi = P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo];
3779 fftw_complex *gradient = P->Grad.GradientArray[ActualGradient];
3780 //int diff = 0;
3781 //debug(P,"fdf");
3782 // put x into current Psi
3783 for (i=0; i< n; i+=2) {
3784 //if ((currentPsi[i/2].re != gsl_vector_get (x, i)) || (currentPsi[i/2].im != gsl_vector_get (x, i+1))) diff++;
3785 currentPsi[i/2].re = gsl_vector_get (x, i); // real part
3786 currentPsi[i/2].im = gsl_vector_get (x, i+1); // imaginary part
3787 }
3788 //if (diff) fprintf(stderr,"(%i) %i differences between old and new currentPsi.\n", P->Par.me, diff);
3789 P->R.PsiStep = 0; // make it not advance to next Psi
3790
3791 //debug(P,"UpdateActualPsiNo");
3792 UpdateActualPsiNo(P, P->R.CurrentMin); // orthogonalize
3793 //debug(P,"UpdateEnergyArray");
3794 UpdateEnergyArray(P); // shift energy values in their array by one
3795 //debug(P,"UpdatePerturbedEnergyCalculation");
3796 UpdatePerturbedEnergyCalculation(P); // re-calc energies (which is hopefully lower)
3797 EnergyAllReduce(P); // gather from all processes and sum up to total energy
3798
3799 // checkout gradient
3800 //diff = 0;
3801 for (i=0; i< n; i+=2) {
3802 //if ((-gradient[i/2].re != gsl_vector_get (g, i)) || (-gradient[i/2].im != gsl_vector_get (g, i+1))) diff++;
3803 gsl_vector_set (g, i, -gradient[i/2].re); // real part
3804 gsl_vector_set (g, i+1, -gradient[i/2].im); // imaginary part
3805 }
3806 //if (diff) fprintf(stderr,"(%i) %i differences between old and new gradient.\n", P->Par.me, diff);
3807
3808 *f = P->Lat.E->TotalEnergy[0]; // and return evaluated functional
3809}
3810
3811/* MinimisePerturbed with all the brent minimisation approach
3812void MinimisePerturbed (struct Problem *P, int *Stop, int *SuperStop) {
3813 struct RunStruct *R = &P->R;
3814 struct Lattice *Lat = &P->Lat;
3815 struct Psis *Psi = &Lat->Psi;
3816 int type;
3817 //int i;
3818
3819 // stuff for GSL minimization
3820 //size_t iter;
3821 //int status, Status
3822 int n = R->LevS->MaxG*2;
3823 const gsl_multimin_fdfminimizer_type *T_multi;
3824 const gsl_min_fminimizer_type *T;
3825 gsl_multimin_fdfminimizer *s_multi;
3826 gsl_min_fminimizer *s;
3827 gsl_vector *x;//, *ss;
3828 gsl_multimin_function_fdf my_func;
3829 gsl_function F;
3830 //fftw_complex *currentPsi;
3831 //double a,b,m, f_m, f_a, f_b;
3832 //double old_norm;
3833
3834 my_func.f = &perturbed_f;
3835 my_func.df = &perturbed_df;
3836 my_func.fdf = &perturbed_fdf;
3837 my_func.n = n;
3838 my_func.params = P;
3839 F.function = &perturbed_function;
3840 F.params = P;
3841
3842 x = gsl_vector_alloc (n);
3843 //ss = gsl_vector_alloc (Psi->NoOfPsis);
3844 T_multi = gsl_multimin_fdfminimizer_vector_bfgs;
3845 s_multi = gsl_multimin_fdfminimizer_alloc (T_multi, n);
3846 T = gsl_min_fminimizer_brent;
3847 s = gsl_min_fminimizer_alloc (T);
3848
3849 for (type=Perturbed_P0;type<=Perturbed_RxP2;type++) { // go through each perturbation group separately //
3850 *Stop=0; // reset stop flag
3851 fprintf(stderr,"(%i)Beginning perturbed minimisation of type %s ...\n", P->Par.me, R->MinimisationName[type]);
3852 //OutputOrbitalPositions(P, Occupied);
3853 R->PsiStep = R->MaxPsiStep; // reset in-Psi-minimisation-counter, so that we really advance to the next wave function
3854 UpdateActualPsiNo(P, type); // step on to next perturbed one
3855 fprintf(stderr, "(%i) Re-initializing perturbed psi array for type %s ", P->Par.me, R->MinimisationName[type]);
3856 if (P->Call.ReadSrcFiles && ReadSrcPsiDensity(P,type,1, R->LevSNo)) {
3857 SpeedMeasure(P, InitSimTime, StartTimeDo);
3858 fprintf(stderr,"from source file of recent calculation\n");
3859 ReadSrcPsiDensity(P,type, 0, R->LevSNo);
3860 ResetGramSchTagType(P, Psi, type, IsOrthogonal); // loaded values are orthonormal
3861 SpeedMeasure(P, DensityTime, StartTimeDo);
3862 //InitDensityCalculation(P);
3863 SpeedMeasure(P, DensityTime, StopTimeDo);
3864 R->OldActualLocalPsiNo = R->ActualLocalPsiNo; // needed otherwise called routines in function below crash
3865 UpdateGramSchOldActualPsiNo(P,Psi);
3866 InitPerturbedEnergyCalculation(P, 1); // go through all orbitals calculate each H^{(0)}-eigenvalue, recalc HGDensity, cause InitDensityCalc zero'd it
3867 UpdatePerturbedEnergyCalculation(P); // H1cGradient and Gradient must be current ones
3868 EnergyAllReduce(P); // gather energies for minimum search
3869 SpeedMeasure(P, InitSimTime, StopTimeDo);
3870 }
3871 if (P->Call.ReadSrcFiles != 1) {
3872 SpeedMeasure(P, InitSimTime, StartTimeDo);
3873 ResetGramSchTagType(P, Psi, type, NotOrthogonal); // perturbed now shall be orthonormalized
3874 if (P->Call.ReadSrcFiles != 2) {
3875 if (R->LevSNo == Lat->MaxLevel-1) { // is it the starting level? (see InitRunLevel())
3876 fprintf(stderr, "randomly.\n");
3877 InitPsisValue(P, Psi->TypeStartIndex[type], Psi->TypeStartIndex[type+1]); // initialize perturbed array for this run
3878 } else {
3879 fprintf(stderr, "from source file of last level.\n");
3880 ReadSrcPerturbedPsis(P, type);
3881 }
3882 }
3883 SpeedMeasure(P, InitGramSchTime, StartTimeDo);
3884 GramSch(P, R->LevS, Psi, Orthogonalize);
3885 SpeedMeasure(P, InitGramSchTime, StopTimeDo);
3886 SpeedMeasure(P, InitDensityTime, StartTimeDo);
3887 //InitDensityCalculation(P);
3888 SpeedMeasure(P, InitDensityTime, StopTimeDo);
3889 InitPerturbedEnergyCalculation(P, 1); // go through all orbitals calculate each H^{(0)}-eigenvalue, recalc HGDensity, cause InitDensityCalc zero'd it
3890 R->OldActualLocalPsiNo = R->ActualLocalPsiNo; // needed otherwise called routines in function below crash
3891 UpdateGramSchOldActualPsiNo(P,Psi);
3892 UpdatePerturbedEnergyCalculation(P); // H1cGradient and Gradient must be current ones
3893 EnergyAllReduce(P); // gather energies for minimum search
3894 SpeedMeasure(P, InitSimTime, StopTimeDo);
3895 R->LevS->Step++;
3896 EnergyOutput(P,0);
3897 while (*Stop != 1) {
3898 // copy current Psi into starting vector
3899 currentPsi = R->LevS->LPsi->LocalPsi[R->ActualLocalPsiNo];
3900 for (i=0; i< n; i+=2) {
3901 gsl_vector_set (x, i, currentPsi[i/2].re); // real part
3902 gsl_vector_set (x, i+1, currentPsi[i/2].im); // imaginary part
3903 }
3904 gsl_multimin_fdfminimizer_set (s_multi, &my_func, x, 0.01, 1e-2);
3905 iter = 0;
3906 status = 0;
3907 do { // look for minimum along current local psi
3908 iter++;
3909 status = gsl_multimin_fdfminimizer_iterate (s_multi);
3910 MPI_Allreduce(&status, &Status, 1, MPI_INT, MPI_MAX, P->Par.comm_ST_Psi);
3911 if (Status)
3912 break;
3913 status = gsl_multimin_test_gradient (s_multi->gradient, 1e-2);
3914 MPI_Allreduce(&status, &Status, 1, MPI_INT, MPI_MAX, P->Par.comm_ST_Psi);
3915 //if (Status == GSL_SUCCESS)
3916 //printf ("Minimum found at:\n");
3917 if (P->Par.me == 0) fprintf (stderr,"(%i,%i,%i)S(%i,%i,%i):\t %5d %10.5f\n",P->Par.my_color_comm_ST,P->Par.me_comm_ST, P->Par.me_comm_ST_PsiT, R->MinStep, R->ActualLocalPsiNo, R->PsiStep, (int)iter, s_multi->f);
3918 //TestGramSch(P,R->LevS,Psi, type); // functions are orthonormal?
3919 } while (Status == GSL_CONTINUE && iter < 3);
3920 // now minimize norm of currentPsi (one-dim)
3921 if (0) {
3922 iter = 0;
3923 status = 0;
3924 m = 1.;
3925 a = MYEPSILON;
3926 b = 100.;
3927 f_a = perturbed_function (a, P);
3928 f_b = perturbed_function (b, P);
3929 f_m = perturbed_function (m, P);
3930 //if ((f_m < f_a) && (f_m < f_b)) {
3931 gsl_min_fminimizer_set (s, &F, m, a, b);
3932 do { // look for minimum along current local psi
3933 iter++;
3934 status = gsl_min_fminimizer_iterate (s);
3935 m = gsl_min_fminimizer_x_minimum (s);
3936 a = gsl_min_fminimizer_x_lower (s);
3937 b = gsl_min_fminimizer_x_upper (s);
3938 status = gsl_min_test_interval (a, b, 0.001, 0.0);
3939 if (status == GSL_SUCCESS)
3940 printf ("Minimum found at:\n");
3941 printf ("%5d [%.7f, %.7f] %.7f %.7f\n",
3942 (int) iter, a, b,
3943 m, b - a);
3944 } while (status == GSL_CONTINUE && iter < 100);
3945 old_norm = GramSchGetNorm2(P,P->R.LevS,P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo]);
3946 for (i=0; i< n; i++) {
3947 currentPsi[i].re *= m/old_norm; // real part
3948 currentPsi[i].im *= m/old_norm; // imaginary part
3949 }
3950 } else debug(P,"Norm not minimizable!");
3951 //P->R.PsiStep = P->R.MaxPsiStep; // make it advance to next Psi
3952 FindPerturbedMinimum(P);
3953 //debug(P,"UpdateActualPsiNo");
3954 UpdateActualPsiNo(P, type); // step on to next perturbed Psi
3955 //debug(P,"UpdateEnergyArray");
3956 UpdateEnergyArray(P); // shift energy values in their array by one
3957 //debug(P,"UpdatePerturbedEnergyCalculation");
3958 UpdatePerturbedEnergyCalculation(P); // re-calc energies (which is hopefully lower)
3959 EnergyAllReduce(P); // gather from all processes and sum up to total energy
3960 //ControlNativeDensity(P); // check total density (summed up PertMixed must be zero!)
3961 //printf ("(%i,%i,%i)S(%i,%i,%i):\t %5d %10.5f\n",P->Par.my_color_comm_ST,P->Par.me_comm_ST, P->Par.me_comm_ST_PsiT, R->MinStep, R->ActualLocalPsiNo, R->PsiStep, (int)iter, s_multi->f);
3962 if (*SuperStop != 1)
3963 *SuperStop = CheckCPULIM(P);
3964 *Stop = CalculateMinimumStop(P, *SuperStop);
3965 P->Speed.Steps++; // step on
3966 R->LevS->Step++;
3967 }
3968 // now release normalization condition and minimize wrt to norm
3969 *Stop = 0;
3970 while (*Stop != 1) {
3971 currentPsi = R->LevS->LPsi->LocalPsi[R->ActualLocalPsiNo];
3972 iter = 0;
3973 status = 0;
3974 m = 1.;
3975 a = 0.001;
3976 b = 10.;
3977 f_a = perturbed_function (a, P);
3978 f_b = perturbed_function (b, P);
3979 f_m = perturbed_function (m, P);
3980 if ((f_m < f_a) && (f_m < f_b)) {
3981 gsl_min_fminimizer_set (s, &F, m, a, b);
3982 do { // look for minimum along current local psi
3983 iter++;
3984 status = gsl_min_fminimizer_iterate (s);
3985 m = gsl_min_fminimizer_x_minimum (s);
3986 a = gsl_min_fminimizer_x_lower (s);
3987 b = gsl_min_fminimizer_x_upper (s);
3988 status = gsl_min_test_interval (a, b, 0.001, 0.0);
3989 if (status == GSL_SUCCESS)
3990 printf ("Minimum found at:\n");
3991 printf ("%5d [%.7f, %.7f] %.7f %.7f\n",
3992 (int) iter, a, b,
3993 m, b - a);
3994 } while (status == GSL_CONTINUE && iter < 100);
3995 old_norm = GramSchGetNorm2(P,P->R.LevS,P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo]);
3996 for (i=0; i< n; i++) {
3997 currentPsi[i].re *= m/old_norm; // real part
3998 currentPsi[i].im *= m/old_norm; // imaginary part
3999 }
4000 }
4001 P->R.PsiStep = P->R.MaxPsiStep; // make it advance to next Psi
4002 //debug(P,"UpdateActualPsiNo");
4003 UpdateActualPsiNo(P, type); // step on to next perturbed Psi
4004 if (*SuperStop != 1)
4005 *SuperStop = CheckCPULIM(P);
4006 *Stop = CalculateMinimumStop(P, *SuperStop);
4007 P->Speed.Steps++; // step on
4008 R->LevS->Step++;
4009 }
4010 if(P->Call.out[NormalOut]) fprintf(stderr,"(%i) Write %s srcpsi to disk\n", P->Par.me, R->MinimisationName[type]);
4011 OutputSrcPsiDensity(P, type);
4012// if (!TestReadnWriteSrcDensity(P,type))
4013// Error(SomeError,"TestReadnWriteSrcDensity failed!");
4014 }
4015
4016 TestGramSch(P,R->LevS,Psi, type); // functions are orthonormal?
4017 // calculate current density summands
4018 //if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Filling current density grid ...\n",P->Par.me);
4019 SpeedMeasure(P, CurrDensTime, StartTimeDo);
4020 if (*SuperStop != 1) {
4021 if ((R->DoFullCurrent == 1) || ((R->DoFullCurrent == 2) && (CheckOrbitalOverlap(P) == 1))) { //test to check whether orbitals have mutual overlap and thus \\DeltaJ_{xc} must not be dropped
4022 R->DoFullCurrent = 1; // set to 1 if it was 2 but Check...() yielded necessity
4023 //debug(P,"Filling with Delta j ...");
4024 //FillDeltaCurrentDensity(P);
4025 }// else
4026 //debug(P,"There is no overlap between orbitals.");
4027 //debug(P,"Filling with j ...");
4028 FillCurrentDensity(P);
4029 }
4030 SpeedMeasure(P, CurrDensTime, StopTimeDo);
4031
4032 SetGramSchExtraPsi(P,Psi,NotUsedToOrtho); // remove extra Psis from orthogonality check
4033 ResetGramSchTagType(P, Psi, type, NotUsedToOrtho); // remove this group from the check for the next minimisation group as well!
4034 }
4035 UpdateActualPsiNo(P, Occupied); // step on back to an occupied one
4036
4037 gsl_multimin_fdfminimizer_free (s_multi);
4038 gsl_min_fminimizer_free (s);
4039 gsl_vector_free (x);
4040 //gsl_vector_free (ss);
4041}
4042*/
Note: See TracBrowser for help on using the repository browser.