PSCF v1.5.0
BinaryStructureFactor.tpp
1#ifndef RP_BINARY_STRUCTURE_FACTOR_TPP
2#define RP_BINARY_STRUCTURE_FACTOR_TPP
3
4#include "BinaryStructureFactor.h"
5
6#include <rp/fts/simulator/Simulator.h>
7#include <rp/system/System.h>
8#include <rp/solvers/Mixture.h>
9#include <rp/field/Domain.h>
10#include <rp/field/WFields.h>
11
12#include <pscf/field/FFT.h>
13#include <pscf/field/WaveList.h>
14
15#include <pscf/backend/HostRecvArray.h>
16#include <pscf/backend/VecOp.h>
17#include <pscf/backend/complex.h>
18#include <pscf/interaction/Interaction.h>
19#include <pscf/mesh/MeshIterator.h>
20#include <pscf/mesh/Mesh.h>
21#include <pscf/math/IntVec.h>
22
23#include <util/param/ParamComposite.h>
24#include <util/containers/Array.h>
25#include <util/containers/ConstArray.h>
26#include <util/misc/FileMaster.h>
27#include <util/format/Dbl.h>
28#include <util/format/Int.h>
29#include <util/global.h>
30
31#include <iostream>
32#include <complex>
33
34namespace Pscf {
35namespace Rp {
36
37 using namespace Util;
38
39 // Public member functions
40
41 /*
42 * Constructor.
43 */
44 template <int D, class T>
48 : Analyzer<D,T>(simulator, system),
49 kMeshDimensions_(),
50 nWave_(0),
51 nBunch_(0),
52 writeWaveData_(false),
53 isInitialized_(false)
54 {
55 ParamComposite::setClassName("BinaryStructureFactor");
57 }
58
59 /*
60 * Read parameters from file, and allocate memory.
61 */
62 template <int D, class T>
64 {
65 // Precondition: Require that the system has two monomer types
66 UTIL_CHECK(system().mixture().nMonomer() == 2);
67
70 writeWaveData_ = false;
71 ParamComposite::readOptional(in, "writeWaveData", writeWaveData_);
72 isInitialized_ = true;
73 }
74
75 /*
76 * Setup before entering main loop.
77 */
78 template <int D, class T>
80 {
81 allocate();
82 setupWaveBunches();
83 }
84
85 /*
86 * Compute structure factors for all wavevectors and bunches.
87 */
88 template <int D, class T>
90 {
91 if (Analyzer<D,T>::isAtInterval(iStep)) {
92 computeW();
93 computeS();
94 }
95 }
96
97 // Private member functions
98
99 /*
100 * Allocate memory arrays with dimensions that depend only on mesh.
101 */
102 template <int D, class T>
103 void BinaryStructureFactor<D,T>::allocate()
104 {
105 UTIL_CHECK(isInitialized_);
106
107 // Compute and compute mesh dimensions
108 Mesh<D> const & mesh = system().domain().mesh();
109 IntVec<D> const & rMeshDimensions = mesh.dimensions();
110 FFT<D,T>::computeKMesh(rMeshDimensions, kMeshDimensions_, nWave_);
111
112 // If needed, allocate arrays indexed by wave id
113 if (!wm_.isAllocated()){
114 UTIL_CHECK(!wk_d_.isAllocated());
115 UTIL_CHECK(!waveBunchIds_.isAllocated());
116 UTIL_CHECK(!waveWeights_.isAllocated());
117 wm_.allocate(rMeshDimensions);
118 wk_d_.allocate(rMeshDimensions);
119 waveBunchIds_.allocate(nWave_);
120 waveWeights_.allocate(nWave_);
121 if (writeWaveData_) {
122 UTIL_CHECK(!waveAccumulators_.isAllocated());
123 waveAccumulators_.allocate(nWave_);
124 }
125 }
126 UTIL_CHECK(wm_.capacity() == mesh.size());
127 UTIL_CHECK(wk_d_.capacity() == nWave_);
128 UTIL_CHECK(waveBunchIds_.capacity() == nWave_);
129 UTIL_CHECK(waveWeights_.capacity() == nWave_);
130 if (writeWaveData_) {
131 UTIL_CHECK(waveAccumulators_.capacity() == nWave_);
132 }
133 }
134
135 /*
136 * Allocate and initialize data structures that involve wave bunches.
137 */
138 template <int D, class T>
139 void BinaryStructureFactor<D,T>::setupWaveBunches()
140 {
141 WaveList<D,T>& waveList = system().waveList();
142 UTIL_CHECK(waveList.isRealField());
143
144 // If necessary, compute KSq
145 if (!waveList.hasKSq()) {
146 waveList.computeKSq();
147 }
148 UTIL_CHECK(waveList.kSize() == nWave_);
149
150 // Create local references to kSq and implicit arrays
151 HostRecvArray<double,T> kSq(waveList.kSq());
152 DArray<bool> const & implicit = waveList.implicitInverse();
153 UTIL_CHECK(kSq.capacity() == nWave_);
154 UTIL_CHECK(implicit.capacity() == nWave_);
155
156 // Sort waves in WaveList and set nBunch_
157 waveList.sortWaves();
158 nBunch_ = waveList.nBunch();
159 UTIL_CHECK(nBunch_ > 0);
160
161 // If needed, allocate or re-allocate arrays indexed by bunch id
162 if (bunchAccumulators_.isAllocated()) {
163 int const m = bunchAccumulators_.capacity();
164 UTIL_CHECK(bunchWavenumbers_.capacity() == m);
165 UTIL_CHECK(bunchValues_.capacity() == m);
166 if (m < nBunch_) {
167 bunchAccumulators_.deallocate();
168 bunchWavenumbers_.deallocate();
169 bunchValues_.deallocate();
170 }
171 }
172 if (!bunchAccumulators_.isAllocated()) {
173 UTIL_CHECK(!bunchWavenumbers_.isAllocated());
174 UTIL_CHECK(!bunchValues_.isAllocated());
175 bunchAccumulators_.allocate(nBunch_);
176 bunchWavenumbers_.allocate(nBunch_);
177 bunchValues_.allocate(nBunch_);
178 }
179 int m = bunchAccumulators_.capacity();
180 UTIL_CHECK(m >= nBunch_);
181 UTIL_CHECK(bunchWavenumbers_.capacity() == m);
182 UTIL_CHECK(bunchValues_.capacity() == m);
183
184 // Initialize all arrays
185 for (int ib = 0; ib < m; ++ib) {
186 bunchAccumulators_[ib].clear();
187 bunchWavenumbers_[ib] = 0.0;
188 bunchValues_[ib] = 0.0;
189 }
190 for (int iw = 0; iw < nWave_; ++iw) {
191 waveBunchIds_[iw] = -1;
192 waveWeights_[iw] = 0.0;
193 }
194 if (writeWaveData_) {
195 for (int iw = 0; iw < nWave_; ++iw) {
196 waveAccumulators_[iw].clear();
197 }
198 }
199
200 // Define references to WaveList data structures
201 Array< int > const & sortedIds = waveList.sortedIds();
202 UTIL_CHECK(sortedIds.capacity() == nWave_);
203 GArray< Pair<int> > const & bunches = waveList.sortedBunches();
204 UTIL_CHECK(bunches.size() == nBunch_);
205
206 // Set bunchWavenumbers_, waveBunchIds_, and waveWeights_
207 double wavenumberSq, wavenumber, oldWavenumberSq;
208 double count, sum, tot;
209 int begin, end, k, iw;
210 int nw = 0;
211 for (int ib = 0; ib < nBunch_; ++ib) {
212 begin = bunches[ib][0];
213 end = bunches[ib][1];
214
215 // Compute wavenumberSq from first wave in bunch
216 iw = sortedIds[begin]; // wave id of first wave in bunch
217 wavenumberSq = kSq[iw];
218 UTIL_CHECK(wavenumberSq >= 0.0);
219 if (ib > 0) {
220 UTIL_CHECK(wavenumberSq - oldWavenumberSq > 5.0E-9);
221 }
222 oldWavenumberSq = wavenumberSq;
223
224 // Compute bunchWavenumbers_[ib]
225 wavenumber = std::sqrt(wavenumberSq);
226 bunchWavenumbers_[ib] = wavenumber;
227
228 // Set bunchIds, unnormalized weights for all waves in this bunch
229 sum = 0.0;
230 for (k = begin; k < end; ++k) {
231 iw = sortedIds[k];
232 // Check that each wave is only processed once
233 UTIL_CHECK(waveBunchIds_[iw] == -1);
234 UTIL_CHECK(std::abs(waveWeights_[iw]) < 1.0E-8);
235 waveBunchIds_[iw] = ib;
236 if (implicit[iw]) {
237 count = 2.0;
238 } else {
239 count = 1.0;
240 }
241 // count = 1.0; // Uncomment to weight waves equally
242 waveWeights_[iw] = count;
243 sum += count;
244 UTIL_CHECK(std::abs(kSq[iw] - wavenumberSq) < 2.0E-8);
245 }
246
247 // Normalize weights for all waves in this bunch
248 tot = 0.0;
249 for (k = begin; k < end; ++k) {
250 iw = sortedIds[k];
251 waveWeights_[iw] /= sum;
252 tot += waveWeights_[iw];
253 ++nw;
254 }
255 UTIL_CHECK(std::abs(tot - 1.0) < 1.0E-8);
256
257 }
258 UTIL_CHECK(nw == nWave_);
259
260 }
261
262 /*
263 * Compute W_{-} and it Fourier transform.
264 */
265 template <int D, class T>
266 void BinaryStructureFactor<D,T>::computeW()
267 {
268 // Preconditions
269 UTIL_CHECK(isInitialized_);
270 UTIL_CHECK(nWave_ > 0);
271 UTIL_CHECK(wk_d_.capacity() == nWave_);
272
273 // Compute W_{-}(r)
274 RField<D,T> const & wa = system().w().rgrid(0);
275 RField<D,T> const & wb = system().w().rgrid(1);
276 VecOp::subVV(wm_, wa, wb);
277 VecOp::mulEqS(wm_, 0.5);
278
279 // Fourier transform W_{-}(r)
280 system().domain().fft().forwardTransform(wm_, wk_d_);
281 }
282
283 /*
284 * Compute structure factors for all wavevectors and bunches.
285 */
286 template <int D, class T>
287 void BinaryStructureFactor<D,T>::computeS()
288 {
289 // Preconditions
290 UTIL_CHECK(isInitialized_);
291 UTIL_CHECK(nBunch_ > 0);
292 UTIL_CHECK(nWave_ >= nBunch_);
293 int m = bunchAccumulators_.capacity();
294 UTIL_CHECK(m >= nBunch_);
295 UTIL_CHECK(bunchWavenumbers_.capacity() >= m);
296 UTIL_CHECK(bunchValues_.capacity() >= m);
297 UTIL_CHECK(waveBunchIds_.capacity() == nWave_);
298 UTIL_CHECK(waveWeights_.capacity() == nWave_);
299
300 // Initialize bunch average values to zero
301 for (int ib = 0; ib < nBunch_; ++ib) {
302 bunchValues_[ib] = 0.0;
303 }
304
305 // Set coefficients a_ and b_
306 double const vSystem = system().domain().unitCell().volume();
307 double const vMonomer = system().mixture().vMonomer();
308 double const chi = -simulator().chiEval(0);
309 double a_ = vSystem / (chi * chi * vMonomer * vMonomer);
310 double b_ = 0.5 / (chi * vMonomer);
311
312 // Create const host copy wk_h_ of backend array wk_d_
313 wk_h_ = wk_d_;
314 UTIL_CHECK(wk_h_.capacity() == nWave_);
315
316 // Compute structure factors for all waves, add to bunchValues_
317 double value;
318 int ib;
319 for (int iw = 0; iw < nWave_; ++iw) {
320 value = a_ * absSq( wk_h_[iw] );
321 value -= b_;
322 if (writeWaveData_) {
323 waveAccumulators_[iw].sample(value);
324 }
325 ib = waveBunchIds_[iw];
326 bunchValues_[ib] += waveWeights_[iw] * value;
327 }
328
329 // Release host array
330 wk_h_.dissociate();
331
332 // Pass bunchValues_ to bunchAccumulators_
333 for (ib = 0; ib < nBunch_; ++ib) {
334 bunchAccumulators_[ib].sample(bunchValues_[ib]);
335 }
336
337 }
338
339 /*
340 * Output final results to output file.
341 */
342 template <int D, class T>
344 {
345 std::string filename;
346 std::ofstream file;
347
348 // Output spherical average values of S(q) for wavector bunches
350 if (writeWaveData_) {
351 filename += "_ave";
352 }
354 for (int i = 0; i < nBunch_; ++i) {
355 file << Dbl(bunchWavenumbers_[i], 18, 8);
356 file << Dbl(bunchAccumulators_[i].average(), 18, 8);
357 file << std::endl;
358 }
359 file.close();
360
361 // Optionally output S(q) values for individual waves
362 if (writeWaveData_) {
364 filename += "_wave";
366 MeshIterator<D> iter(kMeshDimensions_);
367 IntVec<D> p;
368 int iw, j;
369 for (iter.begin(); !iter.atEnd(); ++iter) {
370 iw = iter.rank();
371 p = iter.position();
372 for (j = 0; j < D; ++j) {
373 file << Int(p[j], 5);
374 }
375 file << Dbl(waveAccumulators_[iw].average(), 18, 8);
376 file << std::endl;
377 }
378 file.close();
379 }
380
381 }
382
383}
384}
385#endif
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<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 size() const
Get total number of grid points.
Definition Mesh.h:229
Analyzer(Simulator< D, T > &simulator, System< D, T > &system)
Constructor.
Definition Analyzer.tpp:31
void readInterval(std::istream &in)
Optionally read interval from file, with error checking.
Definition Analyzer.tpp:55
bool isAtInterval(long counter) const
Return true iff counter is a multiple of the interval.
Definition Analyzer.h:219
void setFileMaster(FileMaster &fileMaster)
Set the FileMaster to use to open files.
Definition Analyzer.tpp:92
Simulator< D, T > & simulator()
Get the parent Simulator by reference.
Definition Analyzer.h:233
std::string const & outputFileName() const
Get the outputFileName string.
Definition Analyzer.h:226
FileMaster & fileMaster()
Get the FileMaster by reference.
Definition Analyzer.tpp:99
System< D, T > & system()
Get the parent System by reference.
Definition Analyzer.h:243
void readOutputFileName(std::istream &in)
Read outputFileName from file.
Definition Analyzer.tpp:82
void readParameters(std::istream &in) override
Read parameters from file.
void output() override
Output results to predefined output file.
BinaryStructureFactor(Simulator< D, T > &simulator, System< D, T > &system)
Constructor.
void setup() override
Setup before the main loop.
void sample(long iStep) override
Compute structure factors and add to accumulators.
Base class for field theoretic PS-FTS simulator.
Definition Simulator.h:93
Base class template for classes that represent a complete system.
FileMaster const & fileMaster() const
Get the FileMaster (const).
int capacity() const
Return allocated size.
Definition Array.h:250
Dynamically allocatable contiguous array template.
Definition DArray.h:32
Dbl()
Default constructor.
Definition Dbl.cpp:17
void openOutputFile(const std::string &filename, std::ofstream &out, std::ios_base::openmode mode=std::ios_base::out) const
Open an output file.
An automatically growable array, analogous to a std::vector.
Definition GArray.h:34
int size() const
Return the logical size of this array (number of elements).
Definition GArray.h:450
Int()
Default constructor.
Definition Int.cpp:19
void setClassName(const char *className)
Set class name string.
ScalarParam< Type > & readOptional(std::istream &in, const char *label, Type &value)
Add and read a new optional ScalarParam < Type > object.
File containing preprocessor macros for error handling.
#define UTIL_CHECK(condition)
Assertion macro suitable for serial or parallel production code.
Definition global.h:68
double absSq(fftw_complex const &a)
Return square of absolute magnitude of an fftw_complex number.
Definition cpp/complex.h:73
double sum(Array< double > const &in)
Compute sum of array elements (real).
Definition Reduce.cpp:19
void mulEqS(Array< double > &a, double b)
Vector-scalar in-place multiplication, a[i] *= b (real).
Definition VecOp.cpp:270
void subVV(Array< double > &a, Array< double > const &b, Array< double > const &c)
Vector-vector subtraction, a[i] = b[i] - c[i] (real).
Definition VecOp.cpp:100
Code for programs that simulate real-valued periodic fields.
Definition param_pc.dox:2
PSCF package top-level namespace.