ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
Correlator.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2010-2022 The ESPResSo project
3 *
4 * This file is part of ESPResSo.
5 *
6 * ESPResSo is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * ESPResSo is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19#include "Correlator.hpp"
20
21#include <utils/Vector.hpp>
22#include <utils/math/sqr.hpp>
24
25#include <boost/archive/binary_iarchive.hpp>
26#include <boost/archive/binary_oarchive.hpp>
27#include <boost/iostreams/device/array.hpp>
28#include <boost/iostreams/stream.hpp>
29#include <boost/serialization/string.hpp>
30#include <boost/serialization/vector.hpp>
31
32#include <algorithm>
33#include <array>
34#include <cassert>
35#include <cmath>
36#include <cstddef>
37#include <functional>
38#include <numeric>
39#include <sstream>
40#include <stdexcept>
41#include <string>
42#include <vector>
43
44namespace {
45int min(int i, unsigned int j) { return std::min(i, static_cast<int>(j)); }
46} // namespace
47
48namespace Accumulators {
49/** Compress computing arithmetic mean: A_compressed=(A1+A2)/2 */
50std::vector<double> compress_linear(std::vector<double> const &A1,
51 std::vector<double> const &A2) {
52 assert(A1.size() == A2.size());
53 std::vector<double> A_compressed(A1.size());
54
55 std::ranges::transform(A1, A2, A_compressed.begin(),
56 [](double a, double b) { return 0.5 * (a + b); });
57
58 return A_compressed;
59}
60
61/** Compress discarding the 1st argument and return the 2nd */
62std::vector<double>
63compress_discard1([[maybe_unused]] std::vector<double> const &A1,
64 [[maybe_unused]] std::vector<double> const &A2) {
65 assert(A1.size() == A2.size());
66 std::vector<double> A_compressed(A2);
67 return A_compressed;
68}
69
70/** Compress discarding the 2nd argument and return the 1st */
71std::vector<double>
72compress_discard2([[maybe_unused]] std::vector<double> const &A1,
73 [[maybe_unused]] std::vector<double> const &A2) {
74 assert(A1.size() == A2.size());
75 std::vector<double> A_compressed(A1);
76 return A_compressed;
77}
78
79std::vector<double> scalar_product(std::vector<double> const &A,
80 std::vector<double> const &B,
81 Utils::Vector3d const &) {
82 if (A.size() != B.size()) {
83 throw std::runtime_error(
84 "Error in scalar product: The vector sizes do not match");
85 }
86
87 auto const result = std::inner_product(A.begin(), A.end(), B.begin(), 0.0);
88 return {result};
89}
90
91std::vector<double> componentwise_product(std::vector<double> const &A,
92 std::vector<double> const &B,
93 Utils::Vector3d const &) {
94 std::vector<double> C(A.size());
95 if (A.size() != B.size()) {
96 throw std::runtime_error(
97 "Error in componentwise product: The vector sizes do not match");
98 }
99
100 std::ranges::transform(A, B, C.begin(), std::multiplies<>());
101
102 return C;
103}
104
105std::vector<double> tensor_product(std::vector<double> const &A,
106 std::vector<double> const &B,
107 Utils::Vector3d const &) {
108 std::vector<double> C(A.size() * B.size());
109 auto C_it = C.begin();
110
111 for (double a : A) {
112 for (double b : B) {
113 *(C_it++) = a * b;
114 }
115 }
116
117 return C;
118}
119
120std::vector<double> square_distance_componentwise(std::vector<double> const &A,
121 std::vector<double> const &B,
122 Utils::Vector3d const &) {
123 if (A.size() != B.size()) {
124 throw std::runtime_error(
125 "Error in square distance componentwise: The vector sizes do not "
126 "match.");
127 }
128
129 std::vector<double> C(A.size());
130
131 std::ranges::transform(A, B, C.begin(), [](double a, double b) -> double {
132 return Utils::sqr(a - b);
133 });
134
135 return C;
136}
137
138// note: the argument name wsquare denotes that its value is w^2 while the user
139// sets w
140std::vector<double> fcs_acf(std::vector<double> const &A,
141 std::vector<double> const &B,
142 Utils::Vector3d const &wsquare) {
143 if (A.size() != B.size()) {
144 throw std::runtime_error(
145 "Error in fcs_acf: The vector sizes do not match.");
146 }
147
148 auto const C_size = A.size() / 3u;
149 assert(3u * C_size == A.size());
150
151 std::vector<double> C{};
152 C.reserve(C_size);
153
154 for (std::size_t i = 0u; i < C_size; i++) {
155 auto acc = 0.;
156 for (std::size_t j = 0u; j < 3u; j++) {
157 auto const a = A[3u * i + j];
158 auto const b = B[3u * i + j];
159 acc -= Utils::sqr(a - b) / wsquare[j];
160 }
161 C.emplace_back(std::exp(acc));
162 }
163
164 return C;
165}
166
167void Correlator::initialize_operations() {
168 // Class members are assigned via the initializer list
169
170 if (m_tau_lin == 1) { // use the default
171 m_tau_lin = static_cast<int>(std::ceil(m_tau_max / m_dt));
172 m_tau_lin += m_tau_lin % 2;
173 }
174
175 if (m_tau_lin < 2) {
176 throw std::runtime_error("tau_lin must be >= 2");
177 }
178
179 if (m_tau_lin % 2) {
180 throw std::runtime_error("tau_lin must be divisible by 2");
181 }
182
183 if (m_tau_max <= m_dt) {
184 throw std::runtime_error("tau_max must be >= delta_t (delta_N too large)");
185 }
186 // set hierarchy depth which can accommodate at least m_tau_max
187 if ((m_tau_max / m_dt) < m_tau_lin) {
188 m_hierarchy_depth = 1;
189 } else {
190 auto const operand = (m_tau_max / m_dt) / double(m_tau_lin - 1);
191 assert(operand > 0.);
192 m_hierarchy_depth = static_cast<int>(std::ceil(1. + std::log2(operand)));
193 }
194
195 assert(A_obs);
196 assert(B_obs);
197 dim_A = A_obs->n_values();
198 dim_B = B_obs->n_values();
199
200 if (dim_A == 0u) {
201 throw std::runtime_error("dimension of first observable has to be >= 1");
202 }
203 if (dim_B == 0u) {
204 throw std::runtime_error("dimension of second observable has to be >= 1");
205 }
206
207 // choose the correlation operation
208 if (corr_operation_name == "componentwise_product") {
209 m_dim_corr = dim_A;
210 m_shape = A_obs->shape();
211 corr_operation = &componentwise_product;
212 m_correlation_args = Utils::Vector3d{0, 0, 0};
213 } else if (corr_operation_name == "tensor_product") {
214 m_dim_corr = dim_A * dim_B;
215 m_shape.clear();
216 m_shape.emplace_back(dim_A);
217 m_shape.emplace_back(dim_B);
218 corr_operation = &tensor_product;
219 m_correlation_args = Utils::Vector3d{0, 0, 0};
220 } else if (corr_operation_name == "square_distance_componentwise") {
221 m_dim_corr = dim_A;
222 m_shape = A_obs->shape();
223 corr_operation = &square_distance_componentwise;
224 m_correlation_args = Utils::Vector3d{0, 0, 0};
225 } else if (corr_operation_name == "fcs_acf") {
226 // note: user provides w=(wx,wy,wz) but we want to use
227 // wsquare=(wx^2,wy^2,wz^2)
228 if (not(m_correlation_args_input > Utils::Vector3d::broadcast(0.))) {
229 throw std::runtime_error("missing parameter for fcs_acf: w_x w_y w_z");
230 }
231 m_correlation_args = Utils::hadamard_product(m_correlation_args_input,
232 m_correlation_args_input);
233 if (dim_A % 3u)
234 throw std::runtime_error("dimA must be divisible by 3 for fcs_acf");
235 m_dim_corr = dim_A / 3u;
236 m_shape = A_obs->shape();
237 if (m_shape.back() != 3u)
238 throw std::runtime_error(
239 "the last dimension of dimA must be 3 for fcs_acf");
240 m_shape.pop_back();
241 corr_operation = &fcs_acf;
242 } else if (corr_operation_name == "scalar_product") {
243 m_dim_corr = 1u;
244 m_shape.clear();
245 m_shape.emplace_back(1u);
246 corr_operation = &scalar_product;
247 m_correlation_args = Utils::Vector3d{0, 0, 0};
248 } else {
249 throw std::invalid_argument("correlation operation '" +
250 corr_operation_name + "' not implemented");
251 }
252
253 // Choose the compression function
254 if (compressA_name == "discard2") {
255 compressA = &compress_discard2;
256 } else if (compressA_name == "discard1") {
257 compressA = &compress_discard1;
258 } else if (compressA_name == "linear") {
259 compressA = &compress_linear;
260 } else {
261 throw std::invalid_argument("unknown compression method '" +
262 compressA_name + "' for first observable");
263 }
264
265 if (compressB_name == "discard2") {
266 compressB = &compress_discard2;
267 } else if (compressB_name == "discard1") {
268 compressB = &compress_discard1;
269 } else if (compressB_name == "linear") {
270 compressB = &compress_linear;
271 } else {
272 throw std::invalid_argument("unknown compression method '" +
273 compressB_name + "' for second observable");
274 }
275}
276
277void Correlator::initialize_buffers() {
278 using index_type = decltype(result)::index;
279
280 A.resize(std::array<int, 2>{{m_hierarchy_depth, m_tau_lin + 1}});
281 std::fill_n(A.data(), A.num_elements(), std::vector<double>(dim_A, 0));
282 B.resize(std::array<int, 2>{{m_hierarchy_depth, m_tau_lin + 1}});
283 std::fill_n(B.data(), B.num_elements(), std::vector<double>(dim_B, 0));
284
285 n_data = 0;
286 A_accumulated_average = std::vector<double>(dim_A, 0);
287 B_accumulated_average = std::vector<double>(dim_B, 0);
288
289 auto const n_result = n_values();
290 n_sweeps = std::vector<std::size_t>(n_result, 0);
291 n_vals = std::vector<long>(m_hierarchy_depth, 0);
292
293 result.resize(std::array<std::size_t, 2>{{n_result, m_dim_corr}});
294 for (index_type i = 0; i < static_cast<index_type>(n_result); i++) {
295 for (index_type j = 0; j < static_cast<index_type>(m_dim_corr); j++) {
296 result[i][j] = 0.;
297 }
298 }
299
300 newest = std::vector<long>(m_hierarchy_depth, m_tau_lin);
301
302 tau.resize(n_result);
303 for (int i = 0; i < m_tau_lin + 1; i++) {
304 tau[i] = i;
305 }
306
307 for (int j = 1; j < m_hierarchy_depth; j++) {
308 for (int k = 0; k < m_tau_lin / 2; k++) {
309 tau[m_tau_lin + 1 + (j - 1) * m_tau_lin / 2 + k] =
310 (k + (m_tau_lin / 2) + 1) * (1 << j);
311 }
312 }
313}
314
315void Correlator::update(boost::mpi::communicator const &comm) {
316 if (finalized) {
317 throw std::runtime_error(
318 "No data can be added after finalize() was called.");
319 }
320
321 if (comm.rank() != 0) {
322 // worker nodes just need to update the observables and exit
323 A_obs->operator()(comm);
324 if (A_obs != B_obs) {
325 B_obs->operator()(comm);
326 }
327
328 return;
329 }
330
331 // We must now go through the hierarchy and make sure there is space for the
332 // new datapoint. For every hierarchy level we have to decide if it is
333 // necessary to move something
334 int highest_level_to_compress = -1;
335
336 t++;
337
338 // Let's find out how far we have to go back in the hierarchy to make space
339 // for the new value
340 {
341 auto const max_depth = m_hierarchy_depth - 1;
342 int i = 0;
343 while (true) {
344 if (i >= max_depth or n_vals[i] <= m_tau_lin) {
345 break;
346 }
347 auto const modulo = 1 << (i + 1);
348 auto const remainder = (t - (m_tau_lin + 1) * (modulo - 1) - 1) % modulo;
349 if (remainder != 0) {
350 break;
351 }
352 highest_level_to_compress += 1;
353 i++;
354 }
355 }
356
357 // Now we know we must make space on the levels 0..highest_level_to_compress
358 // Now let's compress the data level by level.
359
360 for (int i = highest_level_to_compress; i >= 0; i--) {
361 // We increase the index indicating the newest on level i+1 by one (plus
362 // folding)
363 newest[i + 1] = (newest[i + 1] + 1) % (m_tau_lin + 1);
364 n_vals[i + 1] += 1;
365 A[i + 1][newest[i + 1]] =
366 (*compressA)(A[i][(newest[i] + 1) % (m_tau_lin + 1)],
367 A[i][(newest[i] + 2) % (m_tau_lin + 1)]);
368 B[i + 1][newest[i + 1]] =
369 (*compressB)(B[i][(newest[i] + 1) % (m_tau_lin + 1)],
370 B[i][(newest[i] + 2) % (m_tau_lin + 1)]);
371 }
372
373 newest[0] = (newest[0] + 1) % (m_tau_lin + 1);
374 n_vals[0]++;
375
376 A[0][newest[0]] = A_obs->operator()(comm);
377 if (A_obs != B_obs) {
378 B[0][newest[0]] = B_obs->operator()(comm);
379 } else {
380 B[0][newest[0]] = A[0][newest[0]];
381 }
382
383 // Now we update the cumulated averages and variances of A and B
384 n_data++;
385 for (std::size_t k = 0; k < dim_A; k++) {
386 A_accumulated_average[k] += A[0][newest[0]][k];
387 }
388
389 for (std::size_t k = 0; k < dim_B; k++) {
390 B_accumulated_average[k] += B[0][newest[0]][k];
391 }
392
393 using index_type = decltype(result)::index;
394 // Now update the lowest level correlation estimates
395 for (long j = 0; j < min(m_tau_lin + 1, n_vals[0]); j++) {
396 auto const index_new = newest[0];
397 auto const index_old = (newest[0] - j + m_tau_lin + 1) % (m_tau_lin + 1);
398 auto const temp =
399 (corr_operation)(A[0][index_old], B[0][index_new], m_correlation_args);
400 assert(temp.size() == m_dim_corr);
401
402 n_sweeps[j]++;
403 for (index_type k = 0; k < static_cast<index_type>(m_dim_corr); k++) {
404 result[j][k] += temp[k];
405 }
406 }
407 // Now for the higher ones
408 for (int i = 1; i < highest_level_to_compress + 2; i++) {
409 for (long j = (m_tau_lin + 1) / 2 + 1; j < min(m_tau_lin + 1, n_vals[i]);
410 j++) {
411 auto const index_new = newest[i];
412 auto const index_old = (newest[i] - j + m_tau_lin + 1) % (m_tau_lin + 1);
413 auto const index_res =
414 m_tau_lin + (i - 1) * m_tau_lin / 2 + (j - m_tau_lin / 2 + 1) - 1;
415 auto const temp = (corr_operation)(A[i][index_old], B[i][index_new],
416 m_correlation_args);
417 assert(temp.size() == m_dim_corr);
418
419 n_sweeps[index_res]++;
420 for (index_type k = 0; k < static_cast<index_type>(m_dim_corr); k++) {
421 result[index_res][k] += temp[k];
422 }
423 }
424 }
425}
426
427int Correlator::finalize(boost::mpi::communicator const &comm) {
428 using index_type = decltype(result)::index;
429 if (finalized) {
430 throw std::runtime_error("Correlator::finalize() can only be called once.");
431 }
432 // We must now go through the hierarchy and make sure there is space for the
433 // new datapoint. For every hierarchy level we have to decide if it is
434 // necessary to move something
435
436 // mark the correlation as finalized
437 finalized = true;
438
439 // worker nodes don't need to do anything
440 if (comm.rank() != 0) {
441 return 0;
442 }
443
444 for (int ll = 0; ll < m_hierarchy_depth - 1; ll++) {
445 long vals_ll; // number of values remaining in the lowest level
446 if (n_vals[ll] > m_tau_lin + 1)
447 vals_ll = m_tau_lin + n_vals[ll] % 2;
448 else
449 vals_ll = n_vals[ll];
450
451 while (vals_ll) {
452 // Check, if we will want to push the value from the lowest level
453 auto highest_level_to_compress = (vals_ll % 2) ? ll : -1;
454
455 // Let's find out how far we have to go back in the hierarchy to make
456 // space for the new value
457 {
458 auto const max_depth = m_hierarchy_depth - 1;
459 int i = ll + 1; // lowest level for which to check for compression
460 while (highest_level_to_compress > -1) {
461 if (i >= max_depth or n_vals[i] % 2 == 0 or n_vals[i] <= m_tau_lin) {
462 break;
463 }
464 highest_level_to_compress += 1;
465 i++;
466 }
467 }
468 vals_ll -= 1;
469
470 // Now we know we must make space on the levels
471 // 0..highest_level_to_compress
472 // Now let's compress the data level by level.
473
474 for (int i = highest_level_to_compress; i >= ll; i--) {
475 // We increase the index indicating the newest on level i+1 by one (plus
476 // folding)
477 newest[i + 1] = (newest[i + 1] + 1) % (m_tau_lin + 1);
478 n_vals[i + 1] += 1;
479
480 (*compressA)(A[i][(newest[i] + 1) % (m_tau_lin + 1)],
481 A[i][(newest[i] + 2) % (m_tau_lin + 1)]);
482 (*compressB)(B[i][(newest[i] + 1) % (m_tau_lin + 1)],
483 B[i][(newest[i] + 2) % (m_tau_lin + 1)]);
484 }
485 newest[ll] = (newest[ll] + 1) % (m_tau_lin + 1);
486
487 // We only need to update correlation estimates for the higher levels
488 for (int i = ll + 1; i < highest_level_to_compress + 2; i++) {
489 for (long j = (m_tau_lin + 1) / 2 + 1;
490 j < min(m_tau_lin + 1, n_vals[i]); j++) {
491 auto const index_new = newest[i];
492 auto const index_old =
493 (newest[i] - j + m_tau_lin + 1) % (m_tau_lin + 1);
494 auto const index_res =
495 m_tau_lin + (i - 1) * m_tau_lin / 2 + (j - m_tau_lin / 2 + 1) - 1;
496
497 auto const temp = (corr_operation)(A[i][index_old], B[i][index_new],
498 m_correlation_args);
499 assert(temp.size() == m_dim_corr);
500
501 n_sweeps[index_res]++;
502 for (index_type k = 0; k < static_cast<index_type>(m_dim_corr); k++) {
503 result[index_res][k] += temp[k];
504 }
505 }
506 }
507 }
508 }
509 return 0;
510}
511
512std::vector<double> Correlator::get_correlation() {
513 using index_type = decltype(result)::index;
514 auto const n_result = n_values();
515 std::vector<double> res(n_result * m_dim_corr);
516
517 for (std::size_t i = 0; i < n_result; i++) {
518 auto const index = static_cast<index_type>(m_dim_corr * i);
519 for (index_type k = 0; k < static_cast<index_type>(m_dim_corr); k++) {
520 if (n_sweeps[i]) {
521 res[index + k] = result[static_cast<index_type>(i)][k] /
522 static_cast<double>(n_sweeps[i]);
523 }
524 }
525 }
526 return res;
527}
528
529std::vector<double> Correlator::get_lag_times() const {
530 std::vector<double> res(n_values());
531 std::ranges::transform(tau, res.begin(),
532 [dt = m_dt](auto const &a) { return a * dt; });
533 return res;
534}
535
537 std::stringstream ss;
538 boost::archive::binary_oarchive oa(ss);
539
540 oa << t;
541 oa << m_dt;
542 oa << m_shape;
543 oa << m_correlation_args_input;
544 oa << A;
545 oa << B;
546 oa << result;
547 oa << n_sweeps;
548 oa << n_vals;
549 oa << newest;
550 oa << A_accumulated_average;
551 oa << B_accumulated_average;
552 oa << n_data;
553
554 return ss.str();
555}
556
557void Correlator::set_internal_state(std::string const &state) {
558 namespace iostreams = boost::iostreams;
559 iostreams::array_source src(state.data(), state.size());
560 iostreams::stream<iostreams::array_source> ss(src);
561 boost::archive::binary_iarchive ia(ss);
562
563 ia >> t;
564 ia >> m_dt;
565 ia >> m_shape;
566 ia >> m_correlation_args_input;
567 ia >> A;
568 ia >> B;
569 ia >> result;
570 ia >> n_sweeps;
571 ia >> n_vals;
572 ia >> newest;
573 ia >> A_accumulated_average;
574 ia >> B_accumulated_average;
575 ia >> n_data;
576 initialize_operations();
577 m_system = nullptr;
578}
579
580} // namespace Accumulators
Vector implementation and trait types for boost qvm interoperability.
void const * m_system
for bookkeeping purposes
std::string get_internal_state() const final
void set_internal_state(std::string const &) final
std::vector< double > get_lag_times() const
int finalize(boost::mpi::communicator const &comm)
At the end of data collection, go through the whole hierarchy and correlate data left there.
std::vector< double > get_correlation()
Return correlation result.
void update(boost::mpi::communicator const &comm) override
The function to process a new datapoint of A and B.
static DEVICE_QUALIFIER constexpr Vector< T, N > broadcast(typename Base::value_type const &value) noexcept
Create a vector that has all entries set to the same value.
Definition Vector.hpp:132
std::vector< double > componentwise_product(std::vector< double > const &A, std::vector< double > const &B, Utils::Vector3d const &)
std::vector< double > tensor_product(std::vector< double > const &A, std::vector< double > const &B, Utils::Vector3d const &)
std::vector< double > compress_linear(std::vector< double > const &A1, std::vector< double > const &A2)
Compress computing arithmetic mean: A_compressed=(A1+A2)/2.
std::vector< double > scalar_product(std::vector< double > const &A, std::vector< double > const &B, Utils::Vector3d const &)
std::vector< double > compress_discard1(std::vector< double > const &A1, std::vector< double > const &A2)
Compress discarding the 1st argument and return the 2nd.
std::vector< double > compress_discard2(std::vector< double > const &A1, std::vector< double > const &A2)
Compress discarding the 2nd argument and return the 1st.
std::vector< double > fcs_acf(std::vector< double > const &A, std::vector< double > const &B, Utils::Vector3d const &wsquare)
std::vector< double > square_distance_componentwise(std::vector< double > const &A, std::vector< double > const &B, Utils::Vector3d const &)
DEVICE_QUALIFIER constexpr T sqr(T x)
Calculates the SQuaRe of x.
Definition sqr.hpp:28
auto hadamard_product(Vector< T, N > const &a, Vector< U, N > const &b)
Definition Vector.hpp:378
int min(int i, unsigned int j)