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 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
|
/*
Project: Adun
Copyright (C) 2005 Michael Johnston & Jordi Villa-Freixa
Author: Michael Johnston
This application 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 application 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
Library General Public License for more details.
You should have received a copy of the GNU General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
*/
#include "AdunKernel/AdunSimulator.h"
@implementation AdSimulator
- (void) emptyPool
{
[pool release];
pool = [[NSAutoreleasePool alloc] init];
AdLogMemoryUsage();
}
- (void) endProduction
{
endSimulation = YES;
}
- (id) init
{
return [self initWithForceFields: nil];
}
- (id) initWithForceFields: (AdForceFieldCollection*) aForceFieldCollection
{
return [self initWithSystems: nil
forceFields: aForceFieldCollection];
}
- (id) initWithSystems: (AdSystemCollection*) aSystemCollection
forceFields: (AdForceFieldCollection*) aForceFieldCollection
{
return [self initWithSystems: aSystemCollection
forceFields: aForceFieldCollection
numberOfSteps: 1000];
}
- (id) initWithSystems: (AdSystemCollection*) aSystemCollection
forceFields: (AdForceFieldCollection*) aForceFieldCollection
numberOfSteps: (unsigned int) intOne
{
return [self initWithSystems: aSystemCollection
forceFields: aForceFieldCollection
numberOfSteps: intOne
timeStep: 1.0];
}
- (id) initWithSystems: (AdSystemCollection*) aSystemCollection
forceFields: (AdForceFieldCollection*) aForceFieldCollection
numberOfSteps: (unsigned int) intOne
timeStep: (double) aDouble
{
return [self initWithSystems: aSystemCollection
forceFields: aForceFieldCollection
components: [NSArray array]
numberOfSteps: intOne
timeStep: aDouble];
}
- (id) initWithSystems: (AdSystemCollection*) aSystemCollection
forceFields: (AdForceFieldCollection*) aForceFieldCollection
components: (NSArray*) anArray
numberOfSteps: (unsigned int) intOne
timeStep: (double) aDouble
{
return [self initWithSystems: aSystemCollection
forceFields: aForceFieldCollection
components: anArray
numberOfSteps: intOne
timeStep: aDouble
checkFPErrorInterval: 100];
}
- (id) initWithSystems: (AdSystemCollection*) aSystemCollection
forceFields: (AdForceFieldCollection*) aForceFieldCollection
components: (NSArray*) anArray
numberOfSteps: (unsigned int) intOne
timeStep: (double) aDouble
checkFPErrorInterval: (unsigned int) intTwo
{
NSEnumerator* componentsEnum;
id component;
if((self = [super init]))
{
endSimulation = NO;
numberOfSteps = intOne;
NSDebugLLog(@"AdSimulator", @"The number of steps is %d", numberOfSteps);
timeStep = aDouble;
[self setTimeStep: timeStep];
checkFPErrorInterval = intTwo;
currentStep = 0;
componentsEnum = [anArray objectEnumerator];
while((component = [componentsEnum nextObject]))
if(![component conformsToProtocol: @protocol(AdSimulatorComponent)])
[NSException raise: NSInvalidArgumentException
format: @"All components must conform to AdSimulatorComponent"];
components = [anArray copy];
timer = [AdMainLoopTimer mainLoopTimer];
[self setForceFields: aForceFieldCollection];
[self setSystems: aSystemCollection];
}
return self;
}
- (void) dealloc
{
[systems release];
[systemCollection release];
[forceFieldCollection release];
[components release];
[super dealloc];
}
- (NSString*) description
{
NSMutableString* description;
NSEnumerator* componentEnum;
id component;
description = [NSMutableString string];
[description appendFormat: @"Class: %@\n", NSStringFromClass([self class])];
[description appendFormat: @"Timestep: %-4.2lf. Number of steps: %d. ",
timeStep, numberOfSteps];
[description appendFormat: @"Floating point error check interval: %d\n", checkFPErrorInterval];
[description appendFormat: @"Components:\n"];
if([components count] > 0)
{
componentEnum = [components objectEnumerator];
while(component = [componentEnum nextObject])
[description appendFormat: @"\t%@\n", [component description]];
}
else
[description appendString: @"\tNone\n"];
return description;
}
- (void) _simulateFrom: (int) start to: (int) end
{
register int j, k;
int numberOfAtoms, offset;
AdMatrix* coordinates, *accelerations, *velocities;
NSString* name;
NSEnumerator *systemEnum, *interactionSystemEnum, *forceFieldEnum, *componentEnum;
id system, interactionSystem, forceField, component;
pool = [[NSAutoreleasePool alloc] init];
//Notify all components that production is about to start
componentEnum = [components objectEnumerator];
while((component = [componentEnum nextObject]))
[component simulator: self
willBeginProductionWithSystems: systemCollection
forceFields: forceFieldCollection];
//Set timers
[timer sendMessage: @selector(emptyPool)
toObject: self
interval: 100
name: @"Autorelease"];
[timer sendMessage: @selector(checkFloatingPointErrors)
toObject: self
interval: checkFPErrorInterval
name: @"FloatingPointErrors"];
for(currentStep=start; currentStep < end; currentStep++)
{
NSDebugLLog(@"SimulationLoop",
@"\nBeginning numerical integration - step %d",
currentStep);
systemEnum = [systems objectEnumerator];
while((system = [systemEnum nextObject]))
{
name = [system systemName];
coordinates = [system coordinates];
velocities = [system velocities];
/*** First Step ***/
[components makeObjectsPerformSelector:
@selector(simulatorWillPerformFirstVelocityUpdateForSystem:)
withObject: system];
numberOfAtoms = coordinates->no_rows;
//Intra-System Forces
forceFieldEnum = [[forceFieldCollection forceFieldsForSystem: system
activityFlag: AdActiveForceFields]
objectEnumerator];
[system object: self willBeginWritingToMatrix: velocities];
while((forceField = [forceFieldEnum nextObject]))
{
accelerations = [forceField accelerations];
for(j=0; j < numberOfAtoms; j++)
for(k=0; k<3; k++)
velocities->matrix[j][k] += accelerations->matrix[j][k]*halfTimeStep;
}
//Inter-System Forces - Taking care of offsets
//FIXME: Precompute for each system
interactionSystemEnum = [[systemCollection interactionSystemsInvolvingSystem: system]
objectEnumerator];
while((interactionSystem = [interactionSystemEnum nextObject]))
{
forceFieldEnum = [[forceFieldCollection forceFieldsForSystem: interactionSystem
activityFlag: AdActiveForceFields]
objectEnumerator];
//Get the offset into the acceleration matrix of
//the interactionSystem for this system
offset = [interactionSystem rangeForSystem: system].location;
while((forceField = [forceFieldEnum nextObject]))
{
accelerations = [forceField accelerations];
for(j=0; j < numberOfAtoms; j++)
for(k=0; k<3; k++)
velocities->matrix[j][k] += accelerations->matrix[j+offset][k]*halfTimeStep;
}
}
[system object: self didFinishWritingToMatrix: velocities];
/*** Second Step ***/
[components makeObjectsPerformSelector:
@selector(simulatorWillPerformPositionUpdateForSystem:)
withObject: system];
[system object: self willBeginWritingToMatrix: coordinates];
for(k=0; k < numberOfAtoms; k++)
for(j=0; j< 3; j++)
coordinates->matrix[k][j] += velocities->matrix[k][j]*timeStep;
[system object: self didFinishWritingToMatrix: coordinates];
[components makeObjectsPerformSelector:
@selector(simulatorDidPerformPositionUpdateForSystem:)
withObject: system];
}
[forceFieldCollection evaluateForces];
systemEnum = [systems objectEnumerator];
while((system = [systemEnum nextObject]))
{
name = [system systemName];
velocities = [system velocities];
numberOfAtoms = [system numberOfElements];
/*** Final Step ***/
[components makeObjectsPerformSelector:
@selector(simulatorWillPerformSecondVelocityUpdateForSystem:)
withObject: system];
//Intra-System Forces
forceFieldEnum = [[forceFieldCollection forceFieldsForSystem: system]
objectEnumerator];
[system object: self willBeginWritingToMatrix: velocities];
while((forceField = [forceFieldEnum nextObject]))
{
accelerations = [forceField accelerations];
for(j=0; j < numberOfAtoms; j++)
for(k=0; k<3; k++)
velocities->matrix[j][k] += accelerations->matrix[j][k]*halfTimeStep;
}
//Inter-System Forces
//FIXME: Precompute for each system
interactionSystemEnum = [[systemCollection interactionSystemsInvolvingSystem: system]
objectEnumerator];
while((interactionSystem = [interactionSystemEnum nextObject]))
{
forceField = [[forceFieldCollection forceFieldsForSystem: interactionSystem
activityFlag: AdActiveForceFields]
objectEnumerator];
while((forceField = [forceFieldEnum nextObject]))
{
accelerations = [forceField accelerations];
offset = [interactionSystem rangeForSystem: system].location;
for(j=0; j < numberOfAtoms; j++)
for(k=0; k<3; k++)
velocities->matrix[j][k] += accelerations->matrix[j+offset][k]*halfTimeStep;
}
}
[system object: self didFinishWritingToMatrix: velocities];
[components makeObjectsPerformSelector:
@selector(simulatorDidPerformSecondVelocityUpdateForSystem:)
withObject: system];
}
[timer increment];
NSDebugLLog(@"SimulationLoop",
@"Finished numerical integration - step %d",
currentStep);
//Don't like this but it seems to be the simplest and
//cleanest way to get the loop to exit when you want it to.
if(endSimulation)
break;
}
//Notify all components that production finished
componentEnum = [components objectEnumerator];
while((component = [componentEnum nextObject]))
[component simulatorDidFinishProduction: self];
[timer removeMessageWithName: @"Autorelease"];
[timer removeMessageWithName: @"FloatingPointErrors"];
[pool release];
}
- (BOOL) production: (NSError**) error
{
BOOL success;
struct tms start;
struct tms end;
NS_DURING
{
GSPrintf(stdout,
@"Beginning numerical integration - %d steps\n",
numberOfSteps);
//Send a notification
[[NSNotificationCenter defaultCenter]
postNotificationName: @"AdConfigurationGeneratorWillBeginProductionNotification"
object: self];
times(&start);
[self _simulateFrom: 0 to: numberOfSteps];
times(&end);
GSPrintf(stdout, @"Finished numerical integration - step %d\n\n",
currentStep);
NSDebugLLog(@"SimulationLoop",
@"Numerical integration complete");
success = YES;
}
NS_HANDLER
{
times(&end);
success = NO;
*error = [[localException userInfo] objectForKey: @"AdKnownExceptionError"];
if(*error == nil)
{
//Its an unknown framework exception
*error = AdCreateError(AdunKernelErrorDomain,
AdKernelUnknownError,
@"Caught an exception from framework",
[NSString stringWithFormat:
@"Name %@. Reason %@",
[localException name], [localException reason]],
[NSString stringWithFormat: @"User info %@",
[localException userInfo]]);
}
NSWarnLog(@"Detected error in integration - step %d", currentStep);
GSPrintf(stdout, @"Detected error in integration - step %d\n", currentStep);
}
NS_ENDHANDLER
//Print out some timing information for people who like that sort of thing.
AdLogTimingInformation(&start, &end, numberOfSteps);
fflush(stdout);
return success;
}
- (BOOL) restartFrom: (int) step error: (NSError**) error
{
BOOL success;
struct tms start;
struct tms end;
NS_DURING
{
GSPrintf(stdout,
@"Restarting numerical integration from step %d - %d steps remaining\n",
step, numberOfSteps - step);
times(&start);
[self _simulateFrom: step to: numberOfSteps];
times(&end);
GSPrintf(stdout, @"Finished numerical integration - step %d\n\n",
currentStep);
NSDebugLLog(@"SimulationLoop",
@"Numerical integration complete");
success = YES;
}
NS_HANDLER
{
times(&end);
success = NO;
*error = [[localException userInfo] objectForKey: @"AdKnownExceptionError"];
if(*error == nil)
{
//Its an unknown framework exception
*error = AdCreateError(AdunKernelErrorDomain,
AdKernelUnknownError,
@"Caught an exception from framework",
[NSString stringWithFormat:
@"Name %@. Reason %@",
[localException name], [localException reason]],
[NSString stringWithFormat: @"User info %@",
[localException userInfo]]);
}
NSWarnLog(@"Detected error in integration - step %d", currentStep);
GSPrintf(stdout, @"Detected error in integration - step %d\n", currentStep);
}
NS_ENDHANDLER
AdLogTimingInformation(&start, &end, numberOfSteps);
fflush(stdout);
return success;
}
/*
* Object Accessors
*/
- (AdSystemCollection*) systems
{
return [[systemCollection retain] autorelease];
}
- (void) setSystems: (AdSystemCollection*) aCollection
{
[systemCollection release];
if(systems != nil)
[systems release];
systemCollection = [aCollection retain];
systems = [systemCollection fullSystems];
[systems retain];
}
- (AdForceFieldCollection*) forceFields
{
return [[forceFieldCollection retain] autorelease];
}
- (void) setForceFields: (AdForceFieldCollection*) object
{
[forceFieldCollection release];
forceFieldCollection = [object retain];
}
- (void) addComponent: (id) anObject
{
if(![anObject conformsToProtocol: @protocol(AdSimulatorComponent)])
[NSException raise: NSInvalidArgumentException
format: @"Only object conforming to AdSystemComponent can be added as components"];
[components addObject: anObject];
}
- (void) removeComponent: (id) anObject
{
[components removeObject: anObject];
}
- (NSArray*) allComponents
{
return [[components copy] autorelease];
}
- (void) setNumberOfSteps: (unsigned int) anInt
{
numberOfSteps = anInt;
}
- (unsigned int) numberOfSteps
{
return numberOfSteps;
}
- (double) timeStep
{
return timeStep;
}
- (void) setTimeStep: (double) aDouble
{
timeStep = aDouble;
halfTimeStep = timeStep*0.5;
halfTimeStepSquared = halfTimeStep*timeStep;
}
- (unsigned int) currentStep
{
return currentStep;
}
@end
|