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 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
|
F@*
AdaptiveStep.tmpl
Created by Graham Dennis on 2007-11-16.
Copyright (c) 2007-2012, Graham Dennis
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*@
@extends xpdeint.Segments.Integrators.Integrator
@def description: segment $segmentNumber ($stepper.name adaptive-step integrator)
@attr $supportsConstantIPOperators = False
@*
Function prototypes
*@
@def functionPrototypes
@#
@super
@#
real _segment${segmentNumber}_setup_sampling(bool* _next_sample_flag, long* _next_sample_counter);
@#
@for $vector in $integrationVectors
real _segment${segmentNumber}_${vector.id}_timestep_error(${vector.type}* _checkfield);
bool _segment${segmentNumber}_${vector.id}_reset(${vector.type}* _reset_to);
@end for
@#
@end def
@*
Function implementations
*@
@def functionImplementations
@#
@super
@#
${setupSamplingFunctionImplementation}@slurp
@for $vector in $integrationVectors
${timestepErrorFunctionImplementation($vector)}@slurp
${resetFunctionImplementation($vector)}@slurp
@end for
@#
@end def
@def setupSamplingFunctionImplementation
@#
real _segment${segmentNumber}_setup_sampling(bool* _next_sample_flag, long* _next_sample_counter)
{
// The numbers of the moment groups that need to be sampled at the next sampling point.
// An entry of N+1 means "reached end of integration interval"
long _momentGroupNumbersNeedingSamplingNext[${len($samples) + 1}];
long _numberOfMomentGroupsToBeSampledNext = 1;
long _previous_m = 1;
long _previous_M = 1;
real _${propagationDimension}_break_next = (real)${interval};
_momentGroupNumbersNeedingSamplingNext[0] = ${len($samples)};
// initialise all flags to false
for (long _i0 = 0; _i0 < ${len($samples) + 1}; _i0++)
_next_sample_flag[_i0] = false;
/* Check if moment group needs sampling at the same time as another already discovered sample (or the final time).
* If so, add this moment group to the to-be-sampled list. If moment group demands sampling earlier than all
* previously noted moment groups, erase all previous ones from list and set the sample time to this earlier one.
*/
@for $momentGroupNumber, $sampleCount in enumerate($samples)
@if $sampleCount == 0
@continue
@end if
if (_next_sample_counter[$momentGroupNumber] * _previous_M == _previous_m * $sampleCount) {
_momentGroupNumbersNeedingSamplingNext[_numberOfMomentGroupsToBeSampledNext] = $momentGroupNumber;
_numberOfMomentGroupsToBeSampledNext++;
} else if (_next_sample_counter[$momentGroupNumber] * _previous_M < _previous_m * $sampleCount) {
_${propagationDimension}_break_next = _next_sample_counter[$momentGroupNumber] * ((real)$interval) / ((real)$sampleCount);
_numberOfMomentGroupsToBeSampledNext = 1;
_momentGroupNumbersNeedingSamplingNext[0] = $momentGroupNumber;
_previous_M = $sampleCount;
_previous_m = _next_sample_counter[$momentGroupNumber];
}
@end for
// _momentGroupNumbersNeedingSamplingNext now contains the complete list of moment groups that need
// to be sampled at the next sampling point. Set their flags to true.
for (long _i0 = 0; _i0 < _numberOfMomentGroupsToBeSampledNext; _i0++)
_next_sample_flag[_momentGroupNumbersNeedingSamplingNext[_i0]] = true;
return _${propagationDimension}_break_next;
}
@#
@end def
@def timestepErrorFunctionImplementation($vector)
@#
real _segment${segmentNumber}_${vector.id}_timestep_error(${vector.type}* _checkfield)
{
real _error = 1e-24;
real _temp_error = 0.0;
real _temp_mod = 0.0;
@set $featureOrdering = ['Diagnostics']
@set $dict = {'vector': vector}
${insertCodeForFeatures('timestepErrorBegin', featureOrdering, {'vector': vector}), autoIndent=True}@slurp
@if len($vector.field.dimensions) > 0
@# FIXME: We need to have the capacity to have both a peak cutoff and an absolute cutoff
// Find the peak value for each component of the field
real _cutoff[_${vector.id}_ncomponents];
for (long _i0 = 0; _i0 < _${vector.id}_ncomponents; _i0++)
_cutoff[_i0] = 0.0;
{
${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideFindPeakLoops(vector)), autoIndent=True}@slurp
}
${insertCodeForFeatures('findMax', ['Driver'], {'variable': '_cutoff', 'count': c'_${vector.id}_ncomponents'}), autoIndent=True}@slurp
for (long _i0 = 0; _i0 < _${vector.id}_ncomponents; _i0++) {
if (_xmds_isnonfinite(_cutoff[_i0]))
// Return an error two times the tolerance in this case because the timestep must be reduced.
return 2.0*${tolerance};
_cutoff[_i0] *= ${cutoff};
@if $vector.type == 'complex'
@# multiply again because we are using norm for our complex vector and the cutoff should be interpreted in terms of
@# the absolute magnitude of the variables, not the mod-square
_cutoff[_i0] *= ${cutoff};
@end if
}
@end if
@# Code for absolute cutoff should go here and modify
@# the _cutoff variables
@#
@# @for $absoluteCutoff in $absoluteCutoffs
@# // absolute cutoff for component '$absoluteCutoff.name'
@# if (_cutoff[${absoluteCutoff.componentIndex}])
@# @end for
@#
{
${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideFindMaxErrorLoops(vector)), autoIndent=True}@slurp
}
${insertCodeForFeatures('findMax', ['Driver'], {'variable': '&_error', 'count': '1'}), autoIndent=True}@slurp
${insertCodeForFeaturesInReverseOrder('timestepErrorEnd', featureOrdering, dict), autoIndent=True}@slurp
return _error;
}
@#
@end def
@def insideFindPeakLoops($vector)
@#
for (long _i1 = 0; _i1 < _${vector.id}_ncomponents; _i1++) {
@if $vector.type == 'complex'
@set $modFunction = 'mod2'
@else
@set $modFunction = 'abs'
@end if
_temp_mod = ${modFunction}(_${vector.id}[_${vector.id}_index_pointer + _i1]);
if (_xmds_isnonfinite(_temp_mod))
_cutoff[_i1] = INFINITY;
else if (_cutoff[_i1] < _temp_mod)
_cutoff[_i1] = _temp_mod;
}
@#
@end def
@def insideFindMaxErrorLoops($vector)
@#
for (long _i1 = 0; _i1 < _${vector.id}_ncomponents; _i1++) {
@if $vector.type == 'complex'
@set $modCutoffFunction = 'mod2'
@else
@set $modCutoffFunction = 'abs'
@end if
@if len($vector.field.dimensions) > 0
if (${modCutoffFunction}(_${vector.id}[_${vector.id}_index_pointer + _i1]) > _cutoff[_i1]) {
${updateMaximumError($vector), autoIndent=True}@slurp
}
@else
${updateMaximumError($vector), autoIndent=True}@slurp
@end if
}
@#
@end def
@def insideLookForNaNLoops($vector)
@#
@# No point in fancy logic trying to exit the test early if a NaN is found, even
@# though this is hot path code, since a NaN means we're about to exit the simulation
@# anyway. Worth having seperate code depending on whether the vector values are
@# real or complex though, since complex requires either two checks or taking the
@# modulus. Presumably two seperate Re(), Im() checks are faster than mod2
@#
for (long _i1 = 0; _i1 < _${vector.id}_ncomponents; _i1++) {
@if $vector.type == 'complex'
if (_xmds_isnonfinite(_${vector.id}[_${vector.id}_index_pointer + _i1].Re())
|| _xmds_isnonfinite(_${vector.id}[_${vector.id}_index_pointer + _i1].Im())) bNoNaNsPresent = false;
@else
if (_xmds_isnonfinite(_${vector.id}[_${vector.id}_index_pointer + _i1])) bNoNaNsPresent = false;
@end if
}
@#
@end def
@def updateMaximumError($vector)
@#
_temp_error = abs(_${vector.id}[_${vector.id}_index_pointer + _i1] - _checkfield[_${vector.id}_index_pointer + _i1]) / (0.5*abs(_${vector.id}[_${vector.id}_index_pointer + _i1]) + 0.5*abs(_checkfield[_${vector.id}_index_pointer + _i1]));
if (_xmds_isnonfinite(_temp_error)) {
/* For _temp_error to be NaN, both the absolute value of the higher and lower order solutions
must BOTH be zero. This therefore implies that their difference is zero, and that there is no error. */
_temp_error = 0.0;
}
if (_error < _temp_error) // UNVECTORISABLE
_error = _temp_error;
@#
${insertCodeForFeatures('updateMaximumError', ['Diagnostics'], {'vector': vector})}@slurp
@#
@end def
@def resetFunctionImplementation($vector)
@#
bool _segment${segmentNumber}_${vector.id}_reset(${vector.type}* _reset_to_${vector.id})
{
${copyVectors([vector], destPrefix = '', srcPrefix = '_reset_to'), autoIndent=True}@slurp
/* return false if there's a NaN somewhere in the vector, otherwise return true */
bool bNoNaNsPresent = true;
{
${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideLookForNaNLoops(vector)), autoIndent=True}@slurp
}
return bNoNaNsPresent;
}
@#
@end def
@def createToleranceVariable
@*doc:
This function returns the code that will create a _step variable,
including any modifications necessary due to the ErrorCheck feature.
*@
@#
real _tolerance = ${tolerance};
@#
@set $featureOrdering = ['ErrorCheck']
${insertCodeForFeatures('createToleranceVariable', featureOrdering)}@slurp
@#
@end def
@def segmentFunctionBody($function)
@#
real _step = ${interval}/(real)${stepCount};
real _old_step = _step;
real _min_step = _step;
real _max_step = _step;
long _attempted_steps = 0;
long _unsuccessful_steps = 0;
${createToleranceVariable}@slurp
@# Insert code for features
@set $featureOrderingOuter = ['Stochastic']
${insertCodeForFeatures('integrateAdaptiveStepBegin', featureOrderingOuter)}@slurp
real _error, _last_norm_error = 1.0;
@for $vector in $integrationVectors
real _${name}_${vector.id}_error;
@end for
bool _discard = false;
bool _break_next = false;
@set $momentGroupCount = len($momentGroups)
bool _next_sample_flag[${momentGroupCount + 2}];
for (long _i0 = 0; _i0 < ${momentGroupCount + 2}; _i0++)
_next_sample_flag[_i0] = false;
long _next_sample_counter[$momentGroupCount];
for (long _i0 = 0; _i0 < $momentGroupCount; _i0++)
_next_sample_counter[_i0] = 1;
real _${propagationDimension}_local = 0.0;
real _${propagationDimension}_break_next = _${name}_setup_sampling(_next_sample_flag, _next_sample_counter);
if ( (_${propagationDimension}_local + _step)*(1.0 + _EPSILON) >= _${propagationDimension}_break_next) {
_break_next = true;
_step = _${propagationDimension}_break_next - _${propagationDimension}_local;
}
${allocate}@slurp
${initialise}@slurp
${localInitialise}@slurp
do {
@set $featureOrderingOuterLoop = ['MaxIterations', 'Output', 'ErrorCheck']
${insertCodeForFeatures('integrateAdaptiveStepOuterLoopBegin', featureOrderingOuterLoop), autoIndent=True}@slurp
${preSingleStep, autoIndent=True}@slurp
do {
@# Insert code for features
@set $featureOrderingInnerLoop = ['Stochastic']
${insertCodeForFeatures('integrateAdaptiveStepInnerLoopBegin', featureOrderingInnerLoop), autoIndent=True}@slurp
${stepper.singleIntegrationStep(function), autoIndent=True}@slurp
${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepInnerLoopEnd', featureOrderingInnerLoop), autoIndent=True}@slurp
_error = 0.0;
@for $vector in $integrationVectors
_${name}_${vector.id}_error = _${name}_${vector.id}_timestep_error(_${stepper.errorFieldName}_${vector.id});
if (_${name}_${vector.id}_error > _error)
_error = _${name}_${vector.id}_error;
@end for
_attempted_steps++;
@set $featureOrderingForToleranceChecking = ['Diagnostics', 'Stochastic']
if (_error < _tolerance) {
${insertCodeForFeatures('adaptiveStepSucceeded', $featureOrderingForToleranceChecking), autoIndent=True}@slurp
_${propagationDimension}_local += _step;
if (_step > _max_step)
_max_step = _step;
if (!_break_next && _step < _min_step)
_min_step = _step;
_discard = false;
} else {
${insertCodeForFeatures('adaptiveStepFailed', $featureOrderingForToleranceChecking), autoIndent=True}@slurp
${propagationDimension} -= _step;
@for $vector in $integrationVectors
if (_${name}_${vector.id}_reset(_${stepper.resetFieldName}_${vector.id}) == false) {
_LOG(_WARNING_LOG_LEVEL, "WARNING: NaN present. Integration halted at ${propagationDimension} = %e.\n"
" Non-finite number in integration vector \"${vector.name}\" in segment ${segmentNumber}.\n", $propagationDimension);
${earlyTerminationCode, autoIndent=True}@slurp
}
@end for
${functions['ipEvolve'].call(_exponent = -1, parentFunction=function)}
_discard = true;
_break_next = false;
_unsuccessful_steps++;
}
_old_step = _step;
// Resize step
if (_error < 0.5*_tolerance || _error > _tolerance) {
const real _safetyFactor = 0.90;
real _scalingFactor = _safetyFactor * pow(abs(_error/_tolerance), real(-0.7/${integrationOrder})) * pow(_last_norm_error, real(0.4/${integrationOrder}));
_scalingFactor = MAX(_scalingFactor, 1.0/5.0);
_scalingFactor = MIN(_scalingFactor, 7.0);
if (_error > _tolerance && _scalingFactor > 1.0) {
// If our step failed don't try and increase our step size. That would be silly.
_scalingFactor = _safetyFactor * pow(abs(_error/_tolerance), real(-1.0/${integrationOrder}));
}
_old_step = _step;
_last_norm_error = pow(_safetyFactor/_scalingFactor*pow(_last_norm_error, real(0.4/${integrationOrder})), real(${integrationOrder}/0.7));
_step *= _scalingFactor;
}
} while (_discard);
${postSingleStep, autoIndent=True}@slurp
${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepOuterLoopEnd', featureOrderingOuterLoop), autoIndent=True}@slurp
} while (!_next_sample_flag[${momentGroupCount + 1}]);
${localFinalise}@slurp
${finalise}@slurp
${free}@slurp
@#
${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepEnd', featureOrderingOuter)}@slurp
_LOG(_SEGMENT_LOG_LEVEL, "Segment ${segmentNumber}: minimum timestep: %e maximum timestep: %e\n", _min_step, _max_step);
_LOG(_SEGMENT_LOG_LEVEL, " Attempted %li steps, %.2f%% steps failed.\n", _attempted_steps, (100.0*_unsuccessful_steps)/_attempted_steps);
@#
@end def
|