PSCF v1.5.0
rFieldIo.tpp
1#ifndef PSCF_FIELD_IO_UTIL_TPP
2#define PSCF_FIELD_IO_UTIL_TPP
3
4/*
5* PSCF - Polymer Self-Consistent Field
6*
7* Copyright 2015 - 2026, David Morse (morse012@um.edu) and co-authors
8* Distributed under the terms of the GNU General Public License.
9*/
10
11#include <pscf/crystal/Basis.h>
12#include <pscf/crystal/UnitCell.h>
13#include <pscf/crystal/shiftToMinimum.h>
14#include <pscf/crystal/replicateUnitCell.h>
15#include <pscf/fieldIo/fieldHeader.h>
16
17#include <pscf/mesh/Mesh.h>
18#include <pscf/mesh/MeshIterator.h>
19#include <pscf/mesh/MeshIteratorFortran.h>
20#include <pscf/math/IntVec.h>
21#include <pscf/math/arithmetic.h>
22#include <pscf/backend/complex.h>
23
24#include <util/containers/DArray.h>
25#include <util/misc/FileMaster.h>
26#include <util/misc/Log.h>
27#include <util/format/Int.h>
28#include <util/format/Dbl.h>
29#include <util/math/Constants.h>
30
31#include <string>
32
33namespace Pscf {
34
35 // RGrid File Io Templates
36
37 template <int D, class AT>
38 void readRGridData(std::istream& in,
39 DArray<AT>& fields,
40 int nMonomer,
41 IntVec<D> const& dimensions)
42 {
43 UTIL_CHECK(nMonomer > 0);
44 UTIL_CHECK(fields.capacity() == nMonomer);
45
46 MeshIteratorFortran<D> iter(dimensions);
47 double value;
48 int rank;
49 for (iter.begin(); !iter.atEnd(); ++iter) {
50 rank = iter.rank();
51 for (int k = 0; k < nMonomer; ++k) {
52 in >> value;
53 assign(fields[k][rank], value);
54 }
55 UTIL_CHECK(!in.fail());
56 }
57 }
58
59 template <int D, class AT>
60 void readRGridData(std::istream& in,
61 AT& field,
62 IntVec<D> const & dimensions)
63 {
64 MeshIteratorFortran<D> iter(dimensions);
65 double value;
66 int rank;
67 for (iter.begin(); !iter.atEnd(); ++iter) {
68 rank = iter.rank();
69 in >> value;
70 UTIL_CHECK(!in.fail());
71 assign(field[rank], value);
72 }
73 }
74
75 template <int D, class AT>
76 void writeRGridData(std::ostream& out,
77 DArray<AT> const& fields,
78 int nMonomer,
79 IntVec<D> const& dimensions)
80 {
81 UTIL_CHECK(nMonomer > 0);
82 UTIL_CHECK(nMonomer == fields.capacity());
83
84 MeshIteratorFortran<D> iter(dimensions);
85 int rank, j;
86 for (iter.begin(); !iter.atEnd(); ++iter) {
87 rank = iter.rank();
88 for (j = 0; j < nMonomer; ++j) {
89 out << " " << Dbl(fields[j][rank], 21, 13);
90 }
91 out << std::endl;
92 }
93
94 }
95
96 template <int D, class AT>
97 void writeRGridData(std::ostream& out,
98 AT const& field,
99 IntVec<D> const& dimensions)
100 {
101 MeshIteratorFortran<D> iter(dimensions);
102 int rank;
103 for (iter.begin(); !iter.atEnd(); ++iter) {
104 rank = iter.rank();
105 out << " " << Dbl(field[rank], 21, 13);
106 out << std::endl;
107 }
108 }
109
110 // KGrid file IO templates
111
112 template <int D, class ACT>
113 void readKGridData(std::istream& in,
114 DArray<ACT> & fields,
115 int nMonomer,
116 IntVec<D> const& dftDimensions)
117 {
118 using T = typename ACT::BackendIdClass;
119 using RealT = typename T::Real;
120 RealT x, y;
121
122 MeshIterator<D> iter(dftDimensions);
123 int rank, i, j, idum;
124 i = 0;
125 for (iter.begin(); !iter.atEnd(); ++iter) {
126 rank = iter.rank();
127 in >> idum;
128 UTIL_CHECK(i == idum);
129 UTIL_CHECK(i == rank);
130 for (j = 0; j < nMonomer; ++j) {
131 in >> x;
132 in >> y;
133 assign(fields[j][rank], x, y);
134 }
135 UTIL_CHECK(!in.fail());
136 ++i;
137 }
138 }
139
140 template <int D, class ACT>
141 void readKGridData(std::istream& in,
142 ACT& field,
143 IntVec<D> const& dftDimensions)
144 {
145 using T = typename ACT::BackendIdClass;
146 using RealT = typename T::Real;
147 RealT x, y;
148
149 MeshIterator<D> iter(dftDimensions);
150 int rank, idum;
151 int i = 0;
152 for (iter.begin(); !iter.atEnd(); ++iter) {
153 rank = iter.rank();
154 in >> idum;
155 UTIL_CHECK(i == idum);
156 UTIL_CHECK(i == rank);
157 in >> x;
158 in >> y;
159 UTIL_CHECK(!in.fail());
160 assign(field[rank], x, y);
161 ++i;
162 }
163 }
164
165 template <int D, class ACT>
166 void writeKGridData(std::ostream& out,
167 DArray<ACT> const& fields,
168 int nMonomer,
169 IntVec<D> const& dftDimensions)
170 {
171 UTIL_CHECK(nMonomer > 0);
172 UTIL_CHECK(nMonomer == fields.capacity());
173
174 using T = typename ACT::BackendIdClass;
175 using RealT = typename T::Real;
176 RealT x, y;
177
178 MeshIterator<D> iter(dftDimensions);
179 int rank;
180 int i = 0;
181 for (iter.begin(); !iter.atEnd(); ++iter) {
182 rank = iter.rank();
183 UTIL_CHECK(i == rank);
184 out << Int(rank, 5);
185 for (int j = 0; j < nMonomer; ++j) {
186 x = real(fields[j][rank]);
187 y = imag(fields[j][rank]);
188 // The space separates x and y also if y fills its width
189 // (e.g., a negative number with a three-digit exponent)
190 out << " "
191 << Dbl(x, 21, 13)
192 << " " << Dbl(y, 20, 13);
193 }
194 out << std::endl;
195 ++i;
196 }
197
198 }
199
200 template <int D, class ACT>
201 void writeKGridData(std::ostream& out,
202 ACT const& field,
203 IntVec<D> const& dftDimensions)
204 {
205 using T = typename ACT::BackendIdClass;
206 using RealT = typename T::Real;
207 RealT x, y;
208
209 MeshIterator<D> iter(dftDimensions);
210 int rank, i;
211 i = 0;
212 for (iter.begin(); !iter.atEnd(); ++iter) {
213 rank = iter.rank();
214 UTIL_CHECK(i == rank);
215 x = real(field[rank]);
216 y = imag(field[rank]);
217 out << Int(rank, 5);
218 out << " "
219 << Dbl(x, 21, 13)
220 << " " << Dbl(y, 20, 13);
221 out << std::endl;
222 ++i;
223 }
224 }
225
226 // Field data IO in symmetry-adapted basis format
227
228 /*
229 * Read the data section for an array of fields in basis format.
230 */
231 template <int D>
232 void readBasisData(std::istream& in,
233 DArray< DArray<double> >& fields,
234 UnitCell<D> const& unitCell,
235 Mesh<D> const& mesh,
236 Basis<D> const& basis,
237 int nBasisIn)
238 {
239 UTIL_CHECK(basis.isInitialized());
240 UTIL_CHECK(fields.isAllocated());
241
242 int nMonomer = fields.capacity();
243 UTIL_CHECK(nMonomer > 0);
244
245 // Initialize all field array elements to zero
246 int fieldCapacity = fields[0].capacity();
247 UTIL_CHECK(fieldCapacity > 0);
248 for (int i = 0; i < nMonomer; ++i) {
249 UTIL_CHECK(fields[i].capacity() == fieldCapacity);
250 for (int j = 0; j < fieldCapacity; ++j) {
251 fields[i][j] = 0.0;
252 }
253 }
254
255 // Reset nBasis = min(nBasisIn, fieldCapacity)
256 int nBasis = nBasisIn;
257 if (fieldCapacity < nBasisIn) {
258 nBasis = fieldCapacity;
259 }
260
261 // Allocate temp arrays used to read in components
262 DArray<double> temp, temp2;
263 temp.allocate(nMonomer);
264 temp2.allocate(nMonomer);
265
266 typename Basis<D>::Star const * starPtr;
267 typename Basis<D>::Star const * starPtr2;
268 IntVec<D> waveIn, waveIn2;
269 int sizeIn, sizeIn2;
270 int starId, starId2;
271 int basisId, basisId2;
272 int waveId, waveId2;
273
274 std::complex<double> coeff, phasor;
275 IntVec<D> waveMin, waveDft;
276 int nReversedPair = 0;
277 bool waveExists, sizeMatches;
278
279 // Loop over stars in input file to read field components
280 int i = 0;
281 while (i < nBasis) {
282
283 // Read next line of data
284 for (int j = 0; j < nMonomer; ++j) {
285 in >> temp[j]; // field components
286 }
287 in >> waveIn; // wave of star
288 in >> sizeIn; // # of waves in star
289 UTIL_CHECK(!in.fail());
290 ++i;
291
292 sizeMatches = false;
293 waveExists = false;
294
295 // Check if wavevector waveIn is a minimum image
296 waveMin = shiftToMinimum(waveIn, mesh.dimensions(), unitCell);
297 waveExists = (waveIn == waveMin);
298
299 if (waveExists) {
300
301 // Find the star containing waveIn
302 waveDft = waveIn;
303 mesh.shift(waveDft);
304 waveId = basis.waveId(waveDft);
305 starId = basis.wave(waveId).starId;
306 starPtr = &basis.star(starId);
307 UTIL_CHECK(!(starPtr->cancel));
308 basisId = starPtr->basisId;
309
310 if (starPtr->size == sizeIn) {
311 sizeMatches = true;
312 } else {
313 Log::file()
314 << "Warning: Inconsistent star size (line ignored)\n"
315 << "wave from file = " << waveIn << "\n"
316 << "size from file = " << sizeIn << "\n"
317 << "size of star = " << starPtr->size
318 << "\n";
319 sizeMatches = false;
320 }
321
322 }
323
324 if (waveExists && sizeMatches) { // Attempt to process wave
325
326 if (starPtr->invertFlag == 0) {
327
328 if (starPtr->waveMin == waveIn) {
329
330 // Copy components of closed star to fields array
331 for (int j = 0; j < nMonomer; ++j) {
332 fields[j][basisId] = temp[j];
333 }
334
335 } else {
336
337 Log::file()
338 << "Inconsistent wave of closed star on input\n"
339 << "wave from file = " << waveIn << "\n"
340 << "starId of wave = " << starId << "\n"
341 << "waveMin of star = " << starPtr->waveMin
342 << "\n";
343
344 }
345
346 } else {
347
348 // Read the next line
349 for (int j = 0; j < nMonomer; ++j) {
350 in >> temp2[j]; // components of field
351 }
352 in >> waveIn2; // wave of star
353 in >> sizeIn2; // # of wavevectors in star
354 UTIL_CHECK(!in.fail());
355 ++i;
356
357 // Check that waveIn2 is also in the 1st BZ
358 waveMin =
359 shiftToMinimum(waveIn2, mesh.dimensions(), unitCell);
360 UTIL_CHECK(waveIn2 == waveMin);
361
362 // Identify the star containing waveIn2
363 waveDft = waveIn2;
364 mesh.shift(waveDft);
365 waveId2 = basis.waveId(waveDft);
366 starId2 = basis.wave(waveId2).starId;
367 starPtr2 = &basis.star(starId2);
368 UTIL_CHECK(!(starPtr2->cancel));
369 basisId2 = starPtr2->basisId;
370 UTIL_CHECK(starPtr2->size == sizeIn2);
371 UTIL_CHECK(sizeIn == sizeIn2);
372
373 if (starPtr->invertFlag == 1) {
374
375 // This is a pair of open stars written in the same
376 // order as in this basis. Check preconditions:
377 UTIL_CHECK(starPtr2->invertFlag == -1);
378 UTIL_CHECK(starId2 == starId + 1);
379 UTIL_CHECK(basisId2 == basisId + 1);
380 UTIL_CHECK(starPtr->waveMin == waveIn);
381 UTIL_CHECK(starPtr2->waveMin == waveIn2);
382
383 // Copy components for both stars into fields array
384 for (int j = 0; j < nMonomer; ++j) {
385 fields[j][basisId] = temp[j];
386 fields[j][basisId2] = temp2[j];
387 }
388
389 } else
390 if (starPtr->invertFlag == -1) {
391
392 // This is a pair of open stars written in opposite
393 // order from in this basis. Check preconditions:
394 UTIL_CHECK(starPtr2->invertFlag == 1);
395 UTIL_CHECK(starId == starId2 + 1);
396 UTIL_CHECK(basisId == basisId2 + 1);
397 UTIL_CHECK(waveId == starPtr->beginId);
398
399 // Check that waveIn2 is negation of waveIn
400 IntVec<D> nVec;
401 nVec.negate(waveIn);
402 nVec =
403 shiftToMinimum(nVec, mesh.dimensions(), unitCell);
404 UTIL_CHECK(waveIn2 == nVec);
405
406 /*
407 * Consider two related stars, C and D, that are listed
408 * in the order (C,D) in the basis used in this code (the
409 * reading program), but that were listed in the opposite
410 * order (D,C) in the program that wrote the file (the
411 * writing program). In the basis of the reading program,
412 * star C has star index starId2, while star D has index
413 * starId = starid2 + 1.
414 *
415 * Let f(r) and f^{*}(r) denote the basis functions used
416 * by the reading program for stars C and D, respectively.
417 * Let u(r) and u^{*}(r) denote the corresponding basis
418 * functions used by the writing program for stars C
419 * and D. Let exp(i phi) denote the unit magnitude
420 * coefficient (i.e., phasor) within f(r) of the wave
421 * with wave index waveId2, which was the characteristic
422 * wave for star C in the writing program. The
423 * coefficient of this wave within the basis function
424 * u(r) used by the writing program must instead be real
425 * and positive. This implies that
426 * u(r) = exp(-i phi) f(r).
427 *
428 * Focus on the contribution to the field for a specific
429 * monomer type j. Let a and b denote the desired
430 * coefficients of stars C and D in the reading program,
431 * for which the total contribution of both stars to the
432 * field is:
433 *
434 * (a - ib) f(r) + (a + ib) f^{*}(r)
435 *
436 * Let A = temp[j] and B = temp2[j] denote the
437 * coefficients read from file in order (A,B). Noting
438 * that the stars were listed in the order (D,C) in the
439 * basis used by the writing program, the contribution
440 * of both stars must be (A-iB)u^{*}(r)+(A+iB)u(r), or:
441 *
442 * (A+iB) exp(-i phi)f(r) + (A-iB) exp(i phi) f^{*}(r)
443 *
444 * Comparing coefficients of f^{*}(r), we find that
445 *
446 * (a + ib) = (A - iB) exp(i phi)
447 *
448 * This equality is implemented below, where the
449 * variable "phasor" is set equal to exp(i phi).
450 */
451 phasor = basis.wave(waveId2).coeff;
452 phasor = phasor/std::abs(phasor);
453 for (int j = 0; j < nMonomer; ++j) {
454 coeff = std::complex<double>(temp[j],-temp2[j]);
455 coeff *= phasor;
456 fields[j][basisId2] = real(coeff);
457 fields[j][basisId ] = imag(coeff);
458 }
459
460 // Increment count of number of reversed open pairs
461 ++nReversedPair;
462
463 } else {
464 UTIL_THROW("Invalid starInvert value");
465 }
466
467 } // if (wavePtr->invertFlag == 0) ... else ...
468
469 } // if (waveExists && sizeMatches)
470
471 } // end while (i < nBasis)
472
473 if (nReversedPair > 0) {
474 Log::file() << "\n";
475 Log::file() << nReversedPair << " reversed pairs of open stars"
476 << " detected in readFieldsBasis\n";
477 }
478
479 }
480
481 /*
482 * Read the data section for a single field in basis format.
483 */
484 template <int D>
485 void readBasisData(std::istream& in,
486 DArray<double>& field,
487 UnitCell<D> const& unitCell,
488 Mesh<D> const& mesh,
489 Basis<D> const& basis,
490 int nBasisIn)
491 {
492 UTIL_CHECK(field.isAllocated());
493
494 // Local array of fields containing only one field
495 DArray< DArray<double> > fields;
496 fields.allocate(1);
497 fields[0].allocate(field.capacity());
498
499 // Call overloaded function that takes an array of fields
500 readBasisData(in, fields, unitCell, mesh, basis, nBasisIn);
501
502 // Copy data from local array fields to function parameter field
503 field = fields[0];
504 }
505
506 /*
507 * Write an array of fields in basis format to an output stream.
508 */
509 template <int D>
510 void writeBasisData(std::ostream &out,
511 DArray< DArray<double> > const & fields,
512 Basis<D> const & basis)
513 {
514 // Preconditions, set nMonomer and fieldCapacity
515 int nMonomer = fields.capacity();
516 UTIL_CHECK(nMonomer > 0);
517 int fieldCapacity = fields[0].capacity();
518 for (int j = 0; j < nMonomer; ++j) {
519 UTIL_CHECK(fieldCapacity == fields[j].capacity());
520 }
521 UTIL_CHECK(basis.isInitialized());
522
523 // Write fields
524 int ib = 0;
525 int nStar = basis.nStar();
526 for (int i = 0; i < nStar; ++i) {
527 if (ib >= fieldCapacity) break;
528 if (!basis.star(i).cancel) {
529 for (int j = 0; j < nMonomer; ++j) {
530 out << Dbl(fields[j][ib], 20, 10);
531 }
532 // Each integer column is preceded by a space, so that
533 // columns stay separated when a value fills its width
534 out << " ";
535 for (int j = 0; j < D; ++j) {
536 out << ' ' << Int(basis.star(i).waveMin[j], 4);
537 }
538 out << ' ' << Int(basis.star(i).size, 4) << std::endl;
539 ++ib;
540 }
541 }
542
543 }
544
545 /*
546 * Write data section of a single field in basis format.
547 */
548 template <int D>
549 void writeBasisData(std::ostream &out,
550 DArray<double> const & field,
551 Basis<D> const & basis)
552 {
553 UTIL_CHECK(field.isAllocated());
554
555 // Local array of fields containing only one field
556 DArray< DArray<double> > fields;
557 fields.allocate(1);
558 fields[0].allocate(field.capacity());
559 fields[0] = field;
560
561 // Call overloaded function that takes and array of fields
562 writeBasisData(out, fields, basis);
563 }
564
565 // Conversion between basis and k-grid formats
566
567 /*
568 * Convert an array of fields from basis to k-grid format.
569 */
570 template <int D, class ACT>
571 void convertBasisToKGrid(DArray<double> const & in,
572 ACT& out,
573 Basis<D> const& basis,
574 IntVec<D> const& dftDimensions)
575 {
576 UTIL_CHECK(basis.isInitialized());
577
578 // Create Mesh<D> with dimensions of DFT Fourier grid.
579 Mesh<D> dftMesh(dftDimensions);
580
581 typename Basis<D>::Star const* starPtr; // pointer to current star
582 typename Basis<D>::Wave const* wavePtr; // pointer to current wave
583 std::complex<double> component; // coefficient for star
584 std::complex<double> coeff; // coefficient for wave
585 IntVec<D> indices; // dft grid indices of wave
586 int rank; // dft grid rank of wave
587 int is; // star index
588 int ib; // basis index
589 int iw; // wave index
590
591 // Initialize all dft coponents to zero
592 for (rank = 0; rank < dftMesh.size(); ++rank) {
593 assign(out[rank], 0.0, 0.0);
594 }
595
596 // Loop over stars, skipping cancelled stars
597 is = 0;
598 while (is < basis.nStar()) {
599 starPtr = &(basis.star(is));
600
601 if (starPtr->cancel) {
602 ++is;
603 continue;
604 }
605
606 // Set basisId for uncancelled star
607 ib = starPtr->basisId;
608
609 if (starPtr->invertFlag == 0) {
610
611 // Make complex coefficient for star basis function
612 component = std::complex<double>(in[ib], 0.0);
613
614 // Loop over waves in closed star
615 for (iw = starPtr->beginId; iw < starPtr->endId; ++iw) {
616 wavePtr = &basis.wave(iw);
617 if (!wavePtr->implicit) {
618 coeff = component*(wavePtr->coeff);
619 indices = wavePtr->indicesStd;
620 rank = dftMesh.rank(indices);
621 //out[rank][0] = coeff.real();
622 //out[rank][1] = coeff.imag();
623 assign(out[rank], coeff);
624 }
625 }
626 ++is;
627
628 } else
629 if (starPtr->invertFlag == 1) {
630
631 // Loop over waves in first star
632 component = std::complex<double>(in[ib], -in[ib+1]);
633 component /= sqrt(2.0);
634 starPtr = &(basis.star(is));
635 for (iw = starPtr->beginId; iw < starPtr->endId; ++iw) {
636 wavePtr = &basis.wave(iw);
637 if (!(wavePtr->implicit)) {
638 coeff = component*(wavePtr->coeff);
639 indices = wavePtr->indicesStd;
640 rank = dftMesh.rank(indices);
641 //out[rank][0] = coeff.real();
642 //out[rank][1] = coeff.imag();
643 assign(out[rank], coeff);
644 }
645 }
646
647 // Loop over waves in second star
648 starPtr = &(basis.star(is+1));
649 UTIL_CHECK(starPtr->invertFlag == -1);
650 component = std::complex<double>(in[ib], +in[ib+1]);
651 component /= sqrt(2.0);
652 for (iw = starPtr->beginId; iw < starPtr->endId; ++iw) {
653 wavePtr = &basis.wave(iw);
654 if (!(wavePtr->implicit)) {
655 coeff = component*(wavePtr->coeff);
656 indices = wavePtr->indicesStd;
657 rank = dftMesh.rank(indices);
658 //out[rank][0] = coeff.real();
659 //out[rank][1] = coeff.imag();
660 assign(out[rank], coeff);
661 }
662 }
663
664 // Increment is by 2 (two stars were processed)
665 is += 2;
666
667 } else {
668
669 UTIL_THROW("Invalid invertFlag value");
670
671 }
672
673 }
674
675 }
676
677 template <int D, class ACT>
678 void convertKGridToBasis(ACT const& in,
679 DArray<double>& out,
680 Basis<D> const& basis,
681 IntVec<D> const& dftDimensions,
682 bool checkSymmetry,
683 double epsilon)
684 {
685 UTIL_CHECK(basis.isInitialized());
686
687 // Check if input field in k-grid format has specified symmetry
688 if (checkSymmetry) {
689 bool symmetric;
690 symmetric = hasSymmetry(in, basis, dftDimensions, epsilon, true);
691 if (!symmetric) {
692 Log::file() << std::endl
693 << "WARNING: Conversion of asymmetric field to"
694 << "symmetry-adapted basis in convertKgridToBasis."
695 << std::endl << std::endl;
696 }
697 }
698
699 // Create Mesh<D> with dimensions of DFT Fourier grid.
700 Mesh<D> dftMesh(dftDimensions);
701
702 typename Basis<D>::Star const* starPtr; // pointer to current star
703 typename Basis<D>::Wave const* wavePtr; // pointer to current wave
704 std::complex<double> component; // coefficient for star
705 int rank; // dft grid rank of wave
706 int is; // star index
707 int ib; // basis index
708 int iw; // wave index
709
710 // Initialize all components to zero
711 for (is = 0; is < basis.nBasis(); ++is) {
712 out[is] = 0.0;
713 }
714
715 // Loop over stars
716 is = 0;
717 while (is < basis.nStar()) {
718 starPtr = &(basis.star(is));
719
720 if (starPtr->cancel) {
721 ++is;
722 continue;
723 }
724
725 // Set basis id for uncancelled star
726 ib = starPtr->basisId;
727
728 if (starPtr->invertFlag == 0) {
729
730 // Choose a wave in the star that is not implicit
731 int beginId = starPtr->beginId;
732 int endId = starPtr->endId;
733 iw = 0;
734 bool isImplicit = true;
735 while (isImplicit) {
736 wavePtr = &basis.wave(beginId + iw);
737 if (!wavePtr->implicit) {
738 isImplicit = false;
739 } else {
740 UTIL_CHECK(beginId + iw < endId - 1 - iw);
741 wavePtr = &basis.wave(endId - 1 - iw);
742 if (!wavePtr->implicit) {
743 isImplicit = false;
744 }
745 }
746 ++iw;
747 }
748 UTIL_CHECK(wavePtr->starId == is);
749
750 // Compute component value
751 rank = dftMesh.rank(wavePtr->indicesStd);
752 //component = std::complex<double>(in[rank][0], in[rank][1]);
753 assign(component, in[rank]);
754 component /= wavePtr->coeff;
755 out[ib] = component.real();
756 ++is;
757
758 } else
759 if (starPtr->invertFlag == 1) {
760
761 // Identify a characteristic wave that is not implicit:
762 // Either the first wave of the 1st star or its inverse
763 // in the second star
764 wavePtr = &basis.wave(starPtr->beginId);
765 UTIL_CHECK(wavePtr->starId == is);
766 if (wavePtr->implicit) {
767 iw = wavePtr->inverseId;
768 starPtr = &(basis.star(is+1));
769 UTIL_CHECK(starPtr->invertFlag == -1);
770 wavePtr = &basis.wave(iw);
771 UTIL_CHECK(!(wavePtr->implicit));
772 UTIL_CHECK(wavePtr->starId == is+1);
773 }
774 rank = dftMesh.rank(wavePtr->indicesStd);
775 //component = std::complex<double>(in[rank][0], in[rank][1]);
776 assign(component, in[rank]);
777 UTIL_CHECK(std::abs(wavePtr->coeff) > 1.0E-8);
778 component /= wavePtr->coeff;
779 component *= sqrt(2.0);
780
781 // Compute basis function coefficient values
782 if (starPtr->invertFlag == 1) {
783 out[ib] = component.real();
784 out[ib+1] = -component.imag();
785 } else {
786 out[ib] = component.real();
787 out[ib+1] = component.imag();
788 }
789
790 is += 2;
791 } else {
792 UTIL_THROW("Invalid invertFlag value");
793 }
794
795 } // loop over star index is
796 }
797
798 /*
799 * Test if an K-grid array has the declared space group symmetry.
800 * Return true if symmetric, false otherwise. Print error values
801 * if verbose == true and hasSymmetry == false.
802 */
803 template <int D, class ACT>
804 bool hasSymmetry(ACT const & in,
805 Basis<D> const& basis,
806 IntVec<D> const& dftDimensions,
807 double epsilon,
808 bool verbose)
809 {
810 UTIL_CHECK(basis.isInitialized());
811
812 typename Basis<D>::Star const* starPtr; // pointer to current star
813 typename Basis<D>::Wave const* wavePtr; // pointer to current wave
814 std::complex<double> waveCoeff; // coefficient from wave
815 std::complex<double> rootCoeff; // coefficient from root
816 int is; // star index
817 int iw; // wave index
818 int beginId, endId; // star begin, end ids
819 int rank; // dft grid rank of wave
820
821 double error; // error in current wave coefficent
822 double cancelledError(0.0); // max error from cancelled stars
823 double uncancelledError(0.0); // max error from uncancelled stars
824 bool result = true; // true iff field has symmetry
825
826 // Create Mesh<D> with dimensions of DFT Fourier grid.
827 Mesh<D> dftMesh(dftDimensions);
828
829 // Loop over all stars
830 for (is = 0; is < basis.nStar(); ++is) {
831 starPtr = &(basis.star(is));
832
833 if (starPtr->cancel) {
834
835 // Check that coefficients are zero for all waves in star
836 beginId = starPtr->beginId;
837 endId = starPtr->endId;
838 for (iw = beginId; iw < endId; ++iw) {
839 wavePtr = &basis.wave(iw);
840 if (!wavePtr->implicit) {
841 rank = dftMesh.rank(wavePtr->indicesStd);
842 assign(waveCoeff, in[rank]);
843 error = std::abs(waveCoeff);
844 if (error > cancelledError) {
845 cancelledError = error;
846 if (cancelledError > epsilon) {
847 result = false;
848 }
849 }
850 }
851 }
852
853 } else {
854
855 // Check consistency of coeff values from all waves
856 bool hasRoot = false;
857 beginId = starPtr->beginId;
858 endId = starPtr->endId;
859 for (iw = beginId; iw < endId; ++iw) {
860 wavePtr = &basis.wave(iw);
861 if (!(wavePtr->implicit)) {
862 rank = dftMesh.rank(wavePtr->indicesStd);
863 assign(waveCoeff, in[rank]);
864 waveCoeff /= wavePtr->coeff;
865 if (hasRoot) {
866 error = std::abs(waveCoeff - rootCoeff);
867 if (error > uncancelledError) {
868 uncancelledError = error;
869 if (uncancelledError > epsilon) {
870 result = false;
871 }
872 }
873 } else {
874 // First explicit wave is the root
875 rootCoeff = waveCoeff;
876 hasRoot = true;
877 }
878 }
879 }
880
881 // Require that rootCoeff be real for closed stars
882 if (starPtr->invertFlag == 0) {
883 error = std::abs(rootCoeff.imag());
884 if (error > uncancelledError) {
885 uncancelledError = error;
886 if (uncancelledError > epsilon) {
887 result = false;
888 }
889 }
890 }
891
892 }
893
894 } // end loop over star index is
895
896 // Verbose report on failure
897 if (!result && verbose) {
898 Log::file()
899 << std::endl
900 << "Maximum coefficient of a cancelled star: "
901 << cancelledError << std::endl
902 << "Maximum error of coefficient for an uncancelled star: "
903 << uncancelledError << std::endl;
904 }
905
906 return result;
907 }
908
909 // Field file manipulations
910
911 template <int D, class AT>
912 void replicateUnitCell(std::ostream &out,
913 DArray<AT> const & fields,
914 IntVec<D> const & meshDimensions,
915 UnitCell<D> const & unitCell,
916 IntVec<D> const & replicas)
917 {
918 // Obtain number of monomer types
919 int nMonomer = fields.capacity();
920 UTIL_CHECK(nMonomer > 0);
921
922 // Compute properties of mesh for replicated fields
923 IntVec<D> repDimensions; // Dimensions
924 int repSize = 1; // Total number of grid points
925 for (int i = 0; i < D; ++i) {
926 UTIL_CHECK(replicas[i] > 0);
927 UTIL_CHECK(meshDimensions[i] > 0);
928 repDimensions[i] = replicas[i] * meshDimensions[i];
929 repSize *= repDimensions[i];
930 }
931
932 // Allocate arrays for replicated fields
933 DArray< DArray<double> > repFields;
934 repFields.allocate(nMonomer);
935 for (int i = 0; i < nMonomer; ++i) {
936 repFields[i].allocate(repSize);
937 }
938
939 // Replicate data
940 Mesh<D> mesh(meshDimensions);
941 Mesh<D> cellMesh(replicas);
942 Mesh<D> repMesh(repDimensions);
943 MeshIterator<D> iter(meshDimensions);
944 MeshIterator<D> cellIter(replicas);
945 IntVec<D> position;
946 IntVec<D> cellPosition;
947 IntVec<D> repPosition;
948 double value;
949 int repRank;
950 for (int i = 0; i < nMonomer; ++i) {
951 for (iter.begin(); !iter.atEnd(); ++iter) {
952 position = iter.position();
953 value = fields[i][iter.rank()];
954 for (cellIter.begin(); !cellIter.atEnd(); ++cellIter) {
955 cellPosition = cellIter.position();
956 for (int j=0; j < D; ++j) {
957 repPosition[j] = position[j]
958 + meshDimensions[j]*cellPosition[j];
959 }
960 repRank = repMesh.rank(repPosition);
961 repFields[i][repRank] = value;
962 }
963 }
964 }
965
966 // Create a replicated UnitCell<D> object
967 // Use function declared in pscf/crystal/replicateUnitCell.h
968 UnitCell<D> cell;
969 replicateUnitCell(replicas, unitCell, cell);
970
971 // Write header
972 int v1 = 1;
973 int v2 = 0;
974 std::string gName = "";
975 Pscf::writeFieldHeader(out, v1, v2, cell, gName, nMonomer);
976 writeMeshDimensions(out, repDimensions);
977
978 // Write field data
979 writeRGridData(out, repFields, nMonomer, repDimensions);
980 }
981
982 template <int D, class AT>
983 void
984 expandRGridDimension(std::ostream &out,
985 DArray<AT> const & fields,
986 IntVec<D> const & meshDimensions,
987 UnitCell<D> const & unitCell,
988 int d,
989 DArray<int> newGridDimensions)
990 {
991 UTIL_THROW("Unimplemented base template");
992 }
993
994 template <class AT>
995 void
996 expandRGridDimension(std::ostream &out,
997 DArray<AT> const & fields,
998 IntVec<1> const & meshDimensions,
999 UnitCell<1> const & unitCell,
1000 int d,
1001 DArray<int> newGridDimensions)
1002
1003 {
1004 // Check validity of expanded dimension d and newGridDimensions
1005 UTIL_CHECK(d > 1);
1006 UTIL_CHECK(d <= 3);
1007 UTIL_CHECK(newGridDimensions.capacity() == (d - 1));
1008
1009
1010 // Obtain number of monomer types
1011 int nMonomer = fields.capacity();
1012 UTIL_CHECK(nMonomer > 0);
1013
1014 // Set up necessary objects
1015 FSArray<double, 6> cellParameters;
1016 cellParameters.append(unitCell.parameter(0));
1017 int v1 = 1;
1018 int v2 = 0;
1019 std::string gName = "";
1020
1021 if (d == 2) {
1022
1023 // 1D expanded to 2D
1024
1025 // Set dimensions
1026 IntVec<2> dimensions;
1027 dimensions[0] = meshDimensions[0];
1028 dimensions[1] = newGridDimensions[0];
1029
1030 // Assign unit cell
1031 UnitCell<2> cell;
1032 if (dimensions[0] == dimensions[1]) {
1033 cell.set(UnitCell<2>::Square, cellParameters);
1034 } else {
1035 cellParameters.append((double)dimensions[1]/dimensions[0]
1036 * cellParameters[0]);
1037 cell.set(UnitCell<2>::Rectangular, cellParameters);
1038 }
1039
1040 // Write Header
1041 Pscf::writeFieldHeader(out, v1, v2, cell, gName, nMonomer);
1042 out << "mesh " << std::endl
1043 << " " << dimensions << std::endl;
1044
1045 } else if (d == 3) {
1046
1047 // 1D expanded to 3D
1048
1049 // Set dimensions
1050 IntVec<3> dimensions;
1051 dimensions[0] = meshDimensions[0];
1052 dimensions[1] = newGridDimensions[0];
1053 dimensions[2] = newGridDimensions[1];
1054
1055 // Assign unit cell
1056 UnitCell<3> cell;
1057 if (dimensions[2] == dimensions[1]) {
1058 if (dimensions[1] == dimensions[0]) {
1059 cell.set(UnitCell<3>::Cubic, cellParameters);
1060 } else {
1061 cellParameters.append((double)dimensions[1]/dimensions[0]
1062 * cellParameters[0]);
1063 cellParameters.append((double)dimensions[2]/dimensions[0]
1064 * cellParameters[0]);
1065 cell.set(UnitCell<3>::Orthorhombic, cellParameters);
1066 }
1067 } else {
1068 if (dimensions[1] == dimensions[0]) {
1069 cellParameters.append((double)dimensions[2]/dimensions[0]
1070 * cellParameters[0]);
1071 cell.set(UnitCell<3>::Tetragonal, cellParameters);
1072 } else {
1073 cellParameters.append((double)dimensions[1]/dimensions[0]
1074 * cellParameters[0]);
1075 cellParameters.append((double)dimensions[2]/dimensions[0]
1076 * cellParameters[0]);
1077 cell.set(UnitCell<3>::Orthorhombic, cellParameters);
1078 }
1079 }
1080
1081 // Write Header
1082 Pscf::writeFieldHeader(out, v1, v2, cell, gName, nMonomer);
1083 out << "mesh " << std::endl
1084 << " " << dimensions << std::endl;
1085
1086 } else {
1087
1088 UTIL_THROW("Invalid d value");
1089
1090 }
1091
1092 // Write expanded fields
1093 int nReplica = newGridDimensions[0];
1094 if (d == 3) {
1095 nReplica *= newGridDimensions[1];
1096 }
1097 MeshIteratorFortran<1> iter(meshDimensions);
1098 int rank;
1099 for (int i = 0; i < nReplica; ++i) {
1100 for (iter.begin(); !iter.atEnd(); ++iter) {
1101 rank = iter.rank();
1102 for (int j = 0; j < nMonomer; ++j) {
1103 out << " " << Dbl(fields[j][rank], 21, 13);
1104 }
1105 out << std::endl;
1106 }
1107 }
1108
1109 }
1110
1111 template <class AT>
1112 void expandRGridDimension(std::ostream &out,
1113 DArray<AT> const & fields,
1114 IntVec<2> const & meshDimensions,
1115 UnitCell<2> const & unitCell,
1116 int d,
1117 DArray<int> newGridDimensions)
1118 {
1119 // 2D expanded to 3D
1120
1121 // Check validity of expanded dimension d and newGridDimensions
1122 UTIL_CHECK(d == 3);
1123 UTIL_CHECK(newGridDimensions.capacity() == 1);
1124
1125 // Obtain number of monomer types
1126 int nMonomer = fields.capacity();
1127 UTIL_CHECK(nMonomer > 0);
1128
1129 // Set dimensions of mesh for replicated fields
1130 IntVec<3> dimensions;
1131 dimensions[0] = meshDimensions[0];
1132 dimensions[1] = meshDimensions[1];
1133 dimensions[2] = newGridDimensions[0];
1134
1135 // Set unit cell for replicated fields
1136 UnitCell<3> cell;
1137 FSArray<double, 6> cellParameters;
1138 cellParameters.append(unitCell.parameter(0));
1139 if (unitCell.lattice() == UnitCell<2>::Square) {
1140 if (newGridDimensions[0] == meshDimensions[0]){
1141 cell.set(UnitCell<3>::Cubic, cellParameters);
1142 } else {
1143 cellParameters.append((double)dimensions[2]/dimensions[0]
1144 * cellParameters[0]);
1145 cell.set(UnitCell<3>::Tetragonal, cellParameters);
1146 }
1147 } else if (unitCell.lattice() == UnitCell<2>::Rectangular) {
1148 cellParameters.append(unitCell.parameter(1));
1149 cellParameters.append((double)dimensions[2]/dimensions[0]
1150 * cellParameters[0]);
1151 cell.set(UnitCell<3>::Orthorhombic, cellParameters);
1152 } else if (unitCell.lattice() == UnitCell<2>::Hexagonal){
1153 cellParameters.append((double)dimensions[2]/dimensions[0]
1154 * cellParameters[0]);
1155 cell.set(UnitCell<3>::Hexagonal, cellParameters);
1156 } else if (unitCell.lattice() == UnitCell<2>::Rhombic) {
1157 cellParameters.append(unitCell.parameter(0));
1158 cellParameters.append((double)dimensions[2]/dimensions[0]
1159 * cellParameters[0]);
1160 cellParameters.append(Constants::Pi / 2);
1161 cellParameters.append(0.0);
1162 cellParameters.append(unitCell.parameter(1));
1163 cell.set(UnitCell<3>::Triclinic, cellParameters);
1164 } else if (unitCell.lattice() == UnitCell<2>::Oblique) {
1165 cellParameters.append(unitCell.parameter(1));
1166 cellParameters.append((double)dimensions[2]/dimensions[0]
1167 * cellParameters[0]);
1168 cellParameters.append(Constants::Pi / 2);
1169 cellParameters.append(0.0);
1170 cellParameters.append(unitCell.parameter(2));
1171 cell.set(UnitCell<3>::Triclinic, cellParameters);
1172 } else {
1173 UTIL_THROW("Unrecognized 2D lattice system.");
1174 }
1175
1176 // Write Header
1177 int v1 = 1;
1178 int v2 = 0;
1179 std::string gName = "";
1180 Pscf::writeFieldHeader(out, v1, v2, cell, gName, nMonomer);
1181 out << "mesh " << std::endl
1182 << " " << dimensions << std::endl;
1183
1184 // Write expanded fields
1185 int nReplica = newGridDimensions[0];
1186 MeshIteratorFortran<2> iter(meshDimensions);
1187 int rank;
1188 for (int i = 0; i < nReplica; ++i) {
1189 for (iter.begin(); !iter.atEnd(); ++iter) {
1190 rank = iter.rank();
1191 for (int j = 0; j < nMonomer; ++j) {
1192 out << " " << Dbl(fields[j][rank], 21, 13);
1193 }
1194 out << std::endl;
1195 }
1196 }
1197
1198 }
1199
1200 template <class AT>
1201 void expandRGridDimension(std::ostream &out,
1202 DArray<AT> const & fields,
1203 IntVec<3> const & meshDimensions,
1204 UnitCell<3> const & unitCell,
1205 int d,
1206 DArray<int> newGridDimensions)
1207
1208 { UTIL_THROW("expandRGridDimension is invalid when D = 3."); }
1209
1210} // namespace Pscf
1211#endif
A list of wavevectors that are related by space-group symmetries.
Definition Basis.h:495
int size
Number of wavevectors in this star.
Definition Basis.h:502
int invertFlag
Index for inversion symmetry of star.
Definition Basis.h:556
int basisId
Index of basis function associated with this star.
Definition Basis.h:583
int beginId
Wave index of the first wavevector in this star.
Definition Basis.h:507
bool cancel
Is this star cancelled, i.e., associated with a zero function?
Definition Basis.h:598
IntVec< D > waveMin
Minimal indices of the root wave of this star.
Definition Basis.h:564
Wavevector used to construct a basis function.
Definition Basis.h:392
std::complex< double > coeff
Coefficient of wave within the associated star basis function.
Definition Basis.h:402
int starId
Index of the star that contains this wavevector.
Definition Basis.h:431
Symmetry-adapted Fourier basis for pseudo-spectral SCFT.
Definition Basis.h:384
bool isInitialized() const
Returns true iff this basis is fully initialized.
Definition Basis.h:926
Star const & star(int id) const
Get a Star, accessed by integer star index.
Definition Basis.h:906
int waveId(IntVec< D > vector) const
Get the integer index of a wave, as required by wave(int id).
Definition Basis.h:914
int nStar() const
Total number of stars.
Definition Basis.h:898
Wave const & wave(int id) const
Get a specific Wave, access by integer index.
Definition Basis.h:902
An IntVec<D, T> is a D-component vector of elements of integer type T.
Definition IntVec.h:27
Iterator over points in a mesh in "Fortran" order.
int rank() const
Return the scalar array rank of the associated grid point.
void begin()
Initialize the iterator to the first grid point.
bool atEnd() const
Is this the end (i.e., past the last grid point)?
Iterator over points in a Mesh<D>.
int rank() const
Get the rank of current element.
void begin()
Set iterator to the first point in the mesh.
bool atEnd() const
Is this the end (i.e., one past the last point)?
IntVec< D > position() const
Get current position in the grid, as integer vector.
Description of a regular grid of points in a periodic domain.
Definition Mesh.h:61
IntVec< D > dimensions() const
Get an IntVec<D> of the grid dimensions.
Definition Mesh.h:217
int rank(IntVec< D > const &position) const
Get the rank of a grid point with specified position.
Definition Mesh.tpp:72
int shift(int &coordinate, int i) const
Shift a periodic coordinate into range.
Definition Mesh.tpp:131
Base template for UnitCell<D> classes, D=1, 2 or 3.
Definition UnitCell.h:55
Vec< D, T > & negate(const Vec< D, T > &v)
Return negative of vector v.
Definition Vec.h:520
int capacity() const
Return allocated size.
Definition Array.h:250
bool isAllocated() const
Does this array have associated data?
Definition Array.h:236
static const double Pi
Trigonometric constant Pi.
Definition Constants.h:35
Dynamically allocatable contiguous array template.
Definition DArray.h:32
void allocate(int capacity)
Allocate the underlying C array.
Definition DArray.h:262
Dbl()
Default constructor.
Definition Dbl.cpp:17
A fixed capacity (static) contiguous array with a variable logical size.
Definition FSArray.h:38
void append(Data const &data)
Append data to the end of the array.
Definition FSArray.h:261
Int()
Default constructor.
Definition Int.cpp:19
static std::ostream & file()
Get log ostream by reference.
Definition Log.cpp:59
#define UTIL_CHECK(condition)
Assertion macro suitable for serial or parallel production code.
Definition global.h:68
#define UTIL_THROW(msg)
Macro for throwing an Exception, reporting function, file and line number.
Definition global.h:49
double imag(fftw_complex const &a)
Return the imaginary part of an fftw_complex number.
Definition cpp/complex.h:49
void assign(fftw_complex &z, double const &a, double const &b)
Create an fftw_complex from real and imaginary parts, z = a + ib.
double real(fftw_complex const &a)
Return the real part of an fftw_complex number.
Definition cpp/complex.h:38
void replicateUnitCell(IntVec< 1 > const &replicas, UnitCell< 1 > const &cellIn, UnitCell< 1 > &cellOut)
Create a replicated UnitCell<1>.
bool hasSymmetry(AT const &in, Basis< D > const &basis, IntVec< D > const &dftDimensions, double epsilon=1.0e-8, bool verbose=true)
Check if a k-grid field has the declared space group symmetry.
void writeKGridData(std::ostream &out, DArray< AT > const &fields, int nMonomer, IntVec< D > const &dftDimensions)
Write data for array of k-grid fields, with no header section.
void readRGridData(std::istream &in, DArray< AT > &fields, int nMonomer, IntVec< D > const &dimensions)
Read data for array of r-grid fields, with no header section.
Definition rFieldIo.tpp:38
void readBasisData(std::istream &in, DArray< DArray< double > > &fields, UnitCell< D > const &unitCell, Mesh< D > const &mesh, Basis< D > const &basis, int nStarIn)
Read an array of fields in basis format, without a header.
Definition rFieldIo.tpp:232
void writeMeshDimensions(std::ostream &out, IntVec< D > const &meshDimensions)
Write mesh dimensions to a field file header.
void convertKGridToBasis(AT const &in, DArray< double > &out, Basis< D > const &basis, IntVec< D > const &dftDimensions, bool checkSymmetry=true, double epsilon=1.0e-8)
Convert a real field from Fourier grid to symmetrized basis.
void writeRGridData(std::ostream &out, DArray< AT > const &fields, int nMonomer, IntVec< D > const &dimensions)
Write data for array of r-grid fields, with no header section.
Definition rFieldIo.tpp:76
void expandRGridDimension(std::ostream &out, DArray< AT > const &fields, IntVec< D > const &meshDimensions, UnitCell< D > const &unitCell, int d, DArray< int > newGridDimensions)
Expand the dimensionality of space from D to d.
Definition rFieldIo.tpp:984
void writeFieldHeader(std::ostream &out, int ver1, int ver2, UnitCell< D > const &cell, std::string const &groupName, int nMonomer)
Write common part of field header (fortran PSCF format).
void writeBasisData(std::ostream &out, DArray< DArray< double > > const &fields, Basis< D > const &basis)
Write data section of an array of fields in basis format.
Definition rFieldIo.tpp:510
void convertBasisToKGrid(DArray< double > const &components, AT &dft, Basis< D > const &basis, IntVec< D > const &dftDimensions)
Convert a real field from symmetrized basis to Fourier grid.
void readKGridData(std::istream &in, DArray< AT > &fields, int nMonomer, IntVec< D > const &dftDimensions)
Read data for array of k-grid fields, with no header section.
PSCF package top-level namespace.