source: pcp/src/perturbed.c@ d2f1b1

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

fixed some Free(.."bla") to show correct function name

  • Property mode set to 100644
File size: 217.2 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/** Linear interpolation for coordinate \a R that lies between grid nodes of \a *grid.
1714 * \param *P Problem at hand
1715 * \param *Lat Lattice structure for grid axis
1716 * \param *Lev LatticeLevel structure for grid axis node counts
1717 * \param R[] coordinate vector
1718 * \param *grid grid with fixed nodes
1719 * \return linearly interpolated value of \a *grid for position \a R[NDIM]
1720 */
1721double LinearInterpolationBetweenGrid(struct Problem *P, struct Lattice *Lat, struct LatticeLevel *Lev, double R[NDIM], fftw_real *grid)
1722{
1723 double x[2][NDIM];
1724 const int myPE = P->Par.me_comm_ST_Psi;
1725 int N[NDIM];
1726 const int N0 = Lev->Plan0.plan->local_nx;
1727 N[0] = Lev->Plan0.plan->N[0];
1728 N[1] = Lev->Plan0.plan->N[1];
1729 N[2] = Lev->Plan0.plan->N[2];
1730 int g;
1731 double n[NDIM];
1732 int k[2][NDIM];
1733 double sigma;
1734
1735 RMat33Vec3(n, Lat->ReciBasis, &R[0]); // transform real coordinates to [0,1]^3 vector
1736 for (g=0;g<NDIM;g++) {
1737 // k[i] are right and left nearest neighbour node to true position
1738 k[0][g] = floor(n[g]/(2.*PI)*(double)N[g]); // n[2] is floor grid
1739 k[1][g] = ceil(n[g]/(2.*PI)*(double)N[g]); // n[1] is ceil grid
1740 // x[i] give weights of left and right neighbours (the nearer the true point is to one, the closer its weight to 1)
1741 x[0][g] = (k[1][g] - n[g]/(2.*PI)*(double)N[g]);
1742 x[1][g] = 1. - x[0][g];
1743 //fprintf(stderr,"(%i) n = %lg, n_floor[%i] = %i\tn_ceil[%i] = %i --- x_floor[%i] = %e\tx_ceil[%i] = %e\n",P->Par.me, n[g], g,k[0][g], g,k[1][g], g,x[0][g], g,x[1][g]);
1744 }
1745 sigma = 0.;
1746 for (g=0;g<2;g++) { // interpolate linearly between adjacent grid points per axis
1747 if ((k[g][0] >= N0*myPE) && (k[g][0] < N0*(myPE+1))) {
1748 //fprintf(stderr,"(%i) grid[%i]: sigma = %e\n", P->Par.me, k[g][2]+N[2]*(k[g][1]+N[1]*(k[g][0]-N0*myPE)), sigma);
1749 sigma += (x[g][0]*x[0][1]*x[0][2])*grid[k[0][2]+N[2]*(k[0][1]+N[1]*(k[g][0]-N0*myPE))]*mu0; // if it's local and factor from inverse fft
1750 //fprintf(stderr,"(%i) grid[%i]: sigma += %e * %e \n", P->Par.me, k[g][2]+N[2]*(k[g][1]+N[1]*(k[g][0]-N0*myPE)), (x[g][0]*x[0][1]*x[0][2]), grid[k[0][2]+N[2]*(k[0][1]+N[1]*(k[g][0]-N0*myPE))]*mu0);
1751 sigma += (x[g][0]*x[0][1]*x[1][2])*grid[k[1][2]+N[2]*(k[0][1]+N[1]*(k[g][0]-N0*myPE))]*mu0; // if it's local and factor from inverse fft
1752 //fprintf(stderr,"(%i) grid[%i]: sigma += %e * %e \n", P->Par.me, k[g][2]+N[2]*(k[g][1]+N[1]*(k[g][0]-N0*myPE)), (x[g][0]*x[0][1]*x[1][2]), grid[k[1][2]+N[2]*(k[0][1]+N[1]*(k[g][0]-N0*myPE))]*mu0);
1753 sigma += (x[g][0]*x[1][1]*x[0][2])*grid[k[0][2]+N[2]*(k[1][1]+N[1]*(k[g][0]-N0*myPE))]*mu0; // if it's local and factor from inverse fft
1754 //fprintf(stderr,"(%i) grid[%i]: sigma += %e * %e \n", P->Par.me, k[g][2]+N[2]*(k[g][1]+N[1]*(k[g][0]-N0*myPE)), (x[g][0]*x[1][1]*x[0][2]), grid[k[0][2]+N[2]*(k[1][1]+N[1]*(k[g][0]-N0*myPE))]*mu0);
1755 sigma += (x[g][0]*x[1][1]*x[1][2])*grid[k[1][2]+N[2]*(k[1][1]+N[1]*(k[g][0]-N0*myPE))]*mu0; // if it's local and factor from inverse fft
1756 //fprintf(stderr,"(%i) grid[%i]: sigma += %e * %e \n", P->Par.me, k[g][2]+N[2]*(k[g][1]+N[1]*(k[g][0]-N0*myPE)), (x[g][0]*x[1][1]*x[1][2]), grid[k[1][2]+N[2]*(k[1][1]+N[1]*(k[g][0]-N0*myPE))]*mu0);
1757 }
1758 }
1759 return sigma;
1760}
1761
1762/** Linear Interpolation from all eight corners of the box that singles down to a point on the lower level.
1763 * \param *P Problem at hand
1764 * \param *Lev LatticeLevel structure for node numbers
1765 * \param upperNode Node around which to interpolate
1766 * \param *upperGrid array of grid points
1767 * \return summed up and then averaged octant around \a upperNode
1768 */
1769double LinearPullDownFromUpperLevel(struct Problem *P, struct LatticeLevel *Lev, int upperNode, fftw_real *upperGrid)
1770{
1771 const int N0 = Lev->Plan0.plan->local_nx;
1772 const int N1 = Lev->Plan0.plan->N[1];
1773 const int N2 = Lev->Plan0.plan->N[2];
1774 double lowerGrid = 0.;
1775 int nr=1;
1776 lowerGrid += upperGrid[upperNode];
1777 if (upperNode % N0 != N0-1) {
1778 lowerGrid += upperGrid[upperNode+1];
1779 nr++;
1780 if (upperNode % N1 != N1-1) {
1781 lowerGrid += upperGrid[upperNode + 0 + N2*(1 + N1*1)];
1782 nr++;
1783 if (upperNode % N2 != N2-1) {
1784 lowerGrid += upperGrid[upperNode + 1 + N2*(1 + N1*1)];
1785 nr++;
1786 }
1787 }
1788 if (upperNode % N2 != N2-1) {
1789 lowerGrid += upperGrid[upperNode + 1 + N2*(0 + N1*1)];
1790 nr++;
1791 }
1792 }
1793 if (upperNode % N1 != N1-1) {
1794 lowerGrid += upperGrid[upperNode + 0 + N2*(1 + N1*0)];
1795 nr++;
1796 if (upperNode % N2 != N2-1) {
1797 lowerGrid += upperGrid[upperNode + 1 + N2*(1 + N1*0)];
1798 nr++;
1799 }
1800 }
1801 if (upperNode % N2 != N2-1) {
1802 lowerGrid += upperGrid[upperNode + 1 + N2*(0 + N1*0)];
1803 nr++;
1804 }
1805 return (lowerGrid/(double)nr);
1806}
1807
1808/** Evaluates the 1-stern in order to evaluate the first derivative on the grid.
1809 * \param *P Problem at hand
1810 * \param *Lev Level to interpret the \a *density on
1811 * \param *density array with gridded values
1812 * \param *n 3 vector with indices on the grid
1813 * \param axis axis along which is derived
1814 * \param myPE number of processes who share the density
1815 * \return [+1/2 -1/2] of \a *n
1816 */
1817double FirstDiscreteDerivative(struct Problem *P, struct LatticeLevel *Lev, fftw_real *density, int *n, int axis, int myPE)
1818{
1819 int *N = Lev->Plan0.plan->N; // maximum nodes per axis
1820 const int N0 = Lev->Plan0.plan->local_nx; // special local number due to parallel split up
1821 double ret[NDIM], Ret[NDIM]; // return value local/global
1822 int i;
1823
1824 for (i=0;i<NDIM;i++) {
1825 ret[i] = Ret[i] = 0.;
1826 }
1827 if (((n[0]+1)%N[0] >= N0*myPE) && ((n[0]+1)%N[0] < N0*(myPE+1))) // next cell belongs to this process
1828 ret[0] += 1./2. * (density[n[2]+N[2]*(n[1]+N[1]*(n[0]+1-N0*myPE))]);
1829 if (((n[0]-1)%N[0] >= N0*myPE) && ((n[0]-1)%N[0] < N0*(myPE+1))) // previous cell belongs to this process
1830 ret[0] -= 1./2. * (density[n[2]+N[2]*(n[1]+N[1]*(n[0]-1-N0*myPE))]);
1831 if ((n[0] >= N0*myPE) && (n[0] < N0*(myPE+1))) {
1832 ret[1] += 1./2. * (density[n[2]+N[2]*((n[1]+1)%N[1] + N[1]*(n[0]%N0))]);
1833 ret[1] -= 1./2. * (density[n[2]+N[2]*((n[1]-1)%N[1] + N[1]*(n[0]%N0))]);
1834 }
1835 if ((n[0] >= N0*myPE) && (n[0] < N0*(myPE+1))) {
1836 ret[2] += 1./2. * (density[(n[2]+1)%N[2] + N[2]*(n[1]+N[1]*(n[0]%N0))]);
1837 ret[2] -= 1./2. * (density[(n[2]-1)%N[2] + N[2]*(n[1]+N[1]*(n[0]%N0))]);
1838 }
1839
1840 if (MPI_Allreduce(ret, Ret, 3, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi) != MPI_SUCCESS)
1841 Error(SomeError, "FirstDiscreteDerivative: MPI_Allreduce failure!");
1842
1843 for (i=0;i<NDIM;i++) // transform from node count to [0,1]^3
1844 Ret[i] *= N[i];
1845 RMat33Vec3(ret, P->Lat.ReciBasis, Ret); // this actually divides it by mesh length in real coordinates
1846 //fprintf(stderr, "(%i) sum at (%i,%i,%i) : %lg\n",P->Par.me, n[0],n[1],n[2], ret[axis]);
1847 return ret[axis]; ///(P->Lat.RealBasisQ[axis]/N[axis]);
1848}
1849
1850/** Fouriertransforms given \a source.
1851 * By the use of the symmetry parameter an additional imaginary unit and/or the momentum operator can
1852 * be applied at the same time.
1853 * \param *P Problem at hand
1854 * \param *Psi source array of reciprocal coefficients
1855 * \param *PsiR destination array, becoming filled with real coefficients
1856 * \param index_g component of G vector (only needed for symmetry=4..7)
1857 * \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
1858 * but additionally with momentum operator
1859 */
1860void fft_Psi(struct Problem *P, const fftw_complex *Psi, fftw_real *PsiR, const int index_g, const int symmetry)
1861{
1862 struct Lattice *Lat = &P->Lat;
1863 struct RunStruct *R = &P->R;
1864 struct LatticeLevel *Lev0 = R->Lev0;
1865 struct LatticeLevel *LevS = R->LevS;
1866 struct Density *Dens0 = Lev0->Dens;
1867 struct fft_plan_3d *plan = Lat->plan;
1868 fftw_complex *tempdestRC = (fftw_complex *)Dens0->DensityArray[TempDensity];
1869 fftw_complex *work = Dens0->DensityCArray[TempDensity];
1870 fftw_complex *posfac, *destpos, *destRCS, *destRCD;
1871 int i, Index, pos;
1872
1873 LockDensityArray(Dens0,TempDensity,imag); // tempdestRC
1874 SetArrayToDouble0((double *)tempdestRC, Dens0->TotalSize*2);
1875 SetArrayToDouble0((double *)PsiR, Dens0->TotalSize*2);
1876 switch (symmetry) {
1877 case 0:
1878 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is positive
1879 Index = LevS->GArray[i].Index;
1880 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1881 destpos = &tempdestRC[LevS->MaxNUp*Index];
1882 for (pos=0; pos < LevS->MaxNUp; pos++) {
1883 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1884 destpos[pos].re = (Psi[i].re)*posfac[pos].re-(Psi[i].im)*posfac[pos].im;
1885 destpos[pos].im = (Psi[i].re)*posfac[pos].im+(Psi[i].im)*posfac[pos].re;
1886 }
1887 }
1888 break;
1889 case 1:
1890 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is - positive
1891 Index = LevS->GArray[i].Index;
1892 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1893 destpos = &tempdestRC[LevS->MaxNUp*Index];
1894 for (pos=0; pos < LevS->MaxNUp; pos++) {
1895 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1896 destpos[pos].re = -((Psi[i].re)*posfac[pos].re-(Psi[i].im)*posfac[pos].im);
1897 destpos[pos].im = -((Psi[i].re)*posfac[pos].im+(Psi[i].im)*posfac[pos].re);
1898 }
1899 }
1900 break;
1901 case 2:
1902 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is negative
1903 Index = LevS->GArray[i].Index;
1904 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1905 destpos = &tempdestRC[LevS->MaxNUp*Index];
1906 for (pos=0; pos < LevS->MaxNUp; pos++) {
1907 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1908 destpos[pos].re = (-Psi[i].im)*posfac[pos].re-(Psi[i].re)*posfac[pos].im;
1909 destpos[pos].im = (-Psi[i].im)*posfac[pos].im+(Psi[i].re)*posfac[pos].re;
1910 }
1911 }
1912 break;
1913 case 3:
1914 for (i=0;i<LevS->MaxG;i++) { // incoming is negative, outgoing is positive
1915 Index = LevS->GArray[i].Index;
1916 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1917 destpos = &tempdestRC[LevS->MaxNUp*Index];
1918 for (pos=0; pos < LevS->MaxNUp; pos++) {
1919 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1920 destpos[pos].re = (Psi[i].im)*posfac[pos].re-(-Psi[i].re)*posfac[pos].im;
1921 destpos[pos].im = (Psi[i].im)*posfac[pos].im+(-Psi[i].re)*posfac[pos].re;
1922 }
1923 }
1924 break;
1925 case 4:
1926 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is positive
1927 Index = LevS->GArray[i].Index;
1928 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1929 destpos = &tempdestRC[LevS->MaxNUp*Index];
1930 for (pos=0; pos < LevS->MaxNUp; pos++) {
1931 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1932 destpos[pos].re = LevS->GArray[i].G[index_g]*((Psi[i].re)*posfac[pos].re-(Psi[i].im)*posfac[pos].im);
1933 destpos[pos].im = LevS->GArray[i].G[index_g]*((Psi[i].re)*posfac[pos].im+(Psi[i].im)*posfac[pos].re);
1934 }
1935 }
1936 break;
1937 case 5:
1938 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is - positive
1939 Index = LevS->GArray[i].Index;
1940 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1941 destpos = &tempdestRC[LevS->MaxNUp*Index];
1942 for (pos=0; pos < LevS->MaxNUp; pos++) {
1943 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1944 destpos[pos].re = -LevS->GArray[i].G[index_g]*((Psi[i].re)*posfac[pos].re-(Psi[i].im)*posfac[pos].im);
1945 destpos[pos].im = -LevS->GArray[i].G[index_g]*((Psi[i].re)*posfac[pos].im+(Psi[i].im)*posfac[pos].re);
1946 }
1947 }
1948 break;
1949 case 6:
1950 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is negative
1951 Index = LevS->GArray[i].Index;
1952 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1953 destpos = &tempdestRC[LevS->MaxNUp*Index];
1954 for (pos=0; pos < LevS->MaxNUp; pos++) {
1955 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1956 destpos[pos].re = LevS->GArray[i].G[index_g]*((-Psi[i].im)*posfac[pos].re-(Psi[i].re)*posfac[pos].im);
1957 destpos[pos].im = LevS->GArray[i].G[index_g]*((-Psi[i].im)*posfac[pos].im+(Psi[i].re)*posfac[pos].re);
1958 }
1959 }
1960 break;
1961 case 7:
1962 for (i=0;i<LevS->MaxG;i++) { // incoming is negative, outgoing is positive
1963 Index = LevS->GArray[i].Index;
1964 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
1965 destpos = &tempdestRC[LevS->MaxNUp*Index];
1966 for (pos=0; pos < LevS->MaxNUp; pos++) {
1967 //if (destpos != &tempdestRC[LevS->MaxNUp*Index] || LevS->MaxNUp*Index+pos<0 || LevS->MaxNUp*Index+pos>=Dens0->TotalSize) Error(SomeError,"fft_Psi: destpos corrupted");
1968 destpos[pos].re = LevS->GArray[i].G[index_g]*((Psi[i].im)*posfac[pos].re-(-Psi[i].re)*posfac[pos].im);
1969 destpos[pos].im = LevS->GArray[i].G[index_g]*((Psi[i].im)*posfac[pos].im+(-Psi[i].re)*posfac[pos].re);
1970 }
1971 }
1972 break;
1973 }
1974 for (i=0; i<LevS->MaxDoubleG; i++) {
1975 destRCS = &tempdestRC[LevS->DoubleG[2*i]*LevS->MaxNUp];
1976 destRCD = &tempdestRC[LevS->DoubleG[2*i+1]*LevS->MaxNUp];
1977 for (pos=0; pos < LevS->MaxNUp; pos++) {
1978 //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");
1979 destRCD[pos].re = destRCS[pos].re;
1980 destRCD[pos].im = -destRCS[pos].im;
1981 }
1982 }
1983 fft_3d_complex_to_real(plan, LevS->LevelNo, FFTNFUp, tempdestRC, work);
1984 DensityRTransformPos(LevS,(fftw_real*)tempdestRC, PsiR);
1985 UnLockDensityArray(Dens0,TempDensity,imag); // tempdestRC
1986}
1987
1988/** Locks all NDIM_NDIM current density arrays
1989 * \param Dens0 Density structure to be locked (in the current parts)
1990 */
1991void AllocCurrentDensity(struct Density *Dens0) {
1992 // real
1993 LockDensityArray(Dens0,CurrentDensity0,real); // CurrentDensity[B_index]
1994 LockDensityArray(Dens0,CurrentDensity1,real); // CurrentDensity[B_index]
1995 LockDensityArray(Dens0,CurrentDensity2,real); // CurrentDensity[B_index]
1996 LockDensityArray(Dens0,CurrentDensity3,real); // CurrentDensity[B_index]
1997 LockDensityArray(Dens0,CurrentDensity4,real); // CurrentDensity[B_index]
1998 LockDensityArray(Dens0,CurrentDensity5,real); // CurrentDensity[B_index]
1999 LockDensityArray(Dens0,CurrentDensity6,real); // CurrentDensity[B_index]
2000 LockDensityArray(Dens0,CurrentDensity7,real); // CurrentDensity[B_index]
2001 LockDensityArray(Dens0,CurrentDensity8,real); // CurrentDensity[B_index]
2002 // imaginary
2003 LockDensityArray(Dens0,CurrentDensity0,imag); // CurrentDensity[B_index]
2004 LockDensityArray(Dens0,CurrentDensity1,imag); // CurrentDensity[B_index]
2005 LockDensityArray(Dens0,CurrentDensity2,imag); // CurrentDensity[B_index]
2006 LockDensityArray(Dens0,CurrentDensity3,imag); // CurrentDensity[B_index]
2007 LockDensityArray(Dens0,CurrentDensity4,imag); // CurrentDensity[B_index]
2008 LockDensityArray(Dens0,CurrentDensity5,imag); // CurrentDensity[B_index]
2009 LockDensityArray(Dens0,CurrentDensity6,imag); // CurrentDensity[B_index]
2010 LockDensityArray(Dens0,CurrentDensity7,imag); // CurrentDensity[B_index]
2011 LockDensityArray(Dens0,CurrentDensity8,imag); // CurrentDensity[B_index]
2012}
2013
2014/** Reset and unlocks all NDIM_NDIM current density arrays
2015 * \param Dens0 Density structure to be unlocked/resetted (in the current parts)
2016 */
2017void DisAllocCurrentDensity(struct Density *Dens0) {
2018 //int i;
2019 // real
2020// for(i=0;i<NDIM*NDIM;i++)
2021// SetArrayToDouble0((double *)Dens0->DensityArray[i], Dens0->TotalSize*2);
2022 UnLockDensityArray(Dens0,CurrentDensity0,real); // CurrentDensity[B_index]
2023 UnLockDensityArray(Dens0,CurrentDensity1,real); // CurrentDensity[B_index]
2024 UnLockDensityArray(Dens0,CurrentDensity2,real); // CurrentDensity[B_index]
2025 UnLockDensityArray(Dens0,CurrentDensity3,real); // CurrentDensity[B_index]
2026 UnLockDensityArray(Dens0,CurrentDensity4,real); // CurrentDensity[B_index]
2027 UnLockDensityArray(Dens0,CurrentDensity5,real); // CurrentDensity[B_index]
2028 UnLockDensityArray(Dens0,CurrentDensity6,real); // CurrentDensity[B_index]
2029 UnLockDensityArray(Dens0,CurrentDensity7,real); // CurrentDensity[B_index]
2030 UnLockDensityArray(Dens0,CurrentDensity8,real); // CurrentDensity[B_index]
2031 // imaginary
2032// for(i=0;i<NDIM*NDIM;i++)
2033// SetArrayToDouble0((double *)Dens0->DensityCArray[i], Dens0->TotalSize*2);
2034 UnLockDensityArray(Dens0,CurrentDensity0,imag); // CurrentDensity[B_index]
2035 UnLockDensityArray(Dens0,CurrentDensity1,imag); // CurrentDensity[B_index]
2036 UnLockDensityArray(Dens0,CurrentDensity2,imag); // CurrentDensity[B_index]
2037 UnLockDensityArray(Dens0,CurrentDensity3,imag); // CurrentDensity[B_index]
2038 UnLockDensityArray(Dens0,CurrentDensity4,imag); // CurrentDensity[B_index]
2039 UnLockDensityArray(Dens0,CurrentDensity5,imag); // CurrentDensity[B_index]
2040 UnLockDensityArray(Dens0,CurrentDensity6,imag); // CurrentDensity[B_index]
2041 UnLockDensityArray(Dens0,CurrentDensity7,imag); // CurrentDensity[B_index]
2042 UnLockDensityArray(Dens0,CurrentDensity8,imag); // CurrentDensity[B_index]
2043}
2044
2045// these defines safe-guard same symmetry for same kind of wave function
2046#define Psi0symmetry 0 // //0 //0 //0 // regard psi0 as real
2047#define Psi1symmetry 0 // //3 //0 //0 // regard psi0 as real
2048#define Psip0symmetry 6 //6 //6 //6 //6 // momentum times "i" due to operation on left hand
2049#define Psip1symmetry 7 //7 //4 //6 //7 // momentum times "-i" as usual (right hand)
2050
2051/** Evaluates the 3x3 current density arrays.
2052 * The formula we want to evaluate is as follows
2053 * \f[
2054 * j_k(r) = \langle \psi_k^{(0)} | \Bigl ( p|r'\rangle\langle r' | + | r' \rangle \langle r' | p \Bigr )
2055 \Bigl [ | \psi_k^{(r\times p )} \rangle - r' \times | \psi_k^{(p)} \rangle \Bigr ] \cdot B.
2056 * \f]
2057 * Most of the DensityTypes-arrays are locked for temporary use. Pointers are set to their
2058 * start address and afterwards the current density arrays locked and reset'ed. Then for every
2059 * unperturbed wave function we do:
2060 * -# FFT unperturbed p-perturbed and rxp-perturbed wave function
2061 * -# FFT wave function with applied momentum operator for all three indices
2062 * -# For each index of the momentum operator:
2063 * -# FFT p-perturbed wave function
2064 * -# For every index of the external field:
2065 * -# FFT rxp-perturbed wave function
2066 * -# Evaluate current density for these momentum index and external field indices
2067 *
2068 * Afterwards the temporary densities are unlocked and the density ones gathered from all Psi-
2069 * sharing processes.
2070 *
2071 * \param *P Problem at hand, containing Lattice and RunStruct
2072 */
2073void FillCurrentDensity(struct Problem *P)
2074{
2075 struct Lattice *Lat = &P->Lat;
2076 struct RunStruct *R = &P->R;
2077 struct Psis *Psi = &Lat->Psi;
2078 struct LatticeLevel *LevS = R->LevS;
2079 struct LatticeLevel *Lev0 = R->Lev0;
2080 struct Density *Dens0 = Lev0->Dens;
2081 fftw_complex *Psi0;
2082 fftw_real *Psi0R, *Psip0R;
2083 fftw_real *CurrentDensity[NDIM*NDIM];
2084 fftw_real *Psi1R;
2085 fftw_real *Psip1R;
2086 fftw_real *tempArray; // intendedly the same
2087 double r_bar[NDIM], x[NDIM], fac[NDIM];
2088 double Current;//, current;
2089 const double UnitsFactor = 1.; ///LevS->MaxN; // 1/N (from ff-backtransform)
2090 int i, index, B_index;
2091 int k, j, i0;
2092 int n[NDIM], n0;
2093 int *N;
2094 N = Lev0->Plan0.plan->N;
2095 const int N0 = Lev0->Plan0.plan->local_nx;
2096 //int ActNum;
2097 const int myPE = P->Par.me_comm_ST_Psi;
2098 const int type = R->CurrentMin;
2099 MPI_Status status;
2100 int cross_lookup_1[4], cross_lookup_3[4], l_1 = 0, l_3 = 0;
2101 double Factor;//, factor;
2102
2103 //fprintf(stderr,"(%i) FactoR %e\n", P->Par.me, R->FactorDensityR);
2104
2105 // Init values and pointers
2106 if (P->Call.out[PsiOut]) {
2107 fprintf(stderr,"(%i) LockArray: ", P->Par.me);
2108 for(i=0;i<MaxDensityTypes;i++)
2109 fprintf(stderr,"(%i,%i) ",Dens0->LockArray[i],Dens0->LockCArray[i]);
2110 fprintf(stderr,"\n");
2111 }
2112 LockDensityArray(Dens0,Temp2Density,real); // Psi1R
2113 LockDensityArray(Dens0,Temp2Density,imag); // Psip1R and tempArray
2114 LockDensityArray(Dens0,GapDensity,real); // Psi0R
2115 LockDensityArray(Dens0,GapLocalDensity,real); // Psip0R
2116
2117 Psi0R = (fftw_real *)Dens0->DensityArray[GapDensity];
2118 Psip0R = (fftw_real *)Dens0->DensityArray[GapLocalDensity];
2119 Psi1R = (fftw_real *)Dens0->DensityArray[Temp2Density];
2120 tempArray = Psip1R = (fftw_real *)Dens0->DensityCArray[Temp2Density];
2121 SetArrayToDouble0((double *)Psi0R,Dens0->TotalSize*2);
2122 SetArrayToDouble0((double *)Psip0R,Dens0->TotalSize*2);
2123 SetArrayToDouble0((double *)Psi1R,Dens0->TotalSize*2);
2124 SetArrayToDouble0((double *)Psip1R,Dens0->TotalSize*2);
2125
2126 if (P->Call.out[PsiOut]) {
2127 fprintf(stderr,"(%i) LockArray: ", P->Par.me);
2128 for(i=0;i<MaxDensityTypes;i++)
2129 fprintf(stderr,"(%i,%i) ",Dens0->LockArray[i],Dens0->LockCArray[i]);
2130 fprintf(stderr,"\n");
2131 }
2132
2133 // don't put the following stuff into a for loop, they might not be continuous! (preprocessor values: CurrentDensity...)
2134 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
2135 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
2136 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
2137 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
2138 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
2139 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
2140 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
2141 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
2142 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
2143
2144 // initialize the array if it is the first of all six perturbation run
2145 if ((R->DoFullCurrent == 0) && (R->CurrentMin == Perturbed_P0)) { // reset if FillDelta...() hasn't done it before
2146 debug(P,"resetting CurrentDensity...");
2147 for (B_index=0; B_index<NDIM*NDIM; B_index++) // initialize current density array
2148 SetArrayToDouble0((double *)CurrentDensity[B_index],Dens0->TotalSize*2); // DensityArray is fftw_real, no 2*LocalSizeR here!
2149 }
2150
2151 switch(type) { // set j (which is linked to the index from derivation wrt to B^{ext})
2152 case Perturbed_P0:
2153 case Perturbed_P1:
2154 case Perturbed_P2:
2155 j = type - Perturbed_P0;
2156 l_1 = crossed(j,1);
2157 l_3 = crossed(j,3);
2158 for(k=0;k<4;k++) {
2159 cross_lookup_1[k] = cross(l_1,k);
2160 cross_lookup_3[k] = cross(l_3,k);
2161 }
2162 break;
2163 case Perturbed_RxP0:
2164 case Perturbed_RxP1:
2165 case Perturbed_RxP2:
2166 j = type - Perturbed_RxP0;
2167 break;
2168 default:
2169 j = 0;
2170 Error(SomeError,"FillCurrentDensity() called while not in perturbed minimisation!");
2171 break;
2172 }
2173
2174 int wished = -1;
2175 FILE *file = fopen(P->Call.MainParameterFile,"r");
2176 if (!ParseForParameter(0,file,"Orbital",0,1,1,int_type,&wished, 1, optional)) {
2177 if (P->Call.out[ReadOut]) fprintf(stderr,"Desired Orbital missing, using: All!\n");
2178 wished = -1;
2179 } else if (wished != -1) {
2180 if (P->Call.out[ReadOut]) fprintf(stderr,"Desired Orbital is: %i.\n", wished);
2181 } else {
2182 if (P->Call.out[ReadOut]) fprintf(stderr,"Desired Orbital is: All.\n");
2183 }
2184 fclose(file);
2185
2186 // Commence grid filling
2187 for (k=Psi->TypeStartIndex[Occupied];k<Psi->TypeStartIndex[Occupied+1];k++) // every local wave functions adds up its part of the current
2188 if ((k + P->Par.me_comm_ST_PsiT*(Psi->TypeStartIndex[UnOccupied]-Psi->TypeStartIndex[Occupied]) == wished) || (wished == -1)) { // compare with global number
2189 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);
2190 //ActNum = k - Psi->TypeStartIndex[Occupied] + Psi->TypeStartIndex[1] * Psi->LocalPsiStatus[k].my_color_comm_ST_Psi; // global number of unperturbed Psi
2191 Psi0 = LevS->LPsi->LocalPsi[k]; // Local unperturbed psi
2192
2193 // now some preemptive ffts for the whole grid
2194 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Bringing |Psi0> one level up and fftransforming\n", P->Par.me);
2195 fft_Psi(P, Psi0, Psi0R, 0, Psi0symmetry); //0 // 0 //0
2196
2197 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Bringing |Psi1> one level up and fftransforming\n", P->Par.me);
2198 fft_Psi(P, LevS->LPsi->LocalPsi[Psi->TypeStartIndex[type]+k], Psi1R, 0, Psi1symmetry); //3 //0 //0
2199
2200 for (index=0;index<NDIM;index++) { // for all NDIM components of momentum operator
2201
2202 if ((P->Call.out[StepLeaderOut]) && (!index)) fprintf(stderr,"(%i) Bringing p|Psi0> one level up and fftransforming\n", P->Par.me);
2203 fft_Psi(P, Psi0, Psip0R, index, Psip0symmetry); //6 //6 //6
2204
2205 if ((P->Call.out[StepLeaderOut]) && (!index)) fprintf(stderr,"(%i) Bringing p|Psi1> one level up and fftransforming\n", P->Par.me);
2206 fft_Psi(P, LevS->LPsi->LocalPsi[Psi->TypeStartIndex[type]+k], Psip1R, index, Psip1symmetry); //4 //6 //7
2207
2208 // then for every point on the grid in real space ...
2209
2210 //if (Psi1R != (fftw_real *)Dens0->DensityArray[Temp2Density] || i0<0 || i0>=Dens0->LocalSizeR) Error(SomeError,"fft_Psi: Psi1R corrupted");
2211 //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]); //
2212 //if (Psip1R != (fftw_real *)Dens0->DensityCArray[Temp2Density] || i0<0 || i0>=Dens0->LocalSizeR) Error(SomeError,"fft_Psi: Psip1R corrupted");
2213 //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]); //
2214
2215 switch(type) {
2216 case Perturbed_P0:
2217 case Perturbed_P1:
2218 case Perturbed_P2:
2219/* // evaluate factor to compensate r x normalized phi(r) against normalized phi(rxp)
2220 factor = 0.;
2221 for (n0=0;n0<N0;n0++) // only local points on x axis
2222 for (n[1]=0;n[1]<N[1];n[1]++)
2223 for (n[2]=0;n[2]<N[2];n[2]++) {
2224 i0 = n[2]+N[2]*(n[1]+N[1]*n0);
2225 n[0]=n0 + N0*myPE; // global relative coordinate: due to partitoning of x-axis in PEPGamma>1 case
2226 fac[0] = (double)n[0]/(double)N[0];
2227 fac[1] = (double)n[1]/(double)N[1];
2228 fac[2] = (double)n[2]/(double)N[2];
2229 RMat33Vec3(x, Lat->RealBasis, fac); // relative coordinate times basis matrix gives absolute ones
2230 MinImageConv(Lat, x, Psi->AddData[k].WannierCentre, X)
2231 for (i=0;i<NDIM;i++) // build gauge-translated r_bar evaluation point
2232 r_bar[i] = sawtooth(Lat,X,i);
2233// ShiftGaugeOrigin(P,truedist(Lat, x[i], Psi->AddData[k].WannierCentre[i], i),i);
2234 //truedist(Lat, x[i], Psi->AddData[k].WannierCentre[i], i);
2235 factor += Psi1R[i0] * (r_bar[cross_lookup_1[0]] * Psi1R[i0]);
2236 }
2237 MPI_Allreduce (&factor, &Factor, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi);
2238 Factor *= R->FactorDensityR; // discrete integration constant
2239 fprintf(stderr,"(%i) normalization factor of Phi^(RxP%i)_{%i} is %lg\n", P->Par.me, type, k, Factor);
2240 Factor = 1./sqrt(fabs(Factor)); //Factor/fabs(Factor) */
2241 Factor = 1.;
2242 for (n0=0;n0<N0;n0++) // only local points on x axis
2243 for (n[1]=0;n[1]<N[1];n[1]++)
2244 for (n[2]=0;n[2]<N[2];n[2]++) {
2245 i0 = n[2]+N[2]*(n[1]+N[1]*n0);
2246 n[0]=n0 + N0*myPE; // global relative coordinate: due to partitoning of x-axis in PEPGamma>1 case
2247 fac[0] = (double)n[0]/(double)N[0];
2248 fac[1] = (double)n[1]/(double)N[1];
2249 fac[2] = (double)n[2]/(double)N[2];
2250 RMat33Vec3(x, Lat->RealBasis, fac); // relative coordinate times basis matrix gives absolute ones
2251 for (i=0;i<NDIM;i++) // build gauge-translated r_bar evaluation point
2252 r_bar[i] =
2253 sawtooth(Lat,MinImageConv(Lat, x[i], Psi->AddData[k].WannierCentre[i], i),i);
2254// ShiftGaugeOrigin(P,truedist(Lat, x[i], Psi->AddData[k].WannierCentre[i], i),i);
2255 //truedist(Lat, x[i], Psi->AddData[k].WannierCentre[i], i);
2256 Current = Psip0R[i0] * (r_bar[cross_lookup_1[0]] * Psi1R[i0]);
2257 Current += (Psi0R[i0] * r_bar[cross_lookup_1[0]] * Psip1R[i0]);
2258 Current *= .5 * UnitsFactor * Psi->LocalPsiStatus[k].PsiFactor * R->FactorDensityR; // factor confirmed, see CalculateOneDensityR() and InitDensityCalculation()
2259 ////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");
2260 CurrentDensity[index+l_1*NDIM][i0] -= Current; // note: sign of cross product resides in Current itself (here: plus)
2261 Current = - Psip0R[i0] * (r_bar[cross_lookup_3[2]] * Psi1R[i0]);
2262 Current += - (Psi0R[i0] * r_bar[cross_lookup_3[2]] * Psip1R[i0]);
2263 Current *= .5 * UnitsFactor * Psi->LocalPsiStatus[k].PsiFactor * R->FactorDensityR; // factor confirmed, see CalculateOneDensityR() and InitDensityCalculation()
2264 ////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");
2265 CurrentDensity[index+l_3*NDIM][i0] -= Current; // note: sign of cross product resides in Current itself (here: minus)
2266 }
2267 break;
2268 case Perturbed_RxP0:
2269 case Perturbed_RxP1:
2270 case Perturbed_RxP2:
2271 for (n0=0;n0<N0;n0++) // only local points on x axis
2272 for (n[1]=0;n[1]<N[1];n[1]++)
2273 for (n[2]=0;n[2]<N[2];n[2]++) {
2274 i0 = n[2]+N[2]*(n[1]+N[1]*n0);
2275 Current = (Psip0R[i0] * Psi1R[i0] + Psi0R[i0] * Psip1R[i0]);
2276 Current *= .5 * UnitsFactor * Psi->LocalPsiStatus[k].PsiFactor * R->FactorDensityR; // factor confirmed, see CalculateOneDensityR() and InitDensityCalculation()
2277 ////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");
2278 CurrentDensity[index+j*NDIM][i0] += Current;
2279 }
2280 break;
2281 default:
2282 break;
2283 }
2284 }
2285 //OutputCurrentDensity(P);
2286 }
2287
2288 //debug(P,"Unlocking arrays");
2289 //debug(P,"GapDensity");
2290 UnLockDensityArray(Dens0,GapDensity,real); // Psi0R
2291 //debug(P,"GapLocalDensity");
2292 UnLockDensityArray(Dens0,GapLocalDensity,real); // Psip0R
2293 //debug(P,"Temp2Density");
2294 UnLockDensityArray(Dens0,Temp2Density,real); // Psi1R
2295
2296// if (P->Call.out[StepLeaderOut])
2297// fprintf(stderr,"\n\n");
2298
2299 //debug(P,"MPI operation");
2300 // and in the end gather partial densities from other processes
2301 if (type == Perturbed_RxP2) // exchange all (due to shared wave functions) only after last pertubation run
2302 for (index=0;index<NDIM*NDIM;index++) {
2303 //if (tempArray != (fftw_real *)Dens0->DensityCArray[Temp2Density]) Error(SomeError,"FillCurrentDensity: tempArray corrupted");
2304 //debug(P,"tempArray to zero");
2305 SetArrayToDouble0((double *)tempArray, Dens0->TotalSize*2);
2306 ////if (CurrentDensity[index] != (fftw_real *) Dens0->DensityArray[CurrentDensity0 + index]) Error(SomeError,"FillCurrentDensity: CurrentDensity[] corrupted");
2307 //debug(P,"CurrentDensity exchange");
2308 MPI_Allreduce( CurrentDensity[index], tempArray, Dens0->LocalSizeR, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_PsiT); // gather results from all wave functions ...
2309 switch(Psi->PsiST) { // ... and also from SpinUp/Downs
2310 default:
2311 //debug(P,"CurrentDensity = tempArray");
2312 for (i=0;i<Dens0->LocalSizeR;i++) {
2313 ////if (CurrentDensity[index] != (fftw_real *) Dens0->DensityArray[CurrentDensity0 + index] || i<0 || i>=Dens0->LocalSizeR) Error(SomeError,"FillCurrentDensity: CurrentDensity[] corrupted");
2314 CurrentDensity[index][i] = tempArray[i];
2315 }
2316 break;
2317 case SpinUp:
2318 //debug(P,"CurrentDensity exchange spinup");
2319 MPI_Sendrecv(tempArray, Dens0->LocalSizeR, MPI_DOUBLE, P->Par.me_comm_ST, CurrentTag1,
2320 CurrentDensity[index], Dens0->LocalSizeR, MPI_DOUBLE, P->Par.me_comm_ST, CurrentTag2, P->Par.comm_STInter, &status );
2321 //debug(P,"CurrentDensity += tempArray");
2322 for (i=0;i<Dens0->LocalSizeR;i++) {
2323 ////if (CurrentDensity[index] != (fftw_real *) Dens0->DensityArray[CurrentDensity0 + index] || i<0 || i>=Dens0->LocalSizeR) Error(SomeError,"FillCurrentDensity: CurrentDensity[] corrupted");
2324 CurrentDensity[index][i] += tempArray[i];
2325 }
2326 break;
2327 case SpinDown:
2328 //debug(P,"CurrentDensity exchange spindown");
2329 MPI_Sendrecv(tempArray, Dens0->LocalSizeR, MPI_DOUBLE, P->Par.me_comm_ST, CurrentTag2,
2330 CurrentDensity[index], Dens0->LocalSizeR, MPI_DOUBLE, P->Par.me_comm_ST, CurrentTag1, P->Par.comm_STInter, &status );
2331 //debug(P,"CurrentDensity += tempArray");
2332 for (i=0;i<Dens0->LocalSizeR;i++) {
2333 ////if (CurrentDensity[index] != (fftw_real *) Dens0->DensityArray[CurrentDensity0 + index] || i<0 || i>=Dens0->LocalSizeR) Error(SomeError,"FillCurrentDensity: CurrentDensity[] corrupted");
2334 CurrentDensity[index][i] += tempArray[i];
2335 }
2336 break;
2337 }
2338 }
2339 //debug(P,"Temp2Density");
2340 UnLockDensityArray(Dens0,Temp2Density,imag); // Psip1R and tempArray
2341 //debug(P,"CurrentDensity end");
2342}
2343
2344/** Structure holding Problem at hand and two indices, defining the greens function to be inverted.
2345 */
2346struct params
2347{
2348 struct Problem *P;
2349 int *k;
2350 int *l;
2351 int *iter;
2352 fftw_complex *x_l;
2353};
2354
2355/** Wrapper function to solve G_kl x = b for x.
2356 * \param *x above x
2357 * \param *param additional parameters, here Problem at hand
2358 * \return evaluated to be minimized functional \f$\frac{1}{2}x \cdot Ax - xb\f$ at \a x on return
2359 */
2360static double DeltaCurrent_f(const gsl_vector * x, void * param)
2361{
2362 struct Problem *P = ((struct params *)param)->P;
2363 struct RunStruct *R = &P->R;
2364 struct LatticeLevel *LevS = R->LevS;
2365 struct Psis *Psi = &P->Lat.Psi;
2366 struct PseudoPot *PP = &P->PP;
2367 const double PsiFactor = Psi->AllPsiStatus[*((struct params *)param)->k].PsiFactor;
2368 double result = 0.;
2369 fftw_complex *TempPsi = LevS->LPsi->TempPsi;
2370 fftw_complex *TempPsi2 = LevS->LPsi->TempPsi2;
2371 int u;
2372
2373 //fprintf(stderr,"Evaluating f(%i,%i) for %i-th time\n", *((struct params *)param)->k, *((struct params *)param)->l, *((struct params *)param)->iter);
2374
2375 // extract gsl_vector
2376 for (u=0;u<LevS->MaxG;u++) {
2377 TempPsi[u].re = gsl_vector_get(x, 2*u);
2378 TempPsi[u].im = gsl_vector_get(x, 2*u+1);
2379 }
2380 // generate fnl
2381 CalculateCDfnl(P, TempPsi, PP->CDfnl); // calculate needed non-local form factors
2382 // Apply Hamiltonian to x
2383 ApplyTotalHamiltonian(P,TempPsi,TempPsi2, PP->CDfnl,PsiFactor,0);
2384 // take scalar product to get eigen value
2385 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]);
2386 return result;
2387}
2388
2389/** Wrapper function to solve G_kl x = b for x.
2390 * \param *x above x
2391 * \param *param additional parameters, here Problem at hand
2392 * \param *g gradient vector on return
2393 * \return error code
2394 */
2395static void DeltaCurrent_df(const gsl_vector * x, void * param, gsl_vector * g)
2396{
2397 struct Problem *P = ((struct params *)param)->P;
2398 struct RunStruct *R = &P->R;
2399 struct LatticeLevel *LevS = R->LevS;
2400 struct Psis *Psi = &P->Lat.Psi;
2401 struct PseudoPot *PP = &P->PP;
2402 const double PsiFactor = Psi->AllPsiStatus[*((struct params *)param)->k].PsiFactor;
2403 fftw_complex *TempPsi = LevS->LPsi->TempPsi;
2404 fftw_complex *TempPsi2 = LevS->LPsi->TempPsi2;
2405 fftw_complex *x_l = ((struct params *)param)->x_l;
2406 int u;
2407
2408 //fprintf(stderr,"Evaluating df(%i,%i) for %i-th time\n", *((struct params *)param)->k, *((struct params *)param)->l, *((struct params *)param)->iter);
2409
2410 // extract gsl_vector
2411 for (u=0;u<LevS->MaxG;u++) {
2412 TempPsi[u].re = gsl_vector_get(x, 2*u);
2413 TempPsi[u].im = gsl_vector_get(x, 2*u+1);
2414 }
2415 // generate fnl
2416 CalculateCDfnl(P, TempPsi, PP->CDfnl); // calculate needed non-local form factors
2417 // Apply Hamiltonian to x
2418 ApplyTotalHamiltonian(P,TempPsi,TempPsi2, PP->CDfnl,PsiFactor,0);
2419 // put into returning vector
2420 for (u=0;u<LevS->MaxG;u++) {
2421 gsl_vector_set(g, 2*u, TempPsi2[u].re - x_l[u].re);
2422 gsl_vector_set(g, 2*u+1, TempPsi2[u].im - x_l[u].im);
2423 }
2424}
2425
2426/** Wrapper function to solve G_kl x = b for x.
2427 * \param *x above x
2428 * \param *param additional parameters, here Problem at hand
2429 * \param *f evaluated to be minimized functional \f$\frac{1}{2}x \cdot Ax - xb\f$ at \a x on return
2430 * \param *g gradient vector on return
2431 * \return error code
2432 */
2433static void DeltaCurrent_fdf(const gsl_vector * x, void * param, double * f, gsl_vector * g)
2434{
2435 struct Problem *P = ((struct params *)param)->P;
2436 struct RunStruct *R = &P->R;
2437 struct LatticeLevel *LevS = R->LevS;
2438 struct Psis *Psi = &P->Lat.Psi;
2439 struct PseudoPot *PP = &P->PP;
2440 const double PsiFactor = Psi->AllPsiStatus[*((struct params *)param)->k].PsiFactor;
2441 fftw_complex *TempPsi = LevS->LPsi->TempPsi;
2442 fftw_complex *TempPsi2 = LevS->LPsi->TempPsi2;
2443 fftw_complex *x_l = ((struct params *)param)->x_l;
2444 int u;
2445
2446 //fprintf(stderr,"Evaluating fdf(%i,%i) for %i-th time\n", *((struct params *)param)->k, *((struct params *)param)->l, *((struct params *)param)->iter);
2447
2448 // extract gsl_vector
2449 for (u=0;u<LevS->MaxG;u++) {
2450 TempPsi[u].re = gsl_vector_get(x, 2*u);
2451 TempPsi[u].im = gsl_vector_get(x, 2*u+1);
2452 }
2453 // generate fnl
2454 CalculateCDfnl(P, TempPsi, PP->CDfnl); // calculate needed non-local form factors
2455 // Apply Hamiltonian to x
2456 ApplyTotalHamiltonian(P,TempPsi,TempPsi2, PP->CDfnl,PsiFactor,0);
2457 // put into returning vector
2458 for (u=0;u<LevS->MaxG;u++) {
2459 gsl_vector_set(g, 2*u, TempPsi[u].re - x_l[u].re);
2460 gsl_vector_set(g, 2*u+1, TempPsi[u].im - x_l[u].im);
2461 }
2462
2463 *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]);
2464}
2465
2466/** Evaluates the \f$\Delta j_k(r')\f$ component of the current density.
2467 * \f[
2468 * \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
2469 * \f]
2470 * \param *P Problem at hand
2471 * \note result has not yet been MPI_Allreduced for ParallelSimulationData#comm_ST_inter or ParallelSimulationData#comm_ST_PsiT groups!
2472 * \warning the routine is checked but does not yet produce sensible results.
2473 */
2474void FillDeltaCurrentDensity(struct Problem *P)
2475{
2476 struct Lattice *Lat = &P->Lat;
2477 struct RunStruct *R = &P->R;
2478 struct Psis *Psi = &Lat->Psi;
2479 struct LatticeLevel *Lev0 = R->Lev0;
2480 struct LatticeLevel *LevS = R->LevS;
2481 struct Density *Dens0 = Lev0->Dens;
2482 int i,j,s;
2483 int k,l,u, in, dex, index,i0;
2484 //const int Num = Psi->NoOfPsis;
2485 int RecvSource;
2486 MPI_Status status;
2487 struct OnePsiElement *OnePsiB, *LOnePsiB, *OnePsiA, *LOnePsiA;
2488 const int ElementSize = (sizeof(fftw_complex) / sizeof(double));
2489 int n[NDIM], n0;
2490 int N[NDIM];
2491 N[0] = Lev0->Plan0.plan->N[0];
2492 N[1] = Lev0->Plan0.plan->N[1];
2493 N[2] = Lev0->Plan0.plan->N[2];
2494 const int N0 = Lev0->Plan0.plan->local_nx;
2495 fftw_complex *LPsiDatB;
2496 fftw_complex *Psi0, *Psi1;
2497 fftw_real *Psi0R, *Psip0R;
2498 fftw_real *Psi1R, *Psip1R;
2499 fftw_complex *x_l = LevS->LPsi->TempPsi;//, **x_l_bak;
2500 fftw_real *CurrentDensity[NDIM*NDIM];
2501 int mem_avail, MEM_avail;
2502 double Current;
2503 const double UnitsFactor = 1.;
2504 int cross_lookup[4];
2505 struct params param;
2506 double factor; // temporary factor in Psi1 pre-evaluation
2507
2508 LockDensityArray(Dens0,GapDensity,real); // Psi0R
2509 LockDensityArray(Dens0,GapLocalDensity,real); // Psip0R
2510 LockDensityArray(Dens0,Temp2Density,imag); // Psi1
2511 LockDensityArray(Dens0,GapUpDensity,real); // Psi1R
2512 LockDensityArray(Dens0,GapDownDensity,real); // Psip1R
2513
2514 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
2515 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
2516 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
2517 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
2518 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
2519 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
2520 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
2521 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
2522 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
2523
2524 Psi0R = (fftw_real *)Dens0->DensityArray[GapDensity];
2525 Psip0R = (fftw_real *)Dens0->DensityArray[GapLocalDensity];
2526 Psi1 = (fftw_complex *) Dens0->DensityCArray[Temp2Density];
2527 Psi1R = (fftw_real *)Dens0->DensityArray[GapUpDensity];
2528 Psip1R = (fftw_real *)Dens0->DensityArray[GapDownDensity];
2529
2530// if (R->CurrentMin == Perturbed_P0)
2531// for (B_index=0; B_index<NDIM*NDIM; B_index++) { // initialize current density array
2532// debug(P,"resetting CurrentDensity...");
2533// SetArrayToDouble0((double *)CurrentDensity[B_index],Dens0->TotalSize*2); // DensityArray is fftw_real, no 2*LocalSizeR here!
2534// }
2535 //if (Psi1 != (fftw_complex *) Dens0->DensityCArray[Temp2Density]) Error(SomeError,"FillDeltaCurrentDensity: Psi1 corrupted");
2536 SetArrayToDouble0((double *)Psi1,2*Dens0->TotalSize);
2537
2538// gsl_vector *x = gsl_vector_alloc(Num);
2539// gsl_matrix *G = gsl_matrix_alloc(Num,Num);
2540// gsl_permutation *p = gsl_permutation_alloc(Num);
2541 //int signum;
2542 // begin of GSL linearer CG solver stuff
2543 int iter, Status;
2544
2545 const gsl_multimin_fdfminimizer_type *T;
2546 gsl_multimin_fdfminimizer *minset;
2547
2548 /* Position of the minimum (1,2). */
2549 //double par[2] = { 1.0, 2.0 };
2550
2551 gsl_vector *x;
2552 gsl_multimin_function_fdf my_func;
2553
2554 param.P = P;
2555 param.k = &k;
2556 param.l = &l;
2557 param.iter = &iter;
2558 param.x_l = x_l;
2559
2560 my_func.f = &DeltaCurrent_f;
2561 my_func.df = &DeltaCurrent_df;
2562 my_func.fdf = &DeltaCurrent_fdf;
2563 my_func.n = 2*LevS->MaxG;
2564 my_func.params = (void *)&param;
2565
2566 T = gsl_multimin_fdfminimizer_conjugate_pr;
2567 minset = gsl_multimin_fdfminimizer_alloc (T, 2*LevS->MaxG);
2568 x = gsl_vector_alloc (2*LevS->MaxG);
2569 // end of GSL CG stuff
2570
2571
2572// // construct G_kl = - (H^{(0)} \delta_{kl} -\langle \varphi^{(0)}_k |H^{(0)}| \varphi^{(0)}_l|rangle)^{-1} = A^{-1}
2573// for (k=0;k<Num;k++)
2574// for (l=0;l<Num;l++)
2575// gsl_matrix_set(G, k, l, k == l ? 0. : Psi->lambda[k][l]);
2576// // and decompose G_kl = L U
2577
2578 mem_avail = MEM_avail = 0;
2579// x_l_bak = x_l = (fftw_complex **) Malloc(sizeof(fftw_complex *)*Num,"FillDeltaCurrentDensity: *x_l");
2580// for (i=0;i<Num;i++) {
2581// x_l[i] = NULL;
2582// x_l[i] = (fftw_complex *) malloc(sizeof(fftw_complex)*LevS->MaxG);
2583// if (x_l[i] == NULL) {
2584// mem_avail = 1; // there was not enough memory for this node
2585// fprintf(stderr,"(%i) FillDeltaCurrentDensity: x_l[%i] ... insufficient memory.\n",P->Par.me,i);
2586// }
2587// }
2588// MPI_Allreduce(&mem_avail,&MEM_avail,1,MPI_INT,MPI_SUM,P->Par.comm_ST); // sum results from all processes
2589
2590 if (MEM_avail != 0) { // means at least node couldn't allocate sufficient memory, skipping...
2591 fprintf(stderr,"(%i) FillDeltaCurrentDensity: x_l[], not enough memory: %i! Skipping FillDeltaCurrentDensity evaluation.", P->Par.me, MEM_avail);
2592 } else {
2593 // sum over k and calculate \Delta j_k(r')
2594 k=-1;
2595 for (i=0; i < Psi->MaxPsiOfType+P->Par.Max_me_comm_ST_PsiT; i++) { // go through all wave functions
2596 //fprintf(stderr,"(%i) GlobalNo: %d\tLocalNo: %d\n", P->Par.me,Psi->AllPsiStatus[i].MyGlobalNo,Psi->AllPsiStatus[i].MyLocalNo);
2597 OnePsiA = &Psi->AllPsiStatus[i]; // grab OnePsiA
2598 if (OnePsiA->PsiType == Occupied) { // drop the extra and perturbed ones
2599 k++;
2600 if (OnePsiA->my_color_comm_ST_Psi == P->Par.my_color_comm_ST_Psi) // local?
2601 LOnePsiA = &Psi->LocalPsiStatus[OnePsiA->MyLocalNo];
2602 else
2603 LOnePsiA = NULL;
2604 if (LOnePsiA != NULL) {
2605 Psi0=LevS->LPsi->LocalPsi[OnePsiA->MyLocalNo];
2606
2607 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Bringing |Psi0> one level up and fftransforming\n", P->Par.me);
2608 //if (Psi0R != (fftw_real *)Dens0->DensityArray[GapDensity]) Error(SomeError,"FillDeltaCurrentDensity: Psi0R corrupted");
2609 fft_Psi(P,Psi0,Psi0R, 0, Psi0symmetry); //0 // 0 //0
2610
2611 for (in=0;in<NDIM;in++) { // in is the index from derivation wrt to B^{ext}
2612 l = -1;
2613 for (j=0; j < Psi->MaxPsiOfType+P->Par.Max_me_comm_ST_PsiT; j++) { // go through all wave functions
2614 OnePsiB = &Psi->AllPsiStatus[j]; // grab OnePsiA
2615 if (OnePsiB->PsiType == Occupied)
2616 l++;
2617 if ((OnePsiB != OnePsiA) && (OnePsiB->PsiType == Occupied)) { // drop the same and the extra ones
2618 if (OnePsiB->my_color_comm_ST_Psi == P->Par.my_color_comm_ST_Psi) // local?
2619 LOnePsiB = &Psi->LocalPsiStatus[OnePsiB->MyLocalNo];
2620 else
2621 LOnePsiB = NULL;
2622 if (LOnePsiB == NULL) { // if it's not local ... receive x from respective process
2623 RecvSource = OnePsiB->my_color_comm_ST_Psi;
2624 MPI_Recv( x_l, LevS->MaxG*ElementSize, MPI_DOUBLE, RecvSource, HamiltonianTag, P->Par.comm_ST_PsiT, &status );
2625 } else { // .. otherwise setup wave function as x ...
2626 // Evaluate cross product: \epsilon_{ijm} (d_k - d_l)_j p_m | \varphi^{(0)} \rangle = b_i ... and
2627 LPsiDatB=LevS->LPsi->LocalPsi[OnePsiB->MyLocalNo];
2628 //LPsiDatx=LevS->LPsi->LocalPsi[OnePsiB->MyLocalNo+Psi->TypeStartIndex[Perturbed_P0]];
2629 //CalculatePerturbationOperator_P(P,LPsiDatB,LPsiDatB_p0,cross(in,1),0);
2630 //CalculatePerturbationOperator_P(P,LPsiDatB,LPsiDatB_p1,cross(in,3),0);
2631 for (dex=0;dex<4;dex++)
2632 cross_lookup[dex] = cross(in,dex);
2633 for(s=0;s<LevS->MaxG;s++) {
2634 //if (x_l != x_l_bak || s<0 || s>LevS->MaxG) Error(SomeError,"FillDeltaCurrentDensity: x_l[] corrupted");
2635 factor =
2636 (MinImageConv(Lat,Psi->AddData[LOnePsiA->MyLocalNo].WannierCentre[cross_lookup[0]],
2637 Psi->AddData[LOnePsiB->MyLocalNo].WannierCentre[cross_lookup[0]],cross_lookup[0]) * LevS->GArray[s].G[cross_lookup[1]] -
2638 MinImageConv(Lat,Psi->AddData[LOnePsiA->MyLocalNo].WannierCentre[cross_lookup[2]],
2639 Psi->AddData[LOnePsiB->MyLocalNo].WannierCentre[cross_lookup[2]],cross_lookup[2]) * LevS->GArray[s].G[cross_lookup[3]]);
2640 x_l[s].re = factor * (-LPsiDatB[s].im); // switched due to factorization with "-i G"
2641 x_l[s].im = factor * (LPsiDatB[s].re);
2642 }
2643 // ... and send it to all other processes (Max_me... - 1)
2644 for (u=0;u<P->Par.Max_me_comm_ST_PsiT;u++)
2645 if (u != OnePsiB->my_color_comm_ST_Psi)
2646 MPI_Send( x_l, LevS->MaxG*ElementSize, MPI_DOUBLE, u, HamiltonianTag, P->Par.comm_ST_PsiT);
2647 } // x_l row is now filled (either by receiving result or evaluating it on its own)
2648 // Solve Ax = b by minimizing 1/2 xAx -xb (gradient is residual Ax - b) with conjugate gradient polak-ribiere
2649
2650 debug(P,"fill starting point x with values from b");
2651 /* Starting point, x = b */
2652 for (u=0;u<LevS->MaxG;u++) {
2653 gsl_vector_set (x, 2*u, x_l[u].re);
2654 gsl_vector_set (x, 2*u+1, x_l[u].im);
2655 }
2656
2657 gsl_multimin_fdfminimizer_set (minset, &my_func, x, 0.01, 1e-4);
2658
2659 fprintf(stderr,"(%i) Start solving for (%i,%i) and index %i\n",P->Par.me, k,l,in);
2660 // start solving
2661 iter = 0;
2662 do
2663 {
2664 iter++;
2665 Status = gsl_multimin_fdfminimizer_iterate (minset);
2666
2667 if (Status)
2668 break;
2669
2670 Status = gsl_multimin_test_gradient (minset->gradient, 1e-3);
2671
2672 if (Status == GSL_SUCCESS)
2673 fprintf (stderr,"(%i) Minimum found after %i iterations.\n", P->Par.me, iter);
2674
2675 } while (Status == GSL_CONTINUE && iter < 100);
2676
2677 debug(P,"Put solution into Psi1");
2678 // ... and what do we do now? Put solution into Psi1!
2679 for(s=0;s<LevS->MaxG;s++) {
2680 //if (Psi1 != (fftw_complex *) Dens0->DensityCArray[Temp2Density] || s<0 || s>LevS->MaxG) Error(SomeError,"FillDeltaCurrentDensity: Psi1 corrupted");
2681 Psi1[s].re = gsl_vector_get (minset->x, 2*s);
2682 Psi1[s].im = gsl_vector_get (minset->x, 2*s+1);
2683 }
2684
2685 // // Solve A^{-1} b_i = x
2686 // for(s=0;s<LevS->MaxG;s++) {
2687 // // REAL PART
2688 // // retrieve column from gathered matrix
2689 // for(u=0;u<Num;u++)
2690 // gsl_vector_set(x,u,x_l[u][s].re);
2691 //
2692 // // solve: sum_l A_{kl}^(-1) b_l (s) = x_k (s)
2693 // gsl_linalg_LU_svx (G, p, x);
2694 //
2695 // // put solution back into x_l[s]
2696 // for(u=0;u<Num;u++) {
2697 // //if (x_l != x_l_bak || s<0 || s>=LevS->MaxG) Error(SomeError,"FillDeltaCurrentDensity: x_l[] corrupted");
2698 // x_l[u][s].re = gsl_vector_get(x,u);
2699 // }
2700 //
2701 // // IMAGINARY PART
2702 // // retrieve column from gathered matrix
2703 // for(u=0;u<Num;u++)
2704 // gsl_vector_set(x,u,x_l[u][s].im);
2705 //
2706 // // solve: sum_l A_{kl}^(-1) b_l (s) = x_k (s)
2707 // gsl_linalg_LU_svx (G, p, x);
2708 //
2709 // // put solution back into x_l[s]
2710 // for(u=0;u<Num;u++) {
2711 // //if (x_l != x_l_bak || s<0 || s>=LevS->MaxG) Error(SomeError,"FillDeltaCurrentDensity: x_l[] corrupted");
2712 // x_l[u][s].im = gsl_vector_get(x,u);
2713 // }
2714 // } // now we have in x_l a vector similar to "Psi1" which we use to evaluate the current density
2715 //
2716 // // evaluate \Delta J_k ... mind the minus sign from G_kl!
2717 // // fill Psi1
2718 // for(s=0;s<LevS->MaxG;s++) {
2719 // //if (Psi1 != (fftw_complex *) Dens0->DensityCArray[Temp2Density] || s<0 || s>LevS->MaxG) Error(SomeError,"FillDeltaCurrentDensity: Psi1 corrupted");
2720 // Psi1[s].re = x_l[k][s].re;
2721 // Psi1[s].im = x_l[k][s].im;
2722 // }
2723
2724 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Bringing |Psi1> one level up and fftransforming\n", P->Par.me);
2725 //if (Psi1R != (fftw_real *)Dens0->DensityArray[GapUpDensity]) Error(SomeError,"FillDeltaCurrentDensity: Psi1R corrupted");
2726 fft_Psi(P,Psi1,Psi1R, 0, Psi1symmetry); //2 // 0 //0
2727
2728 for (index=0;index<NDIM;index++) { // for all NDIM components of momentum operator
2729
2730 if ((P->Call.out[StepLeaderOut]) && (!index)) fprintf(stderr,"(%i) Bringing p|Psi0> one level up and fftransforming\n", P->Par.me);
2731 //if (Psip0R != (fftw_real *)Dens0->DensityArray[GapLocalDensity]) Error(SomeError,"FillDeltaCurrentDensity: Psip0R corrupted");
2732 fft_Psi(P,Psi0,Psip0R, index, Psip0symmetry); //6 //6 //6
2733
2734 if ((P->Call.out[StepLeaderOut]) && (!index)) fprintf(stderr,"(%i) Bringing p|Psi1> one level up and fftransforming\n", P->Par.me);
2735 //if (Psip1R != (fftw_real *)Dens0->DensityArray[GapDownDensity]) Error(SomeError,"FillDeltaCurrentDensity: Psip1R corrupted");
2736 fft_Psi(P,Psi1,Psip1R, index, Psip1symmetry); //4 //6 //6
2737
2738 // then for every point on the grid in real space ...
2739 for (n0=0;n0<N0;n0++) // only local points on x axis
2740 for (n[1]=0;n[1]<N[1];n[1]++)
2741 for (n[2]=0;n[2]<N[2];n[2]++) {
2742 i0 = n[2]+N[2]*(n[1]+N[1]*n0);
2743 // and take the product
2744 Current = (Psip0R[i0] * Psi1R[i0] + Psi0R[i0] * Psip1R[i0]);
2745 Current *= 0.5 * UnitsFactor * Psi->AllPsiStatus[OnePsiA->MyGlobalNo].PsiFactor * R->FactorDensityR;
2746 ////if (CurrentDensity[index+in*NDIM] != (fftw_real *) Dens0->DensityArray[CurrentDensity0 + index+in*NDIM]) Error(SomeError,"FillCurrentDensity: CurrentDensity[] corrupted");
2747 //if (i0<0 || i0>=Dens0->LocalSizeR) Error(SomeError,"FillDeltaCurrentDensity: i0 out of range");
2748 //if ((index+in*NDIM)<0 || (index+in*NDIM)>=NDIM*NDIM) Error(SomeError,"FillDeltaCurrentDensity: index out of range");
2749 CurrentDensity[index+in*NDIM][i0] += Current; // minus sign is from G_kl
2750 }
2751 }
2752 }
2753 }
2754 }
2755 }
2756 }
2757 }
2758 }
2759 UnLockDensityArray(Dens0,GapDensity,real); // Psi0R
2760 UnLockDensityArray(Dens0,GapLocalDensity,real); // Psip0R
2761 UnLockDensityArray(Dens0,Temp2Density,imag); // Psi1
2762 UnLockDensityArray(Dens0,GapUpDensity,real); // Psi1R
2763 UnLockDensityArray(Dens0,GapDownDensity,real); // Psip1R
2764// for (i=0;i<Num;i++)
2765// if (x_l[i] != NULL) Free(x_l[i], "FillDeltaCurrentDensity: x_l[i]");
2766// Free(x_l, "FillDeltaCurrentDensity: x_l");
2767 gsl_multimin_fdfminimizer_free (minset);
2768 gsl_vector_free (x);
2769// gsl_matrix_free(G);
2770// gsl_permutation_free(p);
2771// gsl_vector_free(x);
2772}
2773
2774
2775/** Evaluates the overlap integral between \a state wave functions.
2776 * \f[
2777 * S_{kl} = \langle \varphi_k^{(1)} | \varphi_l^{(1)} \rangle
2778 * \f]
2779 * The scalar product is calculated via GradSP(), MPI_Allreduced among comm_ST_Psi and the result
2780 * stored in Psis#Overlap. The rows have to be MPI exchanged, as otherwise processes will add
2781 * to the TotalEnergy overlaps calculated with old wave functions - they have been minimised after
2782 * the product with exchanged coefficients was taken.
2783 * \param *P Problem at hand
2784 * \param l local number of perturbed wave function.
2785 * \param state PsiTypeTag minimisation state of wave functions to be overlapped
2786 */
2787void CalculateOverlap(struct Problem *P, const int l, const enum PsiTypeTag state)
2788{
2789 struct RunStruct *R = &P->R;
2790 struct Lattice *Lat = &(P->Lat);
2791 struct Psis *Psi = &Lat->Psi;
2792 struct LatticeLevel *LevS = R->LevS;
2793 struct OnePsiElement *OnePsiB, *LOnePsiB;
2794 fftw_complex *LPsiDatB=NULL, *LPsiDatA=NULL;
2795 const int ElementSize = (sizeof(fftw_complex) / sizeof(double));
2796 int RecvSource;
2797 MPI_Status status;
2798 int i,j,m,p;
2799 //const int l_normal = l - Psi->TypeStartIndex[state] + Psi->TypeStartIndex[Occupied];
2800 const int ActNum = l - Psi->TypeStartIndex[state] + Psi->TypeStartIndex[1] * Psi->LocalPsiStatus[l].my_color_comm_ST_Psi;
2801 double *sendbuf, *recvbuf;
2802 double tmp,TMP;
2803 const int gsize = P->Par.Max_me_comm_ST_PsiT; //number of processes in PsiT
2804 int p_num; // number of wave functions (for overlap)
2805
2806 // update overlap table after wave function has changed
2807 LPsiDatA = LevS->LPsi->LocalPsi[l];
2808 m = -1; // to access U matrix element (0..Num-1)
2809 for (j=0; j < Psi->MaxPsiOfType+P->Par.Max_me_comm_ST_PsiT; j++) { // go through all wave functions
2810 OnePsiB = &Psi->AllPsiStatus[j]; // grab OnePsiB
2811 if (OnePsiB->PsiType == state) { // drop all but the ones of current min state
2812 m++; // increase m if it is non-extra wave function
2813 if (OnePsiB->my_color_comm_ST_Psi == P->Par.my_color_comm_ST_Psi) // local?
2814 LOnePsiB = &Psi->LocalPsiStatus[OnePsiB->MyLocalNo];
2815 else
2816 LOnePsiB = NULL;
2817 if (LOnePsiB == NULL) { // if it's not local ... receive it from respective process into TempPsi
2818 RecvSource = OnePsiB->my_color_comm_ST_Psi;
2819 MPI_Recv( LevS->LPsi->TempPsi, LevS->MaxG*ElementSize, MPI_DOUBLE, RecvSource, OverlapTag, P->Par.comm_ST_PsiT, &status );
2820 LPsiDatB=LevS->LPsi->TempPsi;
2821 } else { // .. otherwise send it to all other processes (Max_me... - 1)
2822 for (p=0;p<P->Par.Max_me_comm_ST_PsiT;p++)
2823 if (p != OnePsiB->my_color_comm_ST_Psi)
2824 MPI_Send( LevS->LPsi->LocalPsi[OnePsiB->MyLocalNo], LevS->MaxG*ElementSize, MPI_DOUBLE, p, OverlapTag, P->Par.comm_ST_PsiT);
2825 LPsiDatB=LevS->LPsi->LocalPsi[OnePsiB->MyLocalNo];
2826 } // LPsiDatB is now set to the coefficients of OnePsi either stored or MPI_Received
2827
2828 tmp = GradSP(P, LevS, LPsiDatA, LPsiDatB) * sqrt(Psi->LocalPsiStatus[l].PsiFactor * OnePsiB->PsiFactor);
2829 MPI_Allreduce ( &tmp, &TMP, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi);
2830 //fprintf(stderr,"(%i) Setting Overlap [%i][%i] = %lg\n",P->Par.me, ActNum,m,TMP);
2831 Psi->Overlap[ActNum][m] = TMP; //= Psi->Overlap[m][ActNum]
2832 }
2833 }
2834
2835 // exchange newly calculated rows among PsiT
2836 p_num = (m+1) + 1; // number of Psis: one more due to ActNum
2837 sendbuf = (double *) Malloc(p_num * sizeof(double), "CalculateOverlap: sendbuf");
2838 sendbuf[0] = ActNum; // first entry is the global row number
2839 for (i=1;i<p_num;i++)
2840 sendbuf[i] = Psi->Overlap[ActNum][i-1]; // then follow up each entry of overlap row
2841 recvbuf = (double *) Malloc(gsize * p_num * sizeof(double), "CalculateOverlap: recvbuf");
2842 MPI_Allgather(sendbuf, p_num, MPI_DOUBLE, recvbuf, p_num, MPI_DOUBLE, P->Par.comm_ST_PsiT);
2843 Free(sendbuf, "CalculateOverlap: sendbuf");
2844 for (i=0;i<gsize;i++) {// extract results from other processes out of receiving buffer
2845 m = recvbuf[i*p_num]; // m is ActNum of the process whose results we've just received
2846 //fprintf(stderr,"(%i) Received row %i from process %i\n", P->Par.me, m, i);
2847 for (j=1;j<p_num;j++)
2848 Psi->Overlap[m][j-1] = Psi->Overlap[j-1][m] = recvbuf[i*p_num+j]; // put each entry into correspondent Overlap row
2849 }
2850 Free(recvbuf, "CalculateOverlap: recvbuf");
2851}
2852
2853
2854/** Calculates magnetic susceptibility from known current density.
2855 * The bulk susceptibility tensor can be expressed as a function of the current density.
2856 * \f[
2857 * \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
2858 * \f]
2859 * Thus the integral over real space and subsequent MPI_Allreduce() over results from ParallelSimulationData#comm_ST_Psi is
2860 * straightforward. Tensor is diagonalized afterwards and split into its various sub-tensors of lower rank (e.g., isometric
2861 * value is tensor of rank 0) which are printed to screen and the tensorial elements to file '....chi.csv'
2862 * \param *P Problem at hand
2863 */
2864void CalculateMagneticSusceptibility(struct Problem *P)
2865{
2866 struct RunStruct *R = &P->R;
2867 struct Lattice *Lat = &P->Lat;
2868 struct LatticeLevel *Lev0 = R->Lev0;
2869 struct Density *Dens0 = R->Lev0->Dens;
2870 struct Ions *I = &P->Ion;
2871 fftw_real *CurrentDensity[NDIM*NDIM];
2872 int in, dex, i, i0, n0;
2873 int n[NDIM];
2874 const int N0 = Lev0->Plan0.plan->local_nx;
2875 int N[NDIM];
2876 N[0] = Lev0->Plan0.plan->N[0];
2877 N[1] = Lev0->Plan0.plan->N[1];
2878 N[2] = Lev0->Plan0.plan->N[2];
2879 double chi[NDIM*NDIM],Chi[NDIM*NDIM], x[NDIM], fac[NDIM];
2880 const double discrete_factor = Lat->Volume/Lev0->MaxN;
2881 const int myPE = P->Par.me_comm_ST_Psi;
2882 double eta, delta_chi, S, A, iso;
2883 int cross_lookup[4];
2884 char filename[256];
2885 FILE *ChiFile;
2886 time_t seconds;
2887 time(&seconds); // get current time
2888
2889 // set pointers onto current density
2890 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
2891 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
2892 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
2893 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
2894 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
2895 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
2896 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
2897 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
2898 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
2899 //for(i=0;i<NDIM;i++) {
2900// field[i] = Dens0->DensityArray[TempDensity+i];
2901 //LockDensityArray(Dens0,TempDensity+i,real);
2902// SetArrayToDouble0((double *)field[i],Dens0->TotalSize*2);
2903 //}
2904 gsl_matrix_complex *H = gsl_matrix_complex_calloc(NDIM,NDIM);
2905
2906
2907 if (P->Call.out[ValueOut]) fprintf(stderr,"(%i) magnetic susceptibility tensor \\Chi_ij = \n",P->Par.me);
2908 for (in=0; in<NDIM; in++) { // index i of integrand vector component
2909 for(dex=0;dex<4;dex++) // initialise cross lookup
2910 cross_lookup[dex] = cross(in,dex);
2911 for (dex=0; dex<NDIM; dex++) { // index j of derivation wrt B field
2912 chi[in+dex*NDIM] = 0.;
2913 // do the integration over real space
2914 for(n0=0;n0<N0;n0++)
2915 for(n[1]=0;n[1]<N[1];n[1]++)
2916 for(n[2]=0;n[2]<N[2];n[2]++) {
2917 n[0]=n0 + N0*myPE; // global relative coordinate: due to partitoning of x-axis in PEPGamma>1 case
2918 fac[0] = (double)(n[0])/(double)N[0];
2919 fac[1] = (double)(n[1])/(double)N[1];
2920 fac[2] = (double)(n[2])/(double)N[2];
2921 RMat33Vec3(x, Lat->RealBasis, fac);
2922 i0 = n[2]+N[2]*(n[1]+N[1]*(n0)); // the index of current density must match LocalSizeR!
2923 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.
2924 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.
2925// if (in == dex) field[in][i0] =
2926// truedist(Lat,x[cross_lookup[0]], sqrt(Lat->RealBasisSQ[c[0]])/2.,cross_lookup[0]) * CurrentDensity[dex*NDIM+cross_lookup[1]][i0]
2927// - truedist(Lat,x[cross_lookup[2]], sqrt(Lat->RealBasisSQ[c[2]])/2.,cross_lookup[2]) * CurrentDensity[dex*NDIM+cross_lookup[3]][i0];
2928 //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]);
2929 }
2930 chi[in+dex*NDIM] *= mu0*discrete_factor/(2.*Lat->Volume); // integral factor
2931 chi[in+dex*NDIM] *= (-1625.); // empirical gauge factor ... sigh
2932 MPI_Allreduce ( &chi[in+dex*NDIM], &Chi[in+dex*NDIM], 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum "LocalSize to TotalSize"
2933 I->I[0].chi[in+dex*NDIM] = Chi[in+dex*NDIM];
2934 Chi[in+dex*NDIM] *= Lat->Volume*loschmidt_constant; // factor for _molar_ susceptibility
2935 if (P->Call.out[ValueOut]) {
2936 fprintf(stderr,"%e\t", Chi[in+dex*NDIM]);
2937 if (dex == NDIM-1) fprintf(stderr,"\n");
2938 }
2939 }
2940 }
2941 // store symmetrized matrix
2942 for (in=0;in<NDIM;in++)
2943 for (dex=0;dex<NDIM;dex++)
2944 gsl_matrix_complex_set(H,in,dex,gsl_complex_rect((Chi[in+dex*NDIM]+Chi[dex+in*NDIM])/2.,0));
2945 // output tensor to file
2946 if (P->Par.me == 0) {
2947 sprintf(filename, ".chi.L%i.csv", Lev0->LevelNo);
2948 OpenFile(P, &ChiFile, filename, "a", P->Call.out[ReadOut]);
2949 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));
2950 fprintf(ChiFile,"%lg\t", P->Lat.ECut/(Lat->LevelSizes[0]*Lat->LevelSizes[0]));
2951 for (in=0;in<NDIM*NDIM;in++)
2952 fprintf(ChiFile,"%e\t", Chi[in]);
2953 fprintf(ChiFile,"\n");
2954 fclose(ChiFile);
2955 }
2956 // diagonalize chi
2957 gsl_vector *eval = gsl_vector_alloc(NDIM);
2958 gsl_eigen_herm_workspace *w = gsl_eigen_herm_alloc(NDIM);
2959 gsl_eigen_herm(H, eval, w);
2960 gsl_eigen_herm_free(w);
2961 gsl_sort_vector(eval); // sort eigenvalues
2962 // print eigenvalues
2963 iso = 0;
2964 for (i=0;i<NDIM;i++) {
2965 I->I[0].chi_PAS[i] = gsl_vector_get(eval,i);
2966 iso += Chi[i+i*NDIM]/3.;
2967 }
2968 eta = (gsl_vector_get(eval,1)-gsl_vector_get(eval,0))/(gsl_vector_get(eval,2)-iso);
2969 delta_chi = gsl_vector_get(eval,2) - 0.5*(gsl_vector_get(eval,0)+gsl_vector_get(eval,1));
2970 S = (delta_chi*delta_chi)*(1+1./3.*eta*eta);
2971 A = 0.;
2972 for (i=0;i<NDIM;i++) {
2973 in = cross(i,0);
2974 dex = cross(i,1);
2975 A += pow(-1,i)*pow(0.5*(Chi[in+dex*NDIM]-Chi[dex+in*NDIM]),2);
2976 }
2977 if (P->Call.out[ValueOut]) {
2978 fprintf(stderr,"(%i) converted to Principal Axis System\n==================\nDiagonal entries:", P->Par.me);
2979 for (i=0;i<NDIM;i++)
2980 fprintf(stderr,"\t%lg",gsl_vector_get(eval,i));
2981 fprintf(stderr,"\nsusceptib. : %e\n", iso);
2982 fprintf(stderr,"anisotropy : %e\n", delta_chi);
2983 fprintf(stderr,"asymmetry : %e\n", eta);
2984 fprintf(stderr,"S : %e\n", S);
2985 fprintf(stderr,"A : %e\n", A);
2986 fprintf(stderr,"==================\n");
2987 }
2988 //for(i=0;i<NDIM;i++)
2989 //UnLockDensityArray(Dens0,TempDensity+i,real);
2990 gsl_vector_free(eval);
2991 gsl_matrix_complex_free(H);
2992}
2993
2994/** Fouriertransforms all nine current density components and calculates shielding tensor.
2995 * \f[
2996 * \sigma_{ij} = \left ( \frac{G}{|G|^2} \times J_i(G) \right )_j
2997 * \f]
2998 * The CurrentDensity has to be fouriertransformed to reciprocal subspace in order to be useful, and the final
2999 * product \f$\sigma_{ij}(G)\f$ has to be back-transformed to real space. However, the shielding is the only evaluated
3000 * at the grid points and not where the real ion position is. The shieldings there are interpolated between the eight
3001 * adjacent grid points by a simple linear weighting. Afterwards follows the same analaysis and printout of the rank-2-tensor
3002 * as in the case of CalculateMagneticShielding().
3003 * \param *P Problem at hand
3004 * \note Lots of arrays are used temporarily during the routine for the fft'ed Current density tensor.
3005 * \note MagneticSusceptibility is needed for G=0-component and thus has to be computed beforehand
3006 */
3007void CalculateChemicalShieldingByReciprocalCurrentDensity(struct Problem *P)
3008{
3009 struct RunStruct *R = &P->R;
3010 struct Lattice *Lat = &P->Lat;
3011 struct LatticeLevel *Lev0 = R->Lev0;
3012 struct Ions *I = &P->Ion;
3013 struct Density *Dens0 = Lev0->Dens;
3014 struct OneGData *GArray = Lev0->GArray;
3015 struct fft_plan_3d *plan = Lat->plan;
3016 fftw_real *CurrentDensity[NDIM*NDIM];
3017 fftw_complex *CurrentDensityC[NDIM*NDIM];
3018 fftw_complex *work = (fftw_complex *)Dens0->DensityCArray[TempDensity];
3019 //fftw_complex *sigma_imag = (fftw_complex *)Dens0->DensityCArray[Temp2Density];
3020 //fftw_real *sigma_real = (fftw_real *)sigma_imag;
3021 fftw_complex *sigma_imag[NDIM_NDIM];
3022 fftw_real *sigma_real[NDIM_NDIM];
3023 double sigma,Sigma;
3024 int it, ion, in, dex, g, n[2][NDIM], Index, i;
3025 //const double FFTfactor = 1.;///Lev0->MaxN;
3026 double eta, delta_sigma, S, A, iso, tmp;
3027 FILE *SigmaFile;
3028 char suffixsigma[255];
3029 double x[2][NDIM];
3030 const int myPE = P->Par.me_comm_ST_Psi;
3031 int N[NDIM];
3032 int cross_lookup[4]; // cross lookup table
3033 N[0] = Lev0->Plan0.plan->N[0];
3034 N[1] = Lev0->Plan0.plan->N[1];
3035 N[2] = Lev0->Plan0.plan->N[2];
3036 const int N0 = Lev0->Plan0.plan->local_nx;
3037 const double factorDC = R->FactorDensityC;
3038 gsl_matrix_complex *H = gsl_matrix_complex_calloc(NDIM,NDIM);
3039
3040 time_t seconds;
3041 time(&seconds); // get current time
3042
3043 // inverse Fourier transform current densities
3044 CurrentDensityC[0] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity0];
3045 CurrentDensityC[1] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity1];
3046 CurrentDensityC[2] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity2];
3047 CurrentDensityC[3] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity3];
3048 CurrentDensityC[4] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity4];
3049 CurrentDensityC[5] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity5];
3050 CurrentDensityC[6] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity6];
3051 CurrentDensityC[7] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity7];
3052 CurrentDensityC[8] = (fftw_complex *) Dens0->DensityCArray[CurrentDensity8];
3053 // don't put the following stuff into a for loop, they are not continuous! (preprocessor values CurrentDensity.)
3054 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
3055 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
3056 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
3057 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
3058 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
3059 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
3060 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
3061 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
3062 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
3063
3064 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Checking J_{ij} (G=0) = 0 for each i,j ... \n",P->Par.me);
3065 for (in=0;in<NDIM*NDIM;in++) {
3066 CalculateOneDensityC(Lat, R->LevS, Dens0, CurrentDensity[in], CurrentDensityC[in], factorDC);
3067 tmp = sqrt(CurrentDensityC[in][0].re*CurrentDensityC[in][0].re+CurrentDensityC[in][0].im*CurrentDensityC[in][0].im);
3068 if (GArray[0].GSq < MYEPSILON) {
3069 if (in % NDIM == 0) fprintf(stderr,"(%i) ",P->Par.me);
3070 if (tmp > MYEPSILON) {
3071 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);
3072 } else {
3073 fprintf(stderr,"J_{%i,%i} ok\t", in / NDIM, in%NDIM);
3074 }
3075 if (in % NDIM == (NDIM-1)) fprintf(stderr,"\n");
3076 }
3077 }
3078
3079 for (in=0;in<NDIM*NDIM;in++) {
3080 LockDensityArray(Dens0,in,real); // Psi1R
3081 sigma_imag[in] = (fftw_complex *) Dens0->DensityArray[in];
3082 sigma_real[in] = (fftw_real *) sigma_imag[in];
3083 }
3084
3085 LockDensityArray(Dens0,TempDensity,imag); // work
3086 LockDensityArray(Dens0,Temp2Density,imag); // tempdestRC and field
3087 // go through reciprocal nodes and calculate shielding tensor sigma
3088 for (in=0; in<NDIM; in++) {// index i of vector component in integrand
3089 for(dex=0;dex<4;dex++) // initialise cross lookup
3090 cross_lookup[dex] = cross(in,dex);
3091 for (dex=0; dex<NDIM; dex++) { // index j of B component derivation in current density tensor
3092 //if (tempdestRC != (fftw_complex *)Dens0->DensityCArray[Temp2Density]) Error(SomeError,"CalculateChemicalShieldingByReciprocalCurrentDensity: tempdestRC corrupted");
3093 SetArrayToDouble0((double *)sigma_imag[in+dex*NDIM],Dens0->TotalSize*2);
3094 for (g=0; g < Lev0->MaxG; g++)
3095 if (GArray[g].GSq > MYEPSILON) { // skip due to divisor
3096 Index = GArray[g].Index; // re = im, im = -re due to "i" in formula
3097 //if (tempdestRC != (fftw_complex *)Dens0->DensityCArray[Temp2Density] || Index<0 || Index>=Dens0->LocalSizeC) Error(SomeError,"CalculateChemicalShieldingByReciprocalCurrentDensity: tempdestRC corrupted");
3098 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;
3099 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;
3100 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;
3101 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;
3102 } else { // G=0-component stems from magnetic susceptibility
3103 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]);
3104 }
3105 for (g=0; g<Lev0->MaxDoubleG; g++) { // apply symmetry
3106 //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");
3107 sigma_imag[in+dex*NDIM][Lev0->DoubleG[2*g+1]].re = sigma_imag[in+dex*NDIM][Lev0->DoubleG[2*g]].re;
3108 sigma_imag[in+dex*NDIM][Lev0->DoubleG[2*g+1]].im = -sigma_imag[in+dex*NDIM][Lev0->DoubleG[2*g]].im;
3109 }
3110 // fourier transformation of sigma
3111 //if (tempdestRC != (fftw_complex *)Dens0->DensityCArray[Temp2Density]) Error(SomeError,"CalculateChemicalShieldingByReciprocalCurrentDensity: tempdestRC corrupted");
3112 fft_3d_complex_to_real(plan, Lev0->LevelNo, FFTNF1, sigma_imag[in+dex*NDIM], work);
3113
3114 for (it=0; it < I->Max_Types; it++) { // integration over all types
3115 for (ion=0; ion < I->I[it].Max_IonsOfType; ion++) { // and each ion of type
3116 // read transformed sigma at core position and MPI_Allreduce
3117 for (g=0;g<NDIM;g++) {
3118 n[0][g] = floor(I->I[it].R[NDIM*ion+g]/sqrt(Lat->RealBasisSQ[g])*(double)N[g]);
3119 n[1][g] = ceil(I->I[it].R[NDIM*ion+g]/sqrt(Lat->RealBasisSQ[g])*(double)N[g]);
3120 x[1][g] = I->I[it].R[NDIM*ion+g]/sqrt(Lat->RealBasisSQ[g])*(double)N[g] - (double)n[0][g];
3121 x[0][g] = 1. - x[1][g];
3122 //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]);
3123 }
3124 sigma = 0.;
3125 for (i=0;i<2;i++) { // interpolate linearly between adjacent grid points per axis
3126 if ((n[i][0] >= N0*myPE) && (n[i][0] < N0*(myPE+1))) {
3127// 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);
3128 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
3129 //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);
3130 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
3131 //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);
3132 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
3133 //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);
3134 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
3135 //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);
3136 }
3137 }
3138 sigma *= -R->FactorDensityR; // factor from inverse fft? (and its defined as negative proportionaly factor)
3139 MPI_Allreduce ( &sigma, &Sigma, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum local to total
3140 I->I[it].sigma_rezi[ion][in+dex*NDIM] = Sigma;
3141 }
3142 }
3143 // fabs() all sigma values, as we need them as a positive density: OutputVis plots them in logarithmic scale and
3144 // thus cannot deal with negative values!
3145 for (i=0; i< Dens0->LocalSizeR; i++)
3146 sigma_real[in+dex*NDIM][i] = fabs(sigma_real[in+dex*NDIM][i]);
3147 }
3148 }
3149 UnLockDensityArray(Dens0,TempDensity,imag); // work
3150 UnLockDensityArray(Dens0,Temp2Density,imag); // tempdestRC and field
3151
3152 // output tensor to file
3153 if (P->Par.me == 0) {
3154 sprintf(&suffixsigma[0], ".sigma_chi_rezi.L%i.csv", Lev0->LevelNo);
3155 OpenFile(P, &SigmaFile, suffixsigma, "a", P->Call.out[ReadOut]);
3156 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));
3157 fprintf(SigmaFile,"%lg\t", P->Lat.ECut/(Lat->LevelSizes[0]*Lat->LevelSizes[0]));
3158 for (in=0;in<NDIM;in++)
3159 for (dex=0;dex<NDIM;dex++)
3160 fprintf(SigmaFile,"%e\t", GSL_REAL(gsl_matrix_complex_get(H,in,dex)));
3161 fprintf(SigmaFile,"\n");
3162 fclose(SigmaFile);
3163 }
3164
3165 gsl_vector *eval = gsl_vector_alloc(NDIM);
3166 gsl_eigen_herm_workspace *w = gsl_eigen_herm_alloc(NDIM);
3167
3168 for (it=0; it < I->Max_Types; it++) { // integration over all types
3169 for (ion=0; ion < I->I[it].Max_IonsOfType; ion++) { // and each ion of type
3170 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);
3171 for (in=0; in<NDIM; in++) { // index i of vector component in integrand
3172 for (dex=0; dex<NDIM; dex++) {// index j of B component derivation in current density tensor
3173 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));
3174 if (P->Call.out[ValueOut]) fprintf(stderr,"%e\t", I->I[it].sigma_rezi[ion][in+dex*NDIM]);
3175 }
3176 if (P->Call.out[ValueOut]) fprintf(stderr,"\n");
3177 }
3178 // output tensor to file
3179 if (P->Par.me == 0) {
3180 sprintf(&suffixsigma[0], ".sigma_i%i_%s_rezi.L%i.csv", ion, I->I[it].Symbol, Lev0->LevelNo);
3181 OpenFile(P, &SigmaFile, suffixsigma, "a", P->Call.out[ReadOut]);
3182 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));
3183 fprintf(SigmaFile,"%lg\t", P->Lat.ECut/(Lat->LevelSizes[0]*Lat->LevelSizes[0]));
3184 for (in=0;in<NDIM;in++)
3185 for (dex=0;dex<NDIM;dex++)
3186 fprintf(SigmaFile,"%e\t", I->I[it].sigma_rezi[ion][in+dex*NDIM]);
3187 fprintf(SigmaFile,"\n");
3188 fclose(SigmaFile);
3189 }
3190 // diagonalize sigma
3191 gsl_eigen_herm(H, eval, w);
3192 gsl_sort_vector(eval); // sort eigenvalues
3193// print eigenvalues
3194// if (P->Call.out[ValueOut]) {
3195// fprintf(stderr,"(%i) diagonal shielding for Ion %i of element %s:", P->Par.me, ion, I->I[it].Name);
3196// for (in=0;in<NDIM;in++)
3197// fprintf(stderr,"\t%lg",gsl_vector_get(eval,in));
3198// fprintf(stderr,"\n\n");
3199// }
3200 iso = 0.;
3201 for (i=0;i<NDIM;i++) {
3202 I->I[it].sigma_rezi_PAS[ion][i] = gsl_vector_get(eval,i);
3203 iso += I->I[it].sigma_rezi[ion][i+i*NDIM]/3.;
3204 }
3205 eta = (gsl_vector_get(eval,1)-gsl_vector_get(eval,0))/(gsl_vector_get(eval,2)-iso);
3206 delta_sigma = gsl_vector_get(eval,2) - 0.5*(gsl_vector_get(eval,0)+gsl_vector_get(eval,1));
3207 S = (delta_sigma*delta_sigma)*(1+1./3.*eta*eta);
3208 A = 0.;
3209 for (i=0;i<NDIM;i++) {
3210 in = cross(i,0);
3211 dex = cross(i,1);
3212 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);
3213 }
3214 if (P->Call.out[ValueOut]) {
3215 fprintf(stderr,"(%i) converted to Principal Axis System\n==================\nDiagonal entries:", P->Par.me);
3216 for (i=0;i<NDIM;i++)
3217 fprintf(stderr,"\t%lg",gsl_vector_get(eval,i));
3218 fprintf(stderr,"\nshielding : %e\n", iso);
3219 fprintf(stderr,"anisotropy : %e\n", delta_sigma);
3220 fprintf(stderr,"asymmetry : %e\n", eta);
3221 fprintf(stderr,"S : %e\n", S);
3222 fprintf(stderr,"A : %e\n", A);
3223 fprintf(stderr,"==================\n");
3224
3225 }
3226 }
3227 }
3228
3229 // Output of magnetic field densities for each direction
3230 for (i=0;i<NDIM*NDIM;i++)
3231 OutputVis(P, sigma_real[i]);
3232 // Diagonalizing the tensor "field" B_ij [r]
3233 fprintf(stderr,"(%i) Diagonalizing B_ij [r] ... \n", P->Par.me);
3234 for (i=0; i< Dens0->LocalSizeR; i++) {
3235 for (in=0; in<NDIM; in++) // index i of vector component in integrand
3236 for (dex=0; dex<NDIM; dex++) { // index j of B component derivation in current density tensor
3237 //fprintf(stderr,"(%i) Setting B_(%i,%i)[%i] ... \n", P->Par.me, in,dex,i);
3238 gsl_matrix_complex_set(H,in,dex,gsl_complex_rect((sigma_real[in+dex*NDIM][i]+sigma_real[dex+in*NDIM][i])/2.,0));
3239 }
3240 gsl_eigen_herm(H, eval, w);
3241 gsl_sort_vector(eval); // sort eigenvalues
3242 for (in=0;in<NDIM;in++)
3243 sigma_real[in][i] = gsl_vector_get(eval,in);
3244 }
3245 // Output of diagonalized magnetic field densities for each direction
3246 for (i=0;i<NDIM;i++)
3247 OutputVis(P, sigma_real[i]);
3248 for (i=0;i<NDIM*NDIM;i++)
3249 UnLockDensityArray(Dens0,i,real); // sigma_imag/real free
3250
3251 gsl_eigen_herm_free(w);
3252 gsl_vector_free(eval);
3253 gsl_matrix_complex_free(H);
3254}
3255
3256
3257/** Calculates the chemical shielding tensor at the positions of the nuclei.
3258 * The chemical shielding tensor at position R is defined as the proportionality factor between the induced and
3259 * the externally applied field.
3260 * \f[
3261 * \sigma_{ij} (R) = \frac{\delta B_j^{ind} (R)}{\delta B_i^{ext}}
3262 * = \frac{\mu_0}{4 \pi} \int d^3 r' \left ( \frac{r'-r}{| r' - r |^3} \times J_i (r') \right )_j
3263 * \f]
3264 * One after another for each nuclear position is the tensor evaluated and the result printed
3265 * to screen. Tensor is diagonalized afterwards.
3266 * \param *P Problem at hand
3267 * \sa CalculateMagneticSusceptibility() - similar calculation, yet without translation to ion centers.
3268 * \warning This routine is out-dated due to being numerically unstable because of the singularity which is not
3269 * considered carefully, recommendend replacement is CalculateChemicalShieldingByReciprocalCurrentDensity().
3270 */
3271void CalculateChemicalShielding(struct Problem *P)
3272{
3273 struct RunStruct *R = &P->R;
3274 struct Lattice *Lat = &P->Lat;
3275 struct LatticeLevel *Lev0 = R->Lev0;
3276 struct Density *Dens0 = R->Lev0->Dens;
3277 struct Ions *I = &P->Ion;
3278 double sigma[NDIM*NDIM],Sigma[NDIM*NDIM];
3279 fftw_real *CurrentDensity[NDIM*NDIM];
3280 int it, ion, in, dex, i0, n[NDIM], n0, i;//, *NUp;
3281 double x,y,z;
3282 double dist;
3283 double r[NDIM], fac[NDIM];
3284 const double discrete_factor = Lat->Volume/Lev0->MaxN;
3285 double eta, delta_sigma, S, A, iso;
3286 const int myPE = P->Par.me_comm_ST_Psi;
3287 int N[NDIM];
3288 N[0] = Lev0->Plan0.plan->N[0];
3289 N[1] = Lev0->Plan0.plan->N[1];
3290 N[2] = Lev0->Plan0.plan->N[2];
3291 const int N0 = Lev0->Plan0.plan->local_nx;
3292 FILE *SigmaFile;
3293 char suffixsigma[255];
3294 time_t seconds;
3295 time(&seconds); // get current time
3296
3297 // set pointers onto current density
3298 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
3299 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
3300 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
3301 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
3302 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
3303 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
3304 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
3305 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
3306 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
3307 gsl_matrix_complex *H = gsl_matrix_complex_calloc(NDIM,NDIM);
3308
3309 for (it=0; it < I->Max_Types; it++) { // integration over all types
3310 for (ion=0; ion < I->I[it].Max_IonsOfType; ion++) { // and each ion of type
3311 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);
3312 for (in=0; in<NDIM; in++) {// index i of vector component in integrand
3313 for (dex=0; dex<NDIM; dex++) { // index j of B component derivation in current density tensor
3314 sigma[in+dex*NDIM] = 0.;
3315
3316 for(n0=0;n0<N0;n0++) // do the integration over real space
3317 for(n[1]=0;n[1]<N[1];n[1]++)
3318 for(n[2]=0;n[2]<N[2];n[2]++) {
3319 n[0]=n0 + N0*myPE; // global relative coordinate: due to partitoning of x-axis in PEPGamma>1 case
3320 fac[0] = (double)n[0]/(double)N[0];
3321 fac[1] = (double)n[1]/(double)N[1];
3322 fac[2] = (double)n[2]/(double)N[2];
3323 RMat33Vec3(r, Lat->RealBasis, fac);
3324 i0 = n[2]+N[2]*(n[1]+N[1]*(n0)); // the index of current density must match LocalSizeR!
3325 x = MinImageConv(Lat,r[cross(in,0)], I->I[it].R[NDIM*ion+cross(in,0)],cross(in,0));
3326 y = MinImageConv(Lat,r[cross(in,2)], I->I[it].R[NDIM*ion+cross(in,2)],cross(in,2));
3327 z = MinImageConv(Lat,r[in], I->I[it].R[NDIM*ion+in],in); // "in" always is missing third component in cross product
3328 dist = pow(x*x + y*y + z*z, 3./2.);
3329 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;
3330 //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]);
3331 }
3332 sigma[in+dex*NDIM] *= -mu0*discrete_factor/(4.*PI); // due to summation instead of integration
3333 MPI_Allreduce ( &sigma[in+dex*NDIM], &Sigma[in+dex*NDIM], 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum "LocalSize to TotalSize"
3334 I->I[it].sigma[ion][in+dex*NDIM] = Sigma[in+dex*NDIM];
3335 if (P->Call.out[ValueOut]) fprintf(stderr," %e", Sigma[in+dex*NDIM]);
3336 }
3337 if (P->Call.out[ValueOut]) fprintf(stderr,"\n");
3338 }
3339 // store symmetrized matrix
3340 for (in=0;in<NDIM;in++)
3341 for (dex=0;dex<NDIM;dex++)
3342 gsl_matrix_complex_set(H,in,dex,gsl_complex_rect((Sigma[in+dex*NDIM]+Sigma[dex+in*NDIM])/2.,0));
3343 // output tensor to file
3344 if (P->Par.me == 0) {
3345 sprintf(&suffixsigma[0], ".sigma_i%i_%s.L%i.csv", ion, I->I[it].Symbol, Lev0->LevelNo);
3346 OpenFile(P, &SigmaFile, suffixsigma, "a", P->Call.out[ReadOut]);
3347 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));
3348 fprintf(SigmaFile,"%lg\t", P->Lat.ECut/(Lat->LevelSizes[0]*Lat->LevelSizes[0]));
3349 for (in=0;in<NDIM*NDIM;in++)
3350 fprintf(SigmaFile,"%e\t", Sigma[in]);
3351 fprintf(SigmaFile,"\n");
3352 fclose(SigmaFile);
3353 }
3354 // diagonalize sigma
3355 gsl_vector *eval = gsl_vector_alloc(NDIM);
3356 gsl_eigen_herm_workspace *w = gsl_eigen_herm_alloc(NDIM);
3357 gsl_eigen_herm(H, eval, w);
3358 gsl_eigen_herm_free(w);
3359 gsl_sort_vector(eval); // sort eigenvalues
3360 // print eigenvalues
3361// if (P->Call.out[ValueOut]) {
3362// fprintf(stderr,"(%i) diagonal shielding for Ion %i of element %s:", P->Par.me, ion, I->I[it].Name);
3363// for (in=0;in<NDIM;in++)
3364// fprintf(stderr,"\t%lg",gsl_vector_get(eval,in));
3365// fprintf(stderr,"\n\n");
3366// }
3367 // print eigenvalues
3368 iso = 0;
3369 for (i=0;i<NDIM;i++) {
3370 I->I[it].sigma[ion][i] = gsl_vector_get(eval,i);
3371 iso += Sigma[i+i*NDIM]/3.;
3372 }
3373 eta = (gsl_vector_get(eval,1)-gsl_vector_get(eval,0))/(gsl_vector_get(eval,2)-iso);
3374 delta_sigma = gsl_vector_get(eval,2) - 0.5*(gsl_vector_get(eval,0)+gsl_vector_get(eval,1));
3375 S = (delta_sigma*delta_sigma)*(1+1./3.*eta*eta);
3376 A = 0.;
3377 for (i=0;i<NDIM;i++) {
3378 in = cross(i,0);
3379 dex = cross(i,1);
3380 A += pow(-1,i)*pow(0.5*(Sigma[in+dex*NDIM]-Sigma[dex+in*NDIM]),2);
3381 }
3382 if (P->Call.out[ValueOut]) {
3383 fprintf(stderr,"(%i) converted to Principal Axis System\n==================\nDiagonal entries:", P->Par.me);
3384 for (i=0;i<NDIM;i++)
3385 fprintf(stderr,"\t%lg",gsl_vector_get(eval,i));
3386 fprintf(stderr,"\nshielding : %e\n", iso);
3387 fprintf(stderr,"anisotropy : %e\n", delta_sigma);
3388 fprintf(stderr,"asymmetry : %e\n", eta);
3389 fprintf(stderr,"S : %e\n", S);
3390 fprintf(stderr,"A : %e\n", A);
3391 fprintf(stderr,"==================\n");
3392
3393 }
3394 gsl_vector_free(eval);
3395 }
3396 }
3397
3398 gsl_matrix_complex_free(H);
3399}
3400
3401/** Test if integrated current over cell is 0.
3402 * In most cases we do not reach a numerical sensible zero as in MYEPSILON and remain satisfied as long
3403 * as the integrated current density is very small (e.g. compared to single entries in the current density array)
3404 * \param *P Problem at hand
3405 * \param index index of current component
3406 * \sa CalculateNativeIntDens() for integration of one current tensor component
3407 */
3408 void TestCurrent(struct Problem *P, const int index)
3409{
3410 struct RunStruct *R = &P->R;
3411 struct LatticeLevel *Lev0 = R->Lev0;
3412 struct Density *Dens0 = Lev0->Dens;
3413 fftw_real *CurrentDensity[NDIM*NDIM];
3414 int in;
3415 double result[NDIM*NDIM], res = 0.;
3416
3417 // set pointers onto current density array and get number of grid points in each direction
3418 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
3419 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
3420 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
3421 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
3422 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
3423 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
3424 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
3425 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
3426 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
3427 for(in=0;in<NDIM;in++) {
3428 result[in] = CalculateNativeIntDens(P,Lev0,CurrentDensity[in + NDIM*index],R->FactorDensityR);
3429 res += pow(result[in],2.);
3430 }
3431 res = sqrt(res);
3432 // if greater than 0, complain about it
3433 if ((res > MYEPSILON) && (P->Call.out[LeaderOut]))
3434 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);
3435}
3436
3437/** Testing whether re<->im switches (due to symmetry) confuses fft.
3438 * \param *P Problem at hand
3439 * \param l local wave function number
3440 */
3441void test_fft_symmetry(struct Problem *P, const int l)
3442{
3443 struct Lattice *Lat = &P->Lat;
3444 struct RunStruct *R = &P->R;
3445 struct LatticeLevel *LevS = R->LevS;
3446 struct LatticeLevel *Lev0 = R->Lev0;
3447 struct Density *Dens0 = Lev0->Dens;
3448 struct fft_plan_3d *plan = Lat->plan;
3449 fftw_complex *tempdestRC = (fftw_complex *)Dens0->DensityCArray[Temp2Density];
3450 fftw_complex *work = Dens0->DensityCArray[TempDensity];
3451 fftw_complex *workC = (fftw_complex *)Dens0->DensityArray[TempDensity];
3452 fftw_complex *posfac, *destpos, *destRCS, *destRCD;
3453 fftw_complex *PsiC = Dens0->DensityCArray[ActualPsiDensity];
3454 fftw_real *PsiCR = (fftw_real *) PsiC;
3455 fftw_complex *Psi0 = LevS->LPsi->LocalPsi[l];
3456 fftw_complex *dest = LevS->LPsi->TempPsi;
3457 fftw_real *Psi0R = (fftw_real *)Dens0->DensityArray[Temp2Density];
3458 int i,Index, pos, i0, iS,g; //, NoOfPsis = Psi->TypeStartIndex[UnOccupied] - Psi->TypeStartIndex[Occupied];
3459 int n[NDIM], n0;
3460 const int N0 = LevS->Plan0.plan->local_nx; // we don't want to build global density, but local
3461 int N[NDIM], NUp[NDIM];
3462 N[0] = LevS->Plan0.plan->N[0];
3463 N[1] = LevS->Plan0.plan->N[1];
3464 N[2] = LevS->Plan0.plan->N[2];
3465 NUp[0] = LevS->NUp[0];
3466 NUp[1] = LevS->NUp[1];
3467 NUp[2] = LevS->NUp[2];
3468 //const int k_normal = Lat->Psi.TypeStartIndex[Occupied] + (l - Lat->Psi.TypeStartIndex[R->CurrentMin]);
3469 //const double *Wcentre = Lat->Psi.AddData[k_normal].WannierCentre;
3470 //double x[NDIM], fac[NDIM];
3471 double result1=0., result2=0., result3=0., result4=0.;
3472 double Result1=0., Result2=0., Result3=0., Result4=0.;
3473 const double HGcRCFactor = 1./LevS->MaxN; // factor for inverse fft
3474
3475
3476 // fft to real space
3477 SetArrayToDouble0((double *)tempdestRC, Dens0->TotalSize*2);
3478 SetArrayToDouble0((double *)PsiC, Dens0->TotalSize*2);
3479 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is positive
3480 Index = LevS->GArray[i].Index;
3481 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
3482 destpos = &tempdestRC[LevS->MaxNUp*Index];
3483 for (pos=0; pos < LevS->MaxNUp; pos++) {
3484 destpos[pos].re = (Psi0[i].re)*posfac[pos].re-(Psi0[i].im)*posfac[pos].im;
3485 destpos[pos].im = (Psi0[i].re)*posfac[pos].im+(Psi0[i].im)*posfac[pos].re;
3486 //destpos[pos].re = (Psi0[i].im)*posfac[pos].re-(-Psi0[i].re)*posfac[pos].im;
3487 //destpos[pos].im = (Psi0[i].im)*posfac[pos].im+(-Psi0[i].re)*posfac[pos].re;
3488 }
3489 }
3490 for (i=0; i<LevS->MaxDoubleG; i++) {
3491 destRCS = &tempdestRC[LevS->DoubleG[2*i]*LevS->MaxNUp];
3492 destRCD = &tempdestRC[LevS->DoubleG[2*i+1]*LevS->MaxNUp];
3493 for (pos=0; pos < LevS->MaxNUp; pos++) {
3494 destRCD[pos].re = destRCS[pos].re;
3495 destRCD[pos].im = -destRCS[pos].im;
3496 }
3497 }
3498 fft_3d_complex_to_real(plan, LevS->LevelNo, FFTNFUp, tempdestRC, work);
3499 DensityRTransformPos(LevS,(fftw_real*)tempdestRC, Psi0R);
3500
3501 // apply position operator and do first result
3502 for (n0=0;n0<N0;n0++) // only local points on x axis
3503 for (n[1]=0;n[1]<N[1];n[1]++)
3504 for (n[2]=0;n[2]<N[2];n[2]++) {
3505 n[0]=n0 + LevS->Plan0.plan->start_nx; // global relative coordinate: due to partitoning of x-axis in PEPGamma>1 case
3506 i0 = n[2]*NUp[2]+N[2]*NUp[2]*(n[1]*NUp[1]+N[1]*NUp[1]*n0*NUp[0]);
3507 iS = n[2]+N[2]*(n[1]+N[1]*n0);
3508 //x[0] += 1; // shifting expectation value of x coordinate from 0 to 1
3509 PsiCR[iS] = Psi0R[i0]; // truedist(Lat, x[0], Wcentre[0],0) *
3510 result1 += PsiCR[iS] * Psi0R[i0];
3511 }
3512 result1 /= LevS->MaxN; // factor due to discrete integration
3513 MPI_Allreduce ( &result1, &Result1, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum "LocalSize to TotalSize"
3514 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) 1st result: %e\n",P->Par.me, Result1);
3515
3516 // fft to reciprocal space and do second result
3517 fft_3d_real_to_complex(plan, LevS->LevelNo, FFTNF1, PsiC, workC);
3518 SetArrayToDouble0((double *)dest, 2*R->InitLevS->MaxG);
3519 for (g=0; g < LevS->MaxG; g++) {
3520 Index = LevS->GArray[g].Index;
3521 dest[g].re = (Psi0[Index].re)*HGcRCFactor;
3522 dest[g].im = (Psi0[Index].im)*HGcRCFactor;
3523 }
3524 result2 = GradSP(P,LevS,Psi0,dest);
3525 MPI_Allreduce ( &result2, &Result2, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum "LocalSize to TotalSize"
3526 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) 2nd result: %e\n",P->Par.me, Result2);
3527
3528 // fft again to real space, this time change symmetry
3529 SetArrayToDouble0((double *)tempdestRC, Dens0->TotalSize*2);
3530 SetArrayToDouble0((double *)PsiC, Dens0->TotalSize*2);
3531 for (i=0;i<LevS->MaxG;i++) { // incoming is positive, outgoing is positive
3532 Index = LevS->GArray[i].Index;
3533 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
3534 destpos = &tempdestRC[LevS->MaxNUp*Index];
3535 for (pos=0; pos < LevS->MaxNUp; pos++) {
3536 destpos[pos].re = (Psi0[i].im)*posfac[pos].re-(-Psi0[i].re)*posfac[pos].im;
3537 destpos[pos].im = (Psi0[i].im)*posfac[pos].im+(-Psi0[i].re)*posfac[pos].re;
3538 }
3539 }
3540 for (i=0; i<LevS->MaxDoubleG; i++) {
3541 destRCS = &tempdestRC[LevS->DoubleG[2*i]*LevS->MaxNUp];
3542 destRCD = &tempdestRC[LevS->DoubleG[2*i+1]*LevS->MaxNUp];
3543 for (pos=0; pos < LevS->MaxNUp; pos++) {
3544 destRCD[pos].re = destRCS[pos].re;
3545 destRCD[pos].im = -destRCS[pos].im;
3546 }
3547 }
3548 fft_3d_complex_to_real(plan, LevS->LevelNo, FFTNFUp, tempdestRC, work);
3549 DensityRTransformPos(LevS,(fftw_real*)tempdestRC, Psi0R);
3550
3551 // bring down from Lev0 to LevS
3552 for (n0=0;n0<N0;n0++) // only local points on x axis
3553 for (n[1]=0;n[1]<N[1];n[1]++)
3554 for (n[2]=0;n[2]<N[2];n[2]++) {
3555 i0 = n[2]*NUp[2]+N[2]*NUp[2]*(n[1]*NUp[1]+N[1]*NUp[1]*n0*NUp[0]);
3556 iS = n[2]+N[2]*(n[1]+N[1]*n0);
3557 PsiCR[iS] = Psi0R[i0]; // truedist(Lat, x[0], Wcentre[0],0) *
3558 result3 += PsiCR[iS] * Psi0R[i0];
3559 }
3560 result3 /= LevS->MaxN; // factor due to discrete integration
3561 MPI_Allreduce ( &result3, &Result3, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum "LocalSize to TotalSize"
3562 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) 3rd result: %e\n",P->Par.me, Result3);
3563
3564 // fft back to reciprocal space, change symmetry back and do third result
3565 fft_3d_real_to_complex(plan, LevS->LevelNo, FFTNF1, PsiC, workC);
3566 SetArrayToDouble0((double *)dest, 2*R->InitLevS->MaxG);
3567 for (g=0; g < LevS->MaxG; g++) {
3568 Index = LevS->GArray[g].Index;
3569 dest[g].re = (-PsiC[Index].im)*HGcRCFactor;
3570 dest[g].im = ( PsiC[Index].re)*HGcRCFactor;
3571 }
3572 result4 = GradSP(P,LevS,Psi0,dest);
3573 MPI_Allreduce ( &result4, &Result4, 1, MPI_DOUBLE, MPI_SUM, P->Par.comm_ST_Psi); // sum "LocalSize to TotalSize"
3574 if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) 4th result: %e\n",P->Par.me, Result4);
3575}
3576
3577
3578/** Test function to check RxP application.
3579 * Checks applied solution to an analytic for a specific and simple wave function -
3580 * where just one coefficient is unequal to zero.
3581 * \param *P Problem at hand
3582 exp(I b G) - I exp(I b G) b G - exp(I a G) + I exp(I a G) a G
3583 -------------------------------------------------------------
3584 2
3585 G
3586 */
3587void test_rxp(struct Problem *P)
3588{
3589 struct RunStruct *R = &P->R;
3590 struct Lattice *Lat = &P->Lat;
3591 //struct LatticeLevel *Lev0 = R->Lev0;
3592 struct LatticeLevel *LevS = R->LevS;
3593 struct OneGData *GA = LevS->GArray;
3594 //struct Density *Dens0 = Lev0->Dens;
3595 fftw_complex *Psi0 = LevS->LPsi->TempPsi;
3596 fftw_complex *Psi2 = P->Grad.GradientArray[GraSchGradient];
3597 fftw_complex *Psi3 = LevS->LPsi->TempPsi2;
3598 int g, g_bar, i, j, k, k_normal = 0;
3599 double tmp, a,b, G;
3600 //const double *Wcentre = Lat->Psi.AddData[k_normal].WannierCentre;
3601 const double discrete_factor = 1.;//Lat->Volume/LevS->MaxN;
3602 fftw_complex integral;
3603
3604 // reset coefficients
3605 debug (P,"Creating RxP test function.");
3606 SetArrayToDouble0((double *)Psi0,2*R->InitLevS->MaxG);
3607 SetArrayToDouble0((double *)Psi2,2*R->InitLevS->MaxG);
3608
3609 // pick one which becomes non-zero
3610 g = 3;
3611
3612 //for (g=0;g<LevS->MaxG;g++) {
3613 Psi0[g].re = 1.;
3614 Psi0[g].im = 0.;
3615 //}
3616 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]);
3617 i = 0;
3618
3619 // calculate analytic result
3620 debug (P,"Calculating analytic solution.");
3621 for (g_bar=0;g_bar<LevS->MaxG;g_bar++) {
3622 for (g=0;g<LevS->MaxG;g++) {
3623 if (GA[g].G[i] == GA[g_bar].G[i]) {
3624 j = cross(i,0);
3625 k = cross(i,1);
3626 if (GA[g].G[k] == GA[g_bar].G[k]) {
3627 //b = truedist(Lat, sqrt(Lat->RealBasisSQ[j]), Wcentre[j], j);
3628 b = sqrt(Lat->RealBasisSQ[j]);
3629 //a = truedist(Lat, 0., Wcentre[j], j);
3630 a = 0.;
3631 G = 1; //GA[g].G[k];
3632 if (GA[g].G[j] == GA[g_bar].G[j]) {
3633 Psi2[g_bar].re += G*Psi0[g].re * (.5 * b * b - .5 * a * a) * discrete_factor;
3634 Psi2[g_bar].im += G*Psi0[g].im * (.5 * b * b - .5 * a * a) * discrete_factor;
3635 //if ((G != 0) && ((fabs(Psi0[g].re) > MYEPSILON) || (fabs(Psi0[g].im) > MYEPSILON)))
3636 //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);
3637 } else {
3638 tmp = GA[g].G[j]-GA[g_bar].G[j];
3639 integral.re = (cos(tmp*b)+sin(tmp*b)*b*tmp - cos(tmp*a)-sin(tmp*a)*a*tmp) / (tmp * tmp);
3640 integral.im = (sin(tmp*b)-cos(tmp*b)*b*tmp - sin(tmp*a)+cos(tmp*a)*a*tmp) / (tmp * tmp);
3641 Psi2[g_bar].re += G*(Psi0[g].re*integral.re - Psi0[g].im*integral.im) * discrete_factor;
3642 Psi2[g_bar].im += G*(Psi0[g].re*integral.im + Psi0[g].im*integral.re) * discrete_factor;
3643 //if ((G != 0) && ((fabs(Psi0[g].re) > MYEPSILON) || (fabs(Psi0[g].im) > MYEPSILON)))
3644 //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);
3645 }
3646 }
3647 j = cross(i,2);
3648 k = cross(i,3);
3649 if (GA[g].G[k] == GA[g_bar].G[k]) {
3650 //b = truedist(Lat, sqrt(Lat->RealBasisSQ[j]), Wcentre[j], j);
3651 b = sqrt(Lat->RealBasisSQ[j]);
3652 //a = truedist(Lat, 0., Wcentre[j], j);
3653 a = 0.;
3654 G = 1; //GA[g].G[k];
3655 if (GA[g].G[j] == GA[g_bar].G[j]) {
3656 Psi2[g_bar].re += G*Psi0[g].re * (.5 * b * b - .5 * a * a) * discrete_factor;
3657 Psi2[g_bar].im += G*Psi0[g].im * (.5 * b * b - .5 * a * a) * discrete_factor;
3658 //if ((G != 0) && ((fabs(Psi0[g].re) > MYEPSILON) || (fabs(Psi0[g].im) > MYEPSILON)))
3659 //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);
3660 } else {
3661 tmp = GA[g].G[j]-GA[g_bar].G[j];
3662 integral.re = (cos(tmp*b)+sin(tmp*b)*b*tmp - cos(tmp*a)-sin(tmp*a)*a*tmp) / (tmp * tmp);
3663 integral.im = (sin(tmp*b)-cos(tmp*b)*b*tmp - sin(tmp*a)+cos(tmp*a)*a*tmp) / (tmp * tmp);
3664 Psi2[g_bar].re += G*(Psi0[g].re*integral.re - Psi0[g].im*integral.im) * discrete_factor;
3665 Psi2[g_bar].im += G*(Psi0[g].re*integral.im + Psi0[g].im*integral.re) * discrete_factor;
3666 //if ((G != 0) && ((fabs(Psi0[g].re) > MYEPSILON) || (fabs(Psi0[g].im) > MYEPSILON)))
3667 //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);
3668 }
3669 }
3670 }
3671 }
3672 }
3673
3674 // apply rxp
3675 debug (P,"Applying RxP to test function.");
3676 CalculatePerturbationOperator_RxP(P,Psi0,Psi3,k_normal,i);
3677
3678 // compare both coefficient arrays
3679 debug(P,"Beginning comparison of analytic and Rxp applied solution.");
3680 for (g=0;g<LevS->MaxG;g++) {
3681 if ((fabs(Psi3[g].re-Psi2[g].re) >= MYEPSILON) || (fabs(Psi3[g].im-Psi2[g].im) >= MYEPSILON))
3682 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);
3683 //else
3684 //fprintf(stderr,"(%i) Psi1[%i] == Psi2[%i] = %e +i %e\n",P->Par.me, g, g, Psi1[g].re, Psi1[g].im);
3685 }
3686 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));
3687 fprintf(stderr,"(%i) <1|1> = |r|ᅵ == %e +i %e\n",P->Par.me, GradSP(P,LevS,Psi3,Psi3), GradImSP(P,LevS,Psi3,Psi3));
3688 fprintf(stderr,"(%i) <0|0> = %e +i %e\n",P->Par.me, GradSP(P,LevS,Psi0,Psi0), GradImSP(P,LevS,Psi0,Psi0));
3689 fprintf(stderr,"(%i) <0|2> = %e +i %e\n",P->Par.me, GradSP(P,LevS,Psi0,Psi2), GradImSP(P,LevS,Psi0,Psi2));
3690}
3691
3692
3693/** Output of a (X,Y,DX,DY) 2d-vector plot.
3694 * For a printable representation of the induced current two-dimensional vector plots are useful, as three-dimensional
3695 * isospheres are sometimes mis-leading or do not represent the desired flow direction. The routine simply extracts a
3696 * two-dimensional cut orthogonal to one of the lattice axis at a certain node.
3697 * \param *P Problem at hand
3698 * \param B_index direction of B field
3699 * \param n_orth grid node in B_index direction of the plane (the order in which the remaining two coordinate axis
3700 * appear is the same as in a cross product, which is used to determine orthogonality)
3701 */
3702void PlotVectorPlane(struct Problem *P, int B_index, int n_orth)
3703{
3704 struct RunStruct *R = &P->R;
3705 struct LatticeLevel *Lev0 = R->Lev0;
3706 struct Density *Dens0 = Lev0->Dens;
3707 char filename[255];
3708 char *suchpointer;
3709 FILE *PlotFile = NULL;
3710 const int myPE = P->Par.me_comm_ST;
3711 time_t seconds;
3712 fftw_real *CurrentDensity[NDIM*NDIM];
3713 CurrentDensity[0] = (fftw_real *) Dens0->DensityArray[CurrentDensity0];
3714 CurrentDensity[1] = (fftw_real *) Dens0->DensityArray[CurrentDensity1];
3715 CurrentDensity[2] = (fftw_real *) Dens0->DensityArray[CurrentDensity2];
3716 CurrentDensity[3] = (fftw_real *) Dens0->DensityArray[CurrentDensity3];
3717 CurrentDensity[4] = (fftw_real *) Dens0->DensityArray[CurrentDensity4];
3718 CurrentDensity[5] = (fftw_real *) Dens0->DensityArray[CurrentDensity5];
3719 CurrentDensity[6] = (fftw_real *) Dens0->DensityArray[CurrentDensity6];
3720 CurrentDensity[7] = (fftw_real *) Dens0->DensityArray[CurrentDensity7];
3721 CurrentDensity[8] = (fftw_real *) Dens0->DensityArray[CurrentDensity8];
3722 time(&seconds); // get current time
3723
3724 if (!myPE) { // only process 0 writes to file
3725 // open file
3726 sprintf(&filename[0], ".current.L%i.csv", Lev0->LevelNo);
3727 OpenFile(P, &PlotFile, filename, "w", P->Call.out[ReadOut]);
3728 strcpy(filename, ctime(&seconds));
3729 suchpointer = strchr(filename, '\n');
3730 if (suchpointer != NULL)
3731 *suchpointer = '\0';
3732 if (PlotFile != NULL) {
3733 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);
3734 fprintf(PlotFile,"\n");
3735 } else { Error(SomeError, "PlotVectorPlane: Opening Plot File"); }
3736 }
3737
3738 // plot density
3739 if (!P->Par.me_comm_ST_PsiT) // only first wave function group as current density of all psis was gathered
3740 PlotRealDensity(P, Lev0, PlotFile, B_index, n_orth, CurrentDensity[B_index*NDIM+cross(B_index,0)], CurrentDensity[B_index*NDIM+cross(B_index,1)]);
3741
3742 if (PlotFile != NULL) {
3743 // close file
3744 fclose(PlotFile);
3745 }
3746}
3747
3748
3749/** Reads psi coefficients of \a type from file and transforms to new level.
3750 * \param *P Problem at hand
3751 * \param type PsiTypeTag of which minimisation group to load from file
3752 * \sa ReadSrcPsiDensity() - reading the coefficients, ChangePsiAndDensToLevUp() - transformation to upper level
3753 */
3754void ReadSrcPerturbedPsis(struct Problem *P, enum PsiTypeTag type)
3755{
3756 struct RunStruct *R = &P->R;
3757 struct Lattice *Lat = &P->Lat;
3758 struct LatticeLevel *Lev0 = &P->Lat.Lev[R->Lev0No+1]; // one level higher than current (ChangeLevUp already occurred)
3759 struct LatticeLevel *LevS = &P->Lat.Lev[R->LevSNo+1];
3760 struct Density *Dens = Lev0->Dens;
3761 struct Psis *Psi = &Lat->Psi;
3762 struct fft_plan_3d *plan = Lat->plan;
3763 fftw_complex *work = (fftw_complex *)Dens->DensityCArray[TempDensity];
3764 fftw_complex *tempdestRC = (fftw_complex *)Dens->DensityArray[TempDensity];
3765 fftw_complex *posfac, *destpos, *destRCS, *destRCD;
3766 fftw_complex *source, *source0;
3767 int Index,i,pos;
3768 double factorC = 1./Lev0->MaxN;
3769 int p,g;
3770
3771 // ================= read coefficients from file to LocalPsi ============
3772 ReadSrcPsiDensity(P, type, 0, R->LevSNo+1);
3773
3774 // ================= transform to upper level ===========================
3775 // for all local Psis do the usual transformation (completing coefficients for all grid vectors, fft, permutation)
3776 LockDensityArray(Dens, TempDensity, real);
3777 LockDensityArray(Dens, TempDensity, imag);
3778 for (p=Psi->LocalNo-1; p >= 0; p--)
3779 if (Psi->LocalPsiStatus[p].PsiType == type) { // only for the desired type
3780 source = LevS->LPsi->LocalPsi[p];
3781 source0 = Lev0->LPsi->LocalPsi[p];
3782 //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);
3783 SetArrayToDouble0((double *)tempdestRC, Dens->TotalSize*2);
3784 for (i=0;i<LevS->MaxG;i++) {
3785 Index = LevS->GArray[i].Index;
3786 posfac = &LevS->PosFactorUp[LevS->MaxNUp*i];
3787 destpos = &tempdestRC[LevS->MaxNUp*Index];
3788 //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!"); }
3789 for (pos=0; pos < LevS->MaxNUp; pos++) {
3790 destpos[pos].re = source[i].re*posfac[pos].re-source[i].im*posfac[pos].im;
3791 destpos[pos].im = source[i].re*posfac[pos].im+source[i].im*posfac[pos].re;
3792 }
3793 }
3794 for (i=0; i<LevS->MaxDoubleG; i++) {
3795 destRCS = &tempdestRC[LevS->DoubleG[2*i]*LevS->MaxNUp];
3796 destRCD = &tempdestRC[LevS->DoubleG[2*i+1]*LevS->MaxNUp];
3797 for (pos=0; pos < LevS->MaxNUp; pos++) {
3798 destRCD[pos].re = destRCS[pos].re;
3799 destRCD[pos].im = -destRCS[pos].im;
3800 }
3801 }
3802 fft_3d_complex_to_real(plan, LevS->LevelNo, FFTNFUp, tempdestRC, work);
3803 DensityRTransformPos(LevS,(fftw_real*)tempdestRC,(fftw_real *)Dens->DensityCArray[ActualPsiDensity]);
3804 // now we have density in the upper level, fft back to complex and store it as wave function coefficients
3805 fft_3d_real_to_complex(plan, Lev0->LevelNo, FFTNF1, Dens->DensityCArray[ActualPsiDensity], work);
3806 for (g=0; g < Lev0->MaxG; g++) {
3807 Index = Lev0->GArray[g].Index;
3808 source0[g].re = Dens->DensityCArray[ActualPsiDensity][Index].re*factorC;
3809 source0[g].im = Dens->DensityCArray[ActualPsiDensity][Index].im*factorC;
3810 //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!"); }
3811 }
3812 if (Lev0->GArray[0].GSq == 0.0)
3813 source0[g].im = 0.0;
3814 }
3815 UnLockDensityArray(Dens, TempDensity, real);
3816 UnLockDensityArray(Dens, TempDensity, imag);
3817 // finished.
3818}
3819
3820/** evaluates perturbed energy functional
3821 * \param norm norm of current Psi in functional
3822 * \param *params void-pointer to parameter array
3823 * \return evaluated functional at f(x) with \a norm
3824 */
3825double perturbed_function (double norm, void *params) {
3826 struct Problem *P = (struct Problem *)params;
3827 int i, n = P->R.LevS->MaxG;
3828 double old_norm = GramSchGetNorm2(P,P->R.LevS,P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo]);
3829 fftw_complex *currentPsi = P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo];
3830 fprintf(stderr,"(%i) perturbed_function: setting norm to %lg ...", P->Par.me, norm);
3831 // set desired norm for current Psi
3832 for (i=0; i< n; i++) {
3833 currentPsi[i].re *= norm/old_norm; // real part
3834 currentPsi[i].im *= norm/old_norm; // imaginary part
3835 }
3836 P->R.PsiStep = 0; // make it not advance to next Psi
3837
3838 //debug(P,"UpdateActualPsiNo");
3839 UpdateActualPsiNo(P, P->R.CurrentMin); // orthogonalize
3840 //debug(P,"UpdateEnergyArray");
3841 UpdateEnergyArray(P); // shift energy values in their array by one
3842 //debug(P,"UpdatePerturbedEnergyCalculation");
3843 UpdatePerturbedEnergyCalculation(P); // re-calc energies (which is hopefully lower)
3844 EnergyAllReduce(P); // gather from all processes and sum up to total energy
3845/*
3846 for (i=0; i< n; i++) {
3847 currentPsi[i].re /= norm/old_norm; // real part
3848 currentPsi[i].im /= norm/old_norm; // imaginary part
3849 }*/
3850
3851 fprintf(stderr,"%lg\n", P->Lat.E->TotalEnergy[0]);
3852 return P->Lat.E->TotalEnergy[0]; // and return evaluated functional
3853}
3854
3855/** evaluates perturbed energy functional.
3856 * \param *x current position in functional
3857 * \param *params void-pointer to parameter array
3858 * \return evaluated functional at f(x)
3859 */
3860double perturbed_f (const gsl_vector *x, void *params) {
3861 struct Problem *P = (struct Problem *)params;
3862 int i, n = P->R.LevS->MaxG*2;
3863 fftw_complex *currentPsi = P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo];
3864 //int diff = 0;
3865 //debug(P,"f");
3866 // put x into current Psi
3867 for (i=0; i< n; i+=2) {
3868 //if ((currentPsi[i/2].re != gsl_vector_get (x, i)) || (currentPsi[i/2].im != gsl_vector_get (x, i+1))) diff++;
3869 currentPsi[i/2].re = gsl_vector_get (x, i); // real part
3870 currentPsi[i/2].im = gsl_vector_get (x, i+1); // imaginary part
3871 }
3872 //if (diff) fprintf(stderr,"(%i) %i differences between old and new currentPsi.\n", P->Par.me, diff);
3873 P->R.PsiStep = 0; // make it not advance to next Psi
3874
3875 //debug(P,"UpdateActualPsiNo");
3876 UpdateActualPsiNo(P, P->R.CurrentMin); // orthogonalize
3877 //debug(P,"UpdateEnergyArray");
3878 UpdateEnergyArray(P); // shift energy values in their array by one
3879 //debug(P,"UpdatePerturbedEnergyCalculation");
3880 UpdatePerturbedEnergyCalculation(P); // re-calc energies (which is hopefully lower)
3881 EnergyAllReduce(P); // gather from all processes and sum up to total energy
3882
3883 return P->Lat.E->TotalEnergy[0]; // and return evaluated functional
3884}
3885
3886/** evaluates perturbed energy gradient.
3887 * \param *x current position in functional
3888 * \param *params void-pointer to parameter array
3889 * \param *g array for gradient vector on return
3890 */
3891void perturbed_df (const gsl_vector *x, void *params, gsl_vector *g) {
3892 struct Problem *P = (struct Problem *)params;
3893 int i, n = P->R.LevS->MaxG*2;
3894 fftw_complex *currentPsi = P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo];
3895 fftw_complex *gradient = P->Grad.GradientArray[ActualGradient];
3896 //int diff = 0;
3897 //debug(P,"df");
3898 // put x into current Psi
3899 for (i=0; i< n; i+=2) {
3900 //if ((currentPsi[i/2].re != gsl_vector_get (x, i)) || (currentPsi[i/2].im != gsl_vector_get (x, i+1))) diff++;
3901 currentPsi[i/2].re = gsl_vector_get (x, i); // real part
3902 currentPsi[i/2].im = gsl_vector_get (x, i+1); // imaginary part
3903 }
3904 //if (diff) fprintf(stderr,"(%i) %i differences between old and new currentPsi.\n", P->Par.me, diff);
3905 P->R.PsiStep = 0; // make it not advance to next Psi
3906
3907 //debug(P,"UpdateActualPsiNo");
3908 UpdateActualPsiNo(P, P->R.CurrentMin); // orthogonalize
3909 //debug(P,"UpdateEnergyArray");
3910 UpdateEnergyArray(P); // shift energy values in their array by one
3911 //debug(P,"UpdatePerturbedEnergyCalculation");
3912 UpdatePerturbedEnergyCalculation(P); // re-calc energies (which is hopefully lower)
3913 EnergyAllReduce(P); // gather from all processes and sum up to total energy
3914
3915 // checkout gradient
3916 //diff = 0;
3917 for (i=0; i< n; i+=2) {
3918 //if ((-gradient[i/2].re != gsl_vector_get (g, i)) || (-gradient[i/2].im != gsl_vector_get (g, i+1))) diff++;
3919 gsl_vector_set (g, i, -gradient[i/2].re); // real part
3920 gsl_vector_set (g, i+1, -gradient[i/2].im); // imaginary part
3921 }
3922 //if (diff) fprintf(stderr,"(%i) %i differences between old and new gradient.\n", P->Par.me, diff);
3923}
3924
3925/** evaluates perturbed energy functional and gradient.
3926 * \param *x current position in functional
3927 * \param *params void-pointer to parameter array
3928 * \param *f pointer to energy function value on return
3929 * \param *g array for gradient vector on return
3930 */
3931void perturbed_fdf (const gsl_vector *x, void *params, double *f, gsl_vector *g) {
3932 struct Problem *P = (struct Problem *)params;
3933 int i, n = P->R.LevS->MaxG*2;
3934 fftw_complex *currentPsi = P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo];
3935 fftw_complex *gradient = P->Grad.GradientArray[ActualGradient];
3936 //int diff = 0;
3937 //debug(P,"fdf");
3938 // put x into current Psi
3939 for (i=0; i< n; i+=2) {
3940 //if ((currentPsi[i/2].re != gsl_vector_get (x, i)) || (currentPsi[i/2].im != gsl_vector_get (x, i+1))) diff++;
3941 currentPsi[i/2].re = gsl_vector_get (x, i); // real part
3942 currentPsi[i/2].im = gsl_vector_get (x, i+1); // imaginary part
3943 }
3944 //if (diff) fprintf(stderr,"(%i) %i differences between old and new currentPsi.\n", P->Par.me, diff);
3945 P->R.PsiStep = 0; // make it not advance to next Psi
3946
3947 //debug(P,"UpdateActualPsiNo");
3948 UpdateActualPsiNo(P, P->R.CurrentMin); // orthogonalize
3949 //debug(P,"UpdateEnergyArray");
3950 UpdateEnergyArray(P); // shift energy values in their array by one
3951 //debug(P,"UpdatePerturbedEnergyCalculation");
3952 UpdatePerturbedEnergyCalculation(P); // re-calc energies (which is hopefully lower)
3953 EnergyAllReduce(P); // gather from all processes and sum up to total energy
3954
3955 // checkout gradient
3956 //diff = 0;
3957 for (i=0; i< n; i+=2) {
3958 //if ((-gradient[i/2].re != gsl_vector_get (g, i)) || (-gradient[i/2].im != gsl_vector_get (g, i+1))) diff++;
3959 gsl_vector_set (g, i, -gradient[i/2].re); // real part
3960 gsl_vector_set (g, i+1, -gradient[i/2].im); // imaginary part
3961 }
3962 //if (diff) fprintf(stderr,"(%i) %i differences between old and new gradient.\n", P->Par.me, diff);
3963
3964 *f = P->Lat.E->TotalEnergy[0]; // and return evaluated functional
3965}
3966
3967/* MinimisePerturbed with all the brent minimisation approach
3968void MinimisePerturbed (struct Problem *P, int *Stop, int *SuperStop) {
3969 struct RunStruct *R = &P->R;
3970 struct Lattice *Lat = &P->Lat;
3971 struct Psis *Psi = &Lat->Psi;
3972 int type;
3973 //int i;
3974
3975 // stuff for GSL minimization
3976 //size_t iter;
3977 //int status, Status
3978 int n = R->LevS->MaxG*2;
3979 const gsl_multimin_fdfminimizer_type *T_multi;
3980 const gsl_min_fminimizer_type *T;
3981 gsl_multimin_fdfminimizer *s_multi;
3982 gsl_min_fminimizer *s;
3983 gsl_vector *x;//, *ss;
3984 gsl_multimin_function_fdf my_func;
3985 gsl_function F;
3986 //fftw_complex *currentPsi;
3987 //double a,b,m, f_m, f_a, f_b;
3988 //double old_norm;
3989
3990 my_func.f = &perturbed_f;
3991 my_func.df = &perturbed_df;
3992 my_func.fdf = &perturbed_fdf;
3993 my_func.n = n;
3994 my_func.params = P;
3995 F.function = &perturbed_function;
3996 F.params = P;
3997
3998 x = gsl_vector_alloc (n);
3999 //ss = gsl_vector_alloc (Psi->NoOfPsis);
4000 T_multi = gsl_multimin_fdfminimizer_vector_bfgs;
4001 s_multi = gsl_multimin_fdfminimizer_alloc (T_multi, n);
4002 T = gsl_min_fminimizer_brent;
4003 s = gsl_min_fminimizer_alloc (T);
4004
4005 for (type=Perturbed_P0;type<=Perturbed_RxP2;type++) { // go through each perturbation group separately //
4006 *Stop=0; // reset stop flag
4007 fprintf(stderr,"(%i)Beginning perturbed minimisation of type %s ...\n", P->Par.me, R->MinimisationName[type]);
4008 //OutputOrbitalPositions(P, Occupied);
4009 R->PsiStep = R->MaxPsiStep; // reset in-Psi-minimisation-counter, so that we really advance to the next wave function
4010 UpdateActualPsiNo(P, type); // step on to next perturbed one
4011 fprintf(stderr, "(%i) Re-initializing perturbed psi array for type %s ", P->Par.me, R->MinimisationName[type]);
4012 if (P->Call.ReadSrcFiles && ReadSrcPsiDensity(P,type,1, R->LevSNo)) {
4013 SpeedMeasure(P, InitSimTime, StartTimeDo);
4014 fprintf(stderr,"from source file of recent calculation\n");
4015 ReadSrcPsiDensity(P,type, 0, R->LevSNo);
4016 ResetGramSchTagType(P, Psi, type, IsOrthogonal); // loaded values are orthonormal
4017 SpeedMeasure(P, DensityTime, StartTimeDo);
4018 //InitDensityCalculation(P);
4019 SpeedMeasure(P, DensityTime, StopTimeDo);
4020 R->OldActualLocalPsiNo = R->ActualLocalPsiNo; // needed otherwise called routines in function below crash
4021 UpdateGramSchOldActualPsiNo(P,Psi);
4022 InitPerturbedEnergyCalculation(P, 1); // go through all orbitals calculate each H^{(0)}-eigenvalue, recalc HGDensity, cause InitDensityCalc zero'd it
4023 UpdatePerturbedEnergyCalculation(P); // H1cGradient and Gradient must be current ones
4024 EnergyAllReduce(P); // gather energies for minimum search
4025 SpeedMeasure(P, InitSimTime, StopTimeDo);
4026 }
4027 if (P->Call.ReadSrcFiles != 1) {
4028 SpeedMeasure(P, InitSimTime, StartTimeDo);
4029 ResetGramSchTagType(P, Psi, type, NotOrthogonal); // perturbed now shall be orthonormalized
4030 if (P->Call.ReadSrcFiles != 2) {
4031 if (R->LevSNo == Lat->MaxLevel-1) { // is it the starting level? (see InitRunLevel())
4032 fprintf(stderr, "randomly.\n");
4033 InitPsisValue(P, Psi->TypeStartIndex[type], Psi->TypeStartIndex[type+1]); // initialize perturbed array for this run
4034 } else {
4035 fprintf(stderr, "from source file of last level.\n");
4036 ReadSrcPerturbedPsis(P, type);
4037 }
4038 }
4039 SpeedMeasure(P, InitGramSchTime, StartTimeDo);
4040 GramSch(P, R->LevS, Psi, Orthogonalize);
4041 SpeedMeasure(P, InitGramSchTime, StopTimeDo);
4042 SpeedMeasure(P, InitDensityTime, StartTimeDo);
4043 //InitDensityCalculation(P);
4044 SpeedMeasure(P, InitDensityTime, StopTimeDo);
4045 InitPerturbedEnergyCalculation(P, 1); // go through all orbitals calculate each H^{(0)}-eigenvalue, recalc HGDensity, cause InitDensityCalc zero'd it
4046 R->OldActualLocalPsiNo = R->ActualLocalPsiNo; // needed otherwise called routines in function below crash
4047 UpdateGramSchOldActualPsiNo(P,Psi);
4048 UpdatePerturbedEnergyCalculation(P); // H1cGradient and Gradient must be current ones
4049 EnergyAllReduce(P); // gather energies for minimum search
4050 SpeedMeasure(P, InitSimTime, StopTimeDo);
4051 R->LevS->Step++;
4052 EnergyOutput(P,0);
4053 while (*Stop != 1) {
4054 // copy current Psi into starting vector
4055 currentPsi = R->LevS->LPsi->LocalPsi[R->ActualLocalPsiNo];
4056 for (i=0; i< n; i+=2) {
4057 gsl_vector_set (x, i, currentPsi[i/2].re); // real part
4058 gsl_vector_set (x, i+1, currentPsi[i/2].im); // imaginary part
4059 }
4060 gsl_multimin_fdfminimizer_set (s_multi, &my_func, x, 0.01, 1e-2);
4061 iter = 0;
4062 status = 0;
4063 do { // look for minimum along current local psi
4064 iter++;
4065 status = gsl_multimin_fdfminimizer_iterate (s_multi);
4066 MPI_Allreduce(&status, &Status, 1, MPI_INT, MPI_MAX, P->Par.comm_ST_Psi);
4067 if (Status)
4068 break;
4069 status = gsl_multimin_test_gradient (s_multi->gradient, 1e-2);
4070 MPI_Allreduce(&status, &Status, 1, MPI_INT, MPI_MAX, P->Par.comm_ST_Psi);
4071 //if (Status == GSL_SUCCESS)
4072 //printf ("Minimum found at:\n");
4073 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);
4074 //TestGramSch(P,R->LevS,Psi, type); // functions are orthonormal?
4075 } while (Status == GSL_CONTINUE && iter < 3);
4076 // now minimize norm of currentPsi (one-dim)
4077 if (0) {
4078 iter = 0;
4079 status = 0;
4080 m = 1.;
4081 a = MYEPSILON;
4082 b = 100.;
4083 f_a = perturbed_function (a, P);
4084 f_b = perturbed_function (b, P);
4085 f_m = perturbed_function (m, P);
4086 //if ((f_m < f_a) && (f_m < f_b)) {
4087 gsl_min_fminimizer_set (s, &F, m, a, b);
4088 do { // look for minimum along current local psi
4089 iter++;
4090 status = gsl_min_fminimizer_iterate (s);
4091 m = gsl_min_fminimizer_x_minimum (s);
4092 a = gsl_min_fminimizer_x_lower (s);
4093 b = gsl_min_fminimizer_x_upper (s);
4094 status = gsl_min_test_interval (a, b, 0.001, 0.0);
4095 if (status == GSL_SUCCESS)
4096 printf ("Minimum found at:\n");
4097 printf ("%5d [%.7f, %.7f] %.7f %.7f\n",
4098 (int) iter, a, b,
4099 m, b - a);
4100 } while (status == GSL_CONTINUE && iter < 100);
4101 old_norm = GramSchGetNorm2(P,P->R.LevS,P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo]);
4102 for (i=0; i< n; i++) {
4103 currentPsi[i].re *= m/old_norm; // real part
4104 currentPsi[i].im *= m/old_norm; // imaginary part
4105 }
4106 } else debug(P,"Norm not minimizable!");
4107 //P->R.PsiStep = P->R.MaxPsiStep; // make it advance to next Psi
4108 FindPerturbedMinimum(P);
4109 //debug(P,"UpdateActualPsiNo");
4110 UpdateActualPsiNo(P, type); // step on to next perturbed Psi
4111 //debug(P,"UpdateEnergyArray");
4112 UpdateEnergyArray(P); // shift energy values in their array by one
4113 //debug(P,"UpdatePerturbedEnergyCalculation");
4114 UpdatePerturbedEnergyCalculation(P); // re-calc energies (which is hopefully lower)
4115 EnergyAllReduce(P); // gather from all processes and sum up to total energy
4116 //ControlNativeDensity(P); // check total density (summed up PertMixed must be zero!)
4117 //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);
4118 if (*SuperStop != 1)
4119 *SuperStop = CheckCPULIM(P);
4120 *Stop = CalculateMinimumStop(P, *SuperStop);
4121 P->Speed.Steps++; // step on
4122 R->LevS->Step++;
4123 }
4124 // now release normalization condition and minimize wrt to norm
4125 *Stop = 0;
4126 while (*Stop != 1) {
4127 currentPsi = R->LevS->LPsi->LocalPsi[R->ActualLocalPsiNo];
4128 iter = 0;
4129 status = 0;
4130 m = 1.;
4131 a = 0.001;
4132 b = 10.;
4133 f_a = perturbed_function (a, P);
4134 f_b = perturbed_function (b, P);
4135 f_m = perturbed_function (m, P);
4136 if ((f_m < f_a) && (f_m < f_b)) {
4137 gsl_min_fminimizer_set (s, &F, m, a, b);
4138 do { // look for minimum along current local psi
4139 iter++;
4140 status = gsl_min_fminimizer_iterate (s);
4141 m = gsl_min_fminimizer_x_minimum (s);
4142 a = gsl_min_fminimizer_x_lower (s);
4143 b = gsl_min_fminimizer_x_upper (s);
4144 status = gsl_min_test_interval (a, b, 0.001, 0.0);
4145 if (status == GSL_SUCCESS)
4146 printf ("Minimum found at:\n");
4147 printf ("%5d [%.7f, %.7f] %.7f %.7f\n",
4148 (int) iter, a, b,
4149 m, b - a);
4150 } while (status == GSL_CONTINUE && iter < 100);
4151 old_norm = GramSchGetNorm2(P,P->R.LevS,P->R.LevS->LPsi->LocalPsi[P->R.ActualLocalPsiNo]);
4152 for (i=0; i< n; i++) {
4153 currentPsi[i].re *= m/old_norm; // real part
4154 currentPsi[i].im *= m/old_norm; // imaginary part
4155 }
4156 }
4157 P->R.PsiStep = P->R.MaxPsiStep; // make it advance to next Psi
4158 //debug(P,"UpdateActualPsiNo");
4159 UpdateActualPsiNo(P, type); // step on to next perturbed Psi
4160 if (*SuperStop != 1)
4161 *SuperStop = CheckCPULIM(P);
4162 *Stop = CalculateMinimumStop(P, *SuperStop);
4163 P->Speed.Steps++; // step on
4164 R->LevS->Step++;
4165 }
4166 if(P->Call.out[NormalOut]) fprintf(stderr,"(%i) Write %s srcpsi to disk\n", P->Par.me, R->MinimisationName[type]);
4167 OutputSrcPsiDensity(P, type);
4168// if (!TestReadnWriteSrcDensity(P,type))
4169// Error(SomeError,"TestReadnWriteSrcDensity failed!");
4170 }
4171
4172 TestGramSch(P,R->LevS,Psi, type); // functions are orthonormal?
4173 // calculate current density summands
4174 //if (P->Call.out[StepLeaderOut]) fprintf(stderr,"(%i) Filling current density grid ...\n",P->Par.me);
4175 SpeedMeasure(P, CurrDensTime, StartTimeDo);
4176 if (*SuperStop != 1) {
4177 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
4178 R->DoFullCurrent = 1; // set to 1 if it was 2 but Check...() yielded necessity
4179 //debug(P,"Filling with Delta j ...");
4180 //FillDeltaCurrentDensity(P);
4181 }// else
4182 //debug(P,"There is no overlap between orbitals.");
4183 //debug(P,"Filling with j ...");
4184 FillCurrentDensity(P);
4185 }
4186 SpeedMeasure(P, CurrDensTime, StopTimeDo);
4187
4188 SetGramSchExtraPsi(P,Psi,NotUsedToOrtho); // remove extra Psis from orthogonality check
4189 ResetGramSchTagType(P, Psi, type, NotUsedToOrtho); // remove this group from the check for the next minimisation group as well!
4190 }
4191 UpdateActualPsiNo(P, Occupied); // step on back to an occupied one
4192
4193 gsl_multimin_fdfminimizer_free (s_multi);
4194 gsl_min_fminimizer_free (s);
4195 gsl_vector_free (x);
4196 //gsl_vector_free (ss);
4197}
4198*/
Note: See TracBrowser for help on using the repository browser.