-
Notifications
You must be signed in to change notification settings - Fork 53
/
Method_MC.cpp
346 lines (292 loc) · 13.6 KB
/
Method_MC.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#include <Spirit_Defines.h>
#include <data/Spin_System.hpp>
#include <data/Spin_System_Chain.hpp>
#include <engine/Method_MC.hpp>
#include <engine/Vectormath.hpp>
#include <io/IO.hpp>
#include <utility/Constants.hpp>
#include <utility/Logging.hpp>
#include <Eigen/Dense>
#include <cmath>
#include <ctime>
#include <iostream>
using namespace Utility;
namespace Engine
{
Method_MC::Method_MC( std::shared_ptr<Data::Spin_System> system, int idx_img, int idx_chain )
: Method( system->mc_parameters, idx_img, idx_chain )
{
// Currently we only support a single image being iterated at once:
this->systems = std::vector<std::shared_ptr<Data::Spin_System>>( 1, system );
this->SenderName = Log_Sender::MC;
this->noi = this->systems.size();
this->nos = this->systems[0]->geometry->nos;
this->nos_nonvacant = this->systems[0]->geometry->nos_nonvacant;
this->xi = vectorfield( this->nos, { 0, 0, 0 } );
// We assume it is not converged before the first iteration
// this->max_torque = system->mc_parameters->force_convergence + 1.0;
// History
// this->history = std::map<std::string, std::vector<scalar>>{ { "max_torque", { this->max_torque } },
// { "E", { this->max_torque } },
// { "M_z", { this->max_torque } } };
this->spins_new = vectorfield(this->nos);
this->parameters_mc = system->mc_parameters;
// Starting cone angle
this->cone_angle = Constants::Pi * this->parameters_mc->metropolis_cone_angle / 180.0;
this->n_rejected = 0;
this->acceptance_ratio_current = this->parameters_mc->acceptance_ratio_target;
}
// This implementation is mostly serial as parallelization is nontrivial
// if the range of neighbours for each atom is not pre-defined.
void Method_MC::Iteration()
{
// Temporaries
auto & spins_old = *this->systems[0]->spins;
Vectormath::set_c_a(1, spins_old, this->spins_new);
// Generate randomly displaced spin configuration according to cone radius
// Vectormath::get_random_vectorfield_unitsphere(this->parameters_mc->prng, random_unit_vectors);
// TODO: add switch between Metropolis and heat bath
// One Metropolis step
Metropolis( spins_old, this->spins_new );
Vectormath::set_c_a( 1, this->spins_new, spins_old );
}
void Method_MC::Displace_Spin(int ispin, vectorfield & spins_new, const vectorfield & spins_old, std::uniform_real_distribution<scalar> & distribution)
{
// One Metropolis step for each spin
const Vector3 e_z{ 0, 0, 1 };
scalar costheta, sintheta, phi;
Matrix3 local_basis;
scalar cos_cone_angle = std::cos( cone_angle );
// Sample a cone
if( this->parameters_mc->metropolis_step_cone )
{
// Calculate local basis for the spin
if( spins_old[ispin].z() < 1 - 1e-10 )
{
local_basis.col( 2 ) = spins_old[ispin];
local_basis.col( 0 ) = ( local_basis.col( 2 ).cross( e_z ) ).normalized();
local_basis.col( 1 ) = local_basis.col( 2 ).cross( local_basis.col( 0 ) );
}
else
{
local_basis = Matrix3::Identity();
}
// Rotation angle between 0 and cone_angle degrees
costheta = 1 - ( 1 - cos_cone_angle ) * distribution( this->parameters_mc->prng );
sintheta = std::sqrt( 1 - costheta * costheta );
// Random distribution of phi between 0 and 360 degrees
phi = 2 * Constants::Pi * distribution( this->parameters_mc->prng );
// New spin orientation in local basis
Vector3 local_spin_new{ sintheta * std::cos( phi ), sintheta * std::sin( phi ), costheta };
// New spin orientation in regular basis
spins_new[ispin] = local_basis * local_spin_new;
}
// Sample the entire unit sphere
else
{
// Rotation angle between 0 and 180 degrees
costheta = distribution( this->parameters_mc->prng );
sintheta = std::sqrt( 1 - costheta * costheta );
// Random distribution of phi between 0 and 360 degrees
phi = 2 * Constants::Pi * distribution( this->parameters_mc->prng );
// New spin orientation in local basis
spins_new[ispin] = Vector3{ sintheta * std::cos( phi ), sintheta * std::sin( phi ), costheta };
}
};
// Simple metropolis step
void Method_MC::Metropolis( const vectorfield & spins_old, vectorfield & spins_new )
{
auto distribution = std::uniform_real_distribution<scalar>( 0, 1 );
auto distribution_idx = std::uniform_int_distribution<>( 0, this->nos - 1 );
scalar kB_T = Constants::k_B * this->parameters_mc->temperature;
scalar diff = 0.01;
// Cone angle feedback algorithm
if( this->parameters_mc->metropolis_step_cone && this->parameters_mc->metropolis_cone_adaptive )
{
this->acceptance_ratio_current = 1 - (scalar)this->n_rejected / (scalar)this->nos_nonvacant;
if( ( this->acceptance_ratio_current < this->parameters_mc->acceptance_ratio_target )
&& ( this->cone_angle > diff ) )
this->cone_angle -= diff;
if( ( this->acceptance_ratio_current > this->parameters_mc->acceptance_ratio_target )
&& ( this->cone_angle < Constants::Pi - diff ) )
this->cone_angle += diff;
this->parameters_mc->metropolis_cone_angle = this->cone_angle * 180.0 / Constants::Pi;
}
this->n_rejected = 0;
// Loop over NOS samples (on average every spin should be hit once per Metropolis step)
for( int idx = 0; idx < this->nos; ++idx )
{
int ispin;
if( this->parameters_mc->metropolis_random_sample )
// Better statistics, but additional calculation of random number
ispin = distribution_idx( this->parameters_mc->prng );
else
// Faster, but worse statistics
ispin = idx;
if( Vectormath::check_atom_type( this->systems[0]->geometry->atom_types[ispin] ) )
{
Displace_Spin( ispin, spins_new, spins_old, distribution );
// Energy difference of configurations with and without displacement
scalar Eold = this->systems[0]->hamiltonian->Energy_Single_Spin( ispin, spins_old );
scalar Enew = this->systems[0]->hamiltonian->Energy_Single_Spin( ispin, spins_new );
scalar Ediff = Enew - Eold;
// Metropolis criterion: reject the step if energy rose
if( Ediff > 1e-14 )
{
if( this->parameters_mc->temperature < 1e-12 )
{
// Restore the spin
spins_new[ispin] = spins_old[ispin];
// Counter for the number of rejections
++this->n_rejected;
}
else
{
// Exponential factor
scalar exp_ediff = std::exp( -Ediff / kB_T );
// Metropolis random number
scalar x_metropolis = distribution( this->parameters_mc->prng );
// Only reject if random number is larger than exponential
if( exp_ediff < x_metropolis )
{
// Restore the spin
spins_new[ispin] = spins_old[ispin];
// Counter for the number of rejections
++this->n_rejected;
}
}
}
}
}
}
// TODO:
// Implement heat bath algorithm, see Y. Miyatake et al, J Phys C: Solid State Phys 19, 2539 (1986)
// void Method_MC::HeatBath(const vectorfield & spins_old, vectorfield & spins_new)
// {
// }
void Method_MC::Hook_Pre_Iteration() {}
void Method_MC::Hook_Post_Iteration() {}
void Method_MC::Initialize() {}
void Method_MC::Finalize()
{
this->systems[0]->iteration_allowed = false;
}
void Method_MC::Message_Start()
{
//---- Log messages
std::vector<std::string> block( 0 );
block.emplace_back( fmt::format( "------------ Started {} Calculation ------------", this->Name() ) );
block.emplace_back( fmt::format( " Going to iterate {} step(s)", this->n_log ) );
block.emplace_back( fmt::format( " with {} iterations per step", this->n_iterations_log ) );
if( this->parameters_mc->metropolis_step_cone )
{
if( this->parameters_mc->metropolis_cone_adaptive )
{
block.emplace_back(
fmt::format( " Target acceptance {:>6.3f}", this->parameters_mc->acceptance_ratio_target ) );
block.emplace_back(
fmt::format( " Cone angle (deg): {:>6.3f} (adaptive)", this->cone_angle * 180 / Constants::Pi ) );
}
else
{
block.emplace_back(
fmt::format( " Target acceptance {:>6.3f}", this->parameters_mc->acceptance_ratio_target ) );
block.emplace_back(
fmt::format( " Cone angle (deg): {:>6.3f} (non-adaptive)", this->cone_angle * 180 / Constants::Pi ) );
}
}
block.emplace_back( "-----------------------------------------------------" );
Log.SendBlock( Log_Level::All, this->SenderName, block, this->idx_image, this->idx_chain );
}
void Method_MC::Message_Step()
{
// Update time of current step
auto t_current = std::chrono::system_clock::now();
// Update the system's energy
this->systems[0]->UpdateEnergy();
// Send log message
std::vector<std::string> block( 0 );
block.emplace_back(
fmt::format( "----- {} Calculation: {}", this->Name(), Timing::DateTimePassed( t_current - this->t_start ) ) );
block.emplace_back( fmt::format(
" Completed {} / {} step(s) (step size {})", this->step, this->n_log,
this->n_iterations_log ) );
block.emplace_back( fmt::format( " Iteration {} / {}", this->iteration, this->n_iterations ) );
block.emplace_back(
fmt::format( " Time since last step: {}", Timing::DateTimePassed( t_current - this->t_last ) ) );
block.emplace_back( fmt::format(
" Iterations / sec: {}",
this->n_iterations_log / Timing::SecondsPassed( t_current - this->t_last ) ) );
if( this->parameters_mc->metropolis_step_cone )
{
if( this->parameters_mc->metropolis_cone_adaptive )
{
block.emplace_back( fmt::format(
" Current acceptance ratio: {:>6.3f} (target {})", this->acceptance_ratio_current,
this->parameters_mc->acceptance_ratio_target ) );
block.emplace_back( fmt::format(
" Current cone angle (deg): {:>6.3f} (adaptive)", this->cone_angle * 180 / Constants::Pi ) );
}
else
{
block.emplace_back(
fmt::format( " Current acceptance ratio: {:>6.3f}", this->acceptance_ratio_current ) );
block.emplace_back( fmt::format(
" Current cone angle (deg): {:>6.3f} (non-adaptive)", this->cone_angle * 180 / Constants::Pi ) );
}
}
block.emplace_back( fmt::format( " Total energy: {:20.10f}", this->systems[0]->E ) );
Log.SendBlock( Log_Level::All, this->SenderName, block, this->idx_image, this->idx_chain );
// Update time of last step
this->t_last = t_current;
}
void Method_MC::Message_End()
{
//---- End timings
auto t_end = std::chrono::system_clock::now();
//---- Termination reason
std::string reason = "";
if( this->StopFile_Present() )
reason = "A STOP file has been found";
else if( this->Walltime_Expired( t_end - this->t_start ) )
reason = "The maximum walltime has been reached";
// Update the system's energy
this->systems[0]->UpdateEnergy();
//---- Log messages
std::vector<std::string> block;
block.emplace_back( fmt::format( "------------ Terminated {} Calculation ------------", this->Name() ) );
if( reason.length() > 0 )
block.emplace_back( fmt::format( "----- Reason: {}", reason ) );
block.emplace_back( fmt::format( "----- Duration: {}", Timing::DateTimePassed( t_end - this->t_start ) ) );
block.emplace_back( fmt::format( " Completed {} / {} step(s)", this->step, this->n_log ) );
block.emplace_back( fmt::format( " Iteration {} / {}", this->iteration, this->n_iterations ) );
block.emplace_back(
fmt::format( " Iterations / sec: {}", this->iteration / Timing::SecondsPassed( t_end - this->t_start ) ) );
if( this->parameters_mc->metropolis_step_cone )
{
if( this->parameters_mc->metropolis_cone_adaptive )
{
block.emplace_back( fmt::format(
" Acceptance ratio: {:>6.3f} (target {})", this->acceptance_ratio_current,
this->parameters_mc->acceptance_ratio_target ) );
block.emplace_back(
fmt::format( " Cone angle (deg): {:>6.3f} (adaptive)", this->cone_angle * 180 / Constants::Pi ) );
}
else
{
block.emplace_back( fmt::format( " Acceptance ratio: {:>6.3f}", this->acceptance_ratio_current ) );
block.emplace_back( fmt::format(
" Cone angle (deg): {:>6.3f} (non-adaptive)", this->cone_angle * 180 / Constants::Pi ) );
}
}
block.emplace_back( fmt::format( " Total energy: {:20.10f}", this->systems[0]->E ) );
block.emplace_back( "-----------------------------------------------------" );
Log.SendBlock( Log_Level::All, this->SenderName, block, this->idx_image, this->idx_chain );
}
void Method_MC::Save_Current( std::string starttime, int iteration, bool initial, bool final ) {}
// Method name as string
std::string Method_MC::Name()
{
return "MC";
}
} // namespace Engine