File: AdunMolecularMechanicsForceField.m

package info (click to toggle)
adun.app 0.8.2-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 6,824 kB
  • ctags: 713
  • sloc: objc: 49,683; ansic: 4,680; sh: 523; python: 79; makefile: 67; cpp: 33
file content (897 lines) | stat: -rwxr-xr-x 24,652 bytes parent folder | download
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
/*
   Project: Adun

   Copyright (C) 2007 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/AdunMolecularMechanicsForceField.h"

@class AdEnzymixForceField;
@class AdMolecularMechanicsForceField;
@class AdCharmmForceField;

static NSArray* forceFields;

/**
Private methods for maintaining state
*/
@interface AdMolecularMechanicsForceField (PrivateInternals)
- (void) _systemCleanUp;
- (void) _updateAccelerations;
- (void) _initialisationForSystem;
- (void) _createReciprocalMassArray;
- (void) _handleSystemContentsChange: (NSNotification*) aNotification;
- (AdMatrix*) _internalDataStorageForGroups: (AdDataMatrix*) groups parameters: (AdDataMatrix*) parameters;
@end

BOOL forceFieldDebug = NO;

@implementation AdMolecularMechanicsForceField

+ (void) initialize
{
	static BOOL didInitialize = NO;
	BOOL diagnoseBondedFunctions, diagnoseNonbondedFunctions, diagnoseForceFieldFunctions;
	NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];

	if(didInitialize)
		return;
		
	forceFields = [NSArray arrayWithObjects:
			@"Enzymix",
			@"Amber",
			@"Charmm27",
			nil];
	[forceFields retain];

	//Register base debug defaults - turned off
	[userDefaults registerDefaults:
		[NSDictionary dictionaryWithObjectsAndKeys:
			NO, @"DiagnoseForceFieldFunctions",
			NO, @"DiagoseBondedForceFieldFunctions",
			NO, @"DiagnoseNonbondedForceFieldFunctions",
			nil]];
			
	//Now read the values of the above defaults.
	//If the user didnt set their own values then the
	//above values will be returned.
	
	diagnoseForceFieldFunctions = [userDefaults boolForKey: @"DiagnoseForceFieldFunctions"];
	//If this is turned on the bonded and nonbonded diagnosing is turned on by default.
	if(diagnoseForceFieldFunctions)
	{
		diagnoseBondedFunctions = YES;
		diagnoseNonbondedFunctions = YES;
	}
	else
	{
		diagnoseBondedFunctions = [userDefaults boolForKey: 
						@"DiagnoseBondedForceFieldFunctions"];
		diagnoseNonbondedFunctions = [userDefaults boolForKey:
						@"DiagnoseNonbondedForceFieldFunctions"];
	}

	//Turn on the relevant debugging by setting the value of the debug
	//globals in AdForceFieldFunctions.h to 1
	if(diagnoseBondedFunctions)
	{
		NSLog(@"Bonded force field term diagnostics turned on");
		__HarmonicBondForceDebug__ = true;
		__HarmonicBondEnergyDebug__ = true;
		__HarmonicAngleEnergyDebug__ = true;
		__HarmonicAngleForceDebug__ = true;
		__FourierTorsionEnergyDebug__ = true;
		__FourierTorsionForceDebug__ = true;
		__HarmonicImproperTorsionEnergyDebug__ = true;
		__HarmonicImproperTorsionForceDebug__ = true;
		forceFieldDebug = YES;
	}
	
	if(diagnoseNonbondedFunctions)
	{
		NSLog(@"Nonbonded force field term diagnostics turned on");
		__NonbondedEnergyDebug__ = true;
		__NonbondedForceDebug__ = true;
		__ShiftedNonbondedForceDebug__ = true;
		__ShiftedNonbondedEnergyDebug__ = true;
		__GRFNonbondedForceDebug__ = true;
		__GRFNonbondedEnergyDebug__ = true;
		forceFieldDebug = YES;
	}

	didInitialize = YES;
}

+ (id) classForForceField: (NSString*) forceFieldName
{
	if(![forceFields containsObject: forceFieldName])
	{
		NSWarnLog(@"Unknown force field %@", forceFieldName);
		NSWarnLog(@"Defaulting to enzymix");
		return [AdEnzymixForceField class];
	}	
	else if([forceFieldName isEqual: @"Amber"])
		return [AdMolecularMechanicsForceField class];
	else if([forceFieldName isEqual: @"Enzymix"])
		return [AdEnzymixForceField class];
	else if([forceFieldName isEqual: @"Charmm27"])
		return [AdCharmmForceField class];

	return nil;
}

- (id) init
{
	return [self initWithSystem: nil];
}

- (id) initWithSystem: (id) aSystem
{
	return [self initWithSystem: aSystem nonbondedTerm: nil];
}

- (id) initWithSystem: (id) aSystem nonbondedTerm: (AdNonbondedTerm*) aTerm
{
	return [self initWithSystem: aSystem 
		nonbondedTerm: aTerm 
		customTerms: nil];
}

- (id) initWithSystem: (id) system 
	nonbondedTerm: (AdNonbondedTerm*) anObject
	customTerms: (NSDictionary*) aDict
{

	if((self = [super init]))
	{
		//Get the vdw interaction type of the subclass
		vdwInteractionType = [self vdwInteractionType];
		[vdwInteractionType retain];
	}
	
	return self;
}

- (void) dealloc
{
	AdMemoryManager* memoryManager = [AdMemoryManager appMemoryManager];

	[[NSNotificationCenter defaultCenter] 
		removeObserver: self];
	[system release];
	[state release];
	[availableTerms release];
	[customTerms release];
	[nonbondedTerm release];
	[vdwInteractionType release];
	[memoryManager freeMatrix: bonds];
	[memoryManager freeMatrix: angles];
	[memoryManager freeMatrix: torsions];
	[memoryManager freeMatrix: improperTorsions];
	[memoryManager freeMatrix: forceMatrix];
	[memoryManager freeMatrix: accelerationMatrix];
	[memoryManager freeArray: reciprocalMasses];
	[super dealloc];
}

//Force & Energy calculation methods.
//Here we just flush stderr if debugging is turned on.

- (void) evaluateForces
{
	if(forceFieldDebug)
		fflush(stderr);
}

- (void) evaluateForcesDueToElements: (NSIndexSet*) elementIndexes
{
	if(forceFieldDebug)
		fflush(stderr);
}

- (void) evaluateEnergies
{
	if(forceFieldDebug)
		fflush(stderr);
}

- (void) evaluateEnergiesUsingInteractionsInvolvingElements: (NSIndexSet*) elementIndexes
{
	if(forceFieldDebug)
		fflush(stderr);
}

//custom term methods

- (void) addCustomTerm: (id) object withName: (NSString*) name
{
	if([object conformsToProtocol: @protocol(AdForceFieldTerm)])
	{
		[customTerms setObject: object forKey: name];
		//FIXME: Deal with the case where name already exists.
		[availableTerms addObject: name];
		[[state valueForKey: @"CustomTerms"] 
			setObject: [NSNumber numberWithInt: 0]
			forKey: name];
	}
	else
		[NSException raise: NSInvalidArgumentException
			format: @"Invalid class for custom force object. Must conform to AdForceFieldTerm"];
} 

- (void) addCustomTerms: (NSDictionary*) aDict
{
	NSEnumerator* keyEnum;
	NSString* key;

	keyEnum = [aDict keyEnumerator];
	while((key = [keyEnum nextObject]))
		[self addCustomTerm: [aDict objectForKey: key] 
			withName: key];
}

- (void) setCustomTerms: (NSDictionary*) aDict
{
	NSEnumerator* keyEnum;
	NSString* termName;
	NSMutableDictionary* oldTerms;

	//Remove all previous terms	
	oldTerms = [[customTerms mutableCopy] autorelease];
	[customTerms removeAllObjects];
	keyEnum = [aDict keyEnumerator];
	while((termName = [keyEnum nextObject]))
	{
		NS_DURING
		{
			[self addCustomTerm: [aDict objectForKey: termName]
				withName: termName];
		}
		NS_HANDLER
		{	
			[customTerms removeAllObjects];
			//Restore the old terms
			customTerms = [oldTerms retain];
			[localException raise];
		}
		NS_ENDHANDLER
	}
}

- (void) removeCustomTermWithName: (NSString*) name
{
	[customTerms removeObjectForKey: name];
	[[state valueForKey: @"CustomTerms"]
		removeObjectForKey: name];
	[availableTerms removeObject: name];	
}

//Activating/Deactivating Terms

- (NSArray*) activatedTerms
{
	NSMutableArray* terms;

	terms = [self availableTerms];
	[terms removeObjectsInArray: [self deactivatedTerms]]; 

	return terms;
}

- (NSArray*) deactivatedTerms
{
	return [[[state valueForKey: @"InactiveTerms"] copy] autorelease];
}

- (void) deactivateTerm: (NSString*) termName
{
	if([availableTerms containsObject: termName])
	{
		if(![[state valueForKey: @"InactiveTerms"] containsObject: termName])
		{
			if([termName isEqual: @"HarmonicBond"])
				harmonicBond = NO;
			if([termName isEqual: @"HarmonicAngle"])
				harmonicAngle = NO;
			if([termName isEqual: @"FourierTorsion"])
				fourierTorsion = NO;
			if([termName isEqual: @"HarmonicImproperTorsion"])
				improperTorsion = NO;
			if([termName isEqual: @"Nonbonded"])
				nonbonded = NO;

			[[state valueForKey: @"InactiveTerms"] addObject: termName];
		}
	}
}

- (void) deactivateTermsWithNames: (NSArray*) names
{
	NSEnumerator* termEnum;
	id term;

	termEnum = [names objectEnumerator];
	while((term = [termEnum nextObject]))
		[self deactivateTerm: term];
}

- (void) activateTerm: (NSString*) termName
{
	if([availableTerms containsObject: termName])
	{
		if([[state valueForKey: @"InactiveTerms"] containsObject: termName])
		{
			if([termName isEqual: @"HarmonicBond"])
				harmonicBond = YES;
			if([termName isEqual: @"HarmonicAngle"])
				harmonicAngle = YES;
			if([termName isEqual: @"FourierTorsion"])
				fourierTorsion = YES;
			if([termName isEqual: @"HarmonicImproperTorsion"])
				improperTorsion = YES;
			if([termName isEqual: @"Nonbonded"])
				nonbonded = YES;

			[[state valueForKey: @"InactiveTerms"] removeObject: termName];
		}
	}
}

- (void) activateTermsWithNames: (NSArray*) names
{
	NSEnumerator* termEnum;
	id term;

	termEnum = [names objectEnumerator];
	while((term = [termEnum nextObject]))
		[self activateTerm: term];
}

- (void) clearForces
{
	int i,j;

	for(i=0; i<forceMatrix->no_rows; i++)
		for(j=0; j<3; j++)
			forceMatrix->matrix[i][j] = 0;

	[self _updateAccelerations];		
}

- (AdMatrix*) forces
{
	return forceMatrix;
}

- (AdMatrix*) accelerations
{
	return accelerationMatrix;
}

/********************

Accessors

********************/

- (double) totalEnergy
{
	return total_energy;
}

- (id) availableTerms
{
	return [[availableTerms copy] autorelease];
}

- (NSArray*) arrayOfEnergiesForTerms: (NSArray*) terms notFoundMarker: (id) anObject
{
	double value;
	NSArray* potentials;
	NSMutableArray* array = [NSMutableArray array];
	NSEnumerator* potentialsEnum;
	id object;

	potentials = [[state valueForKey: @"TermPotentials"]
			objectsForKeys: terms notFoundMarker: anObject];
	potentialsEnum = [potentials objectEnumerator];		
	while((object = [potentialsEnum nextObject]))
	{
		if(object != anObject)
		{
			value = *(double*)[object pointerValue];
			[array addObject: [NSNumber numberWithDouble: value]];
		}
		else
			[array addObject: anObject];
	}		

	//FIXME: Have to search custom terms for any value not
	//found above

	return array;
}

- (NSDictionary*) dictionaryOfEnergiesForTerms: (NSArray*) array
{
	NSArray* energies;

	energies = [self arrayOfEnergiesForTerms: array notFoundMarker: [NSNull null]];
	return [NSDictionary dictionaryWithObjects: energies
		forKeys: array];
}

- (NSArray*) coreTerms
{
	return [[coreTerms retain] autorelease];
}

- (NSArray*) arrayOfCoreTermEnergies
{
	NSArray* array;

	array = [NSArray arrayWithObjects: 
			[NSNumber numberWithDouble: bnd_pot],
			[NSNumber numberWithDouble: ang_pot],
			[NSNumber numberWithDouble: tor_pot],
			[NSNumber numberWithDouble: itor_pot],
			[NSNumber numberWithDouble: vdw_pot],
			[NSNumber numberWithDouble: est_pot],
			nil];

	return array;
}

- (NSDictionary*) dictionaryOfCoreTermEnergies
{
	NSArray* energies;

	energies = [self arrayOfCoreTermEnergies];
	return [NSDictionary dictionaryWithObjects: energies
		forKeys: coreTerms];
}

- (id) system
{
	return [[system retain] autorelease];
}

- (void) setSystem: (id) object
{
	if(system != nil)
	{
		[system release];
		[[NSNotificationCenter defaultCenter] 
			removeObserver:self name:nil object: system];
		//clean up all variables relating to the last system
		[self _systemCleanUp];
	}

	system = [object retain];
	[self _initialisationForSystem];
	if(nonbondedTerm != nil)
	{
		if(system != [nonbondedTerm system])
			[nonbondedTerm setSystem: system];

		[nonbondedTerm setExternalForceMatrix: forceMatrix];
	}	

	[[NSNotificationCenter defaultCenter]
		addObserver: self
		selector: @selector(_handleSystemContentsChange:)
		name: @"AdSystemContentsDidChangeNotification"
		object: system];
}

- (void) setNonbondedTerm: (AdNonbondedTerm*) aTerm
{
	[nonbondedTerm release];
	nonbondedTerm = aTerm;
	[nonbondedTerm retain];
		
	if(system != nil)	
	{
		if(system != [aTerm system] )
			[aTerm setSystem: system];
		
		[nonbondedTerm setExternalForceMatrix: forceMatrix];
	}		

	[state setObject: NSStringFromClass([aTerm class])
		 forKey: @"NonbondedTerm"];
}

- (AdNonbondedTerm*) nonbondedTerm
{
	return [[nonbondedTerm retain] autorelease];
}

- (NSString*) vdwInteractionType
{
	return @"TypeOneVDWInteraction";
}

- (NSString*) description
{
	int i;
	NSMutableString* description;
	NSDictionary* energies;
	NSArray* array;
	NSEnumerator* termEnum;
	id term;
	
	description = [NSMutableString string];
	[description appendFormat: @"ForceField: %@\n", [state objectForKey: @"ForceField"]];
	
	[description appendString: @"Available Terms for computation:\n"];
	for(i=0; i<(int)[availableTerms count]; i++)
		[description appendFormat: @"\t%@\n", [availableTerms objectAtIndex: i]];
	
	[description appendString: @"NonbondedTerm:\n"];
	if(nonbondedTerm == nil)
		[description appendString: @"\tNone\n"];
	else
		[description appendFormat: @"\t%@", [nonbondedTerm description]];
				
	[description appendString: @"CustomTerms:\n"];
	if([customTerms count] == 0)
		[description appendString: @"\tNone\n"];
	else
	{	
		termEnum = [customTerms objectEnumerator];
		while(term = [termEnum nextObject])
			[description appendFormat: @"\t%@\n", [term description]];
	}					
	
	array = [state valueForKey: @"InactiveTerms"];
	if([array count] != 0)
	{
		[description appendString: @"InactiveTerms:\n"];
		for(i=0; i<(int)[array count]; i++)
			[description appendFormat: @"\t%@\n", [array objectAtIndex: i]];
	}		
	
	if(system != nil)
	{
		[description appendFormat: @"System: %@\n", [system systemName]];
		[self evaluateEnergies];
		energies = [self dictionaryOfCoreTermEnergies];
		termEnum = [energies keyEnumerator];
		while(term = [termEnum nextObject])
			[description appendFormat: @"\t%25@: %10.5lf Sim Units\n", 
				term, [[energies objectForKey: term] doubleValue]];
	}
		
	return description;
}

@end

@implementation AdMolecularMechanicsForceField (PrivateInternals)

/*
 * Resets variables and frees memory associated with the current system.
 * FIXME: Does not handle custom terms properly
 */

- (void) _systemCleanUp
{
	AdMemoryManager* memoryManager = [AdMemoryManager appMemoryManager];

	[availableTerms removeAllObjects];
	[[state valueForKey:@"InactiveTerms"] removeAllObjects];

	[nonbondedTerm setSystem: nil];
	[memoryManager freeMatrix: bonds];
	[memoryManager freeMatrix: angles];
	[memoryManager freeMatrix: torsions];
	[memoryManager freeMatrix: improperTorsions];
	[memoryManager freeMatrix: forceMatrix];
	[memoryManager freeMatrix: accelerationMatrix];
	[memoryManager freeArray: reciprocalMasses];

	harmonicBond = harmonicAngle = fourierTorsion = improperTorsion = nonbonded = NO;
	bnd_pot = ang_pot = tor_pot = vdw_pot = est_pot = itor_pot = total_energy = 0;
	bonds = angles = torsions = improperTorsions = forceMatrix = accelerationMatrix = NULL;
	reciprocalMasses = NULL;
}

- (void) _createReciprocalMassArray
{
	int i;
	NSArray* massArray;
	AdMemoryManager* memoryManager = [AdMemoryManager appMemoryManager];

	massArray = [system elementMasses];
	reciprocalMasses = [memoryManager allocateArrayOfSize: [massArray count]*sizeof(double)];
	for(i=0; i<(int)[massArray count]; i++)
		reciprocalMasses[i] = 1/[[massArray objectAtIndex: i] doubleValue];
}

/*
 * The information provided by AdSystem is in the form of AdDataMatrices.
 * We need to convert this information into a more primitive and efficent
 * form i.e. AdMatrix stuctures, for use with the C force field functions.
 */
- (AdMatrix*) _internalDataStorageForGroups: (AdDataMatrix*) groups parameters: (AdDataMatrix*) parameters
{
	int numberRows, numberColumns;
	AdMatrix* interaction;

	numberRows = [groups numberOfRows];
	numberColumns = [groups numberOfColumns] + [parameters numberOfColumns];

	interaction = [[AdMemoryManager appMemoryManager] 
			allocateMatrixWithRows: numberRows
			withColumns: numberColumns];
	return interaction;		
}

- (void) _initialisationForSystem
{
	int i, j;
	NSArray* interactionTypes;
	AdDataMatrix *groups, *parameters;

	NSDebugLLog(@"AdMolecularMechanicsForceField", 
		@"Begining system initialisation");

	no_of_atoms = [system numberOfElements];

	//allocate a force and acceleration matrix
	forceMatrix = [[AdMemoryManager appMemoryManager]
			allocateMatrixWithRows: no_of_atoms
			withColumns: 3];
	accelerationMatrix = [[AdMemoryManager appMemoryManager]
				allocateMatrixWithRows: no_of_atoms
				withColumns: 3];
	[self _createReciprocalMassArray];	

	/*
	 * Check what interaction types the system provides information for
	 * and which of these are core terms of this force field.
	 * For each one that is a core terms we convert the information
	 * provided into an internal representation which we will use with
	 * the primitive C force field functions.
	 */

	interactionTypes = [system availableInteractions];

	if([interactionTypes containsObject: @"HarmonicBond"])
	{
		harmonicBond = YES;
		groups = [system groupsForInteraction: @"HarmonicBond"];
		parameters = [system parametersForInteraction: @"HarmonicBond"];
		bonds = [self _internalDataStorageForGroups: groups
				parameters: parameters];
		
		for(i=0; i<bonds->no_rows; i++)
		{
			for(j=0; j<2; j++)
				bonds->matrix[i][j] = [[groups elementAtRow: i column: j] doubleValue];

			bonds->matrix[i][2] = [[parameters elementAtRow: i 
						ofColumnWithHeader: @"Constant"] doubleValue];
			bonds->matrix[i][3] = [[parameters elementAtRow: i 
						ofColumnWithHeader: @"Separation"] doubleValue];
		}
		
		[availableTerms addObject: @"HarmonicBond"];
	}
	else
		harmonicBond = NO;	
	
	if([interactionTypes containsObject: @"HarmonicAngle"])
	{
		harmonicAngle = YES;

		groups = [system groupsForInteraction: @"HarmonicAngle"];
		parameters = [system parametersForInteraction: @"HarmonicAngle"];
		angles = [self _internalDataStorageForGroups: groups
				parameters: parameters];
		
		for(i=0; i<angles->no_rows; i++)
		{
			for(j=0; j<(int)[groups numberOfColumns]; j++)
				angles->matrix[i][j] = [[groups elementAtRow: i column: j] doubleValue];

			angles->matrix[i][3] = [[parameters elementAtRow: i 
						ofColumnWithHeader: @"Constant"] doubleValue];
			angles->matrix[i][4] = [[parameters elementAtRow: i 
						ofColumnWithHeader: @"Angle"] doubleValue];
		}
		
		[availableTerms addObject: @"HarmonicAngle"];
	}
	else
		harmonicAngle = NO;	

	if([interactionTypes containsObject: @"FourierTorsion"])
	{
		fourierTorsion = YES;

		groups = [system groupsForInteraction: @"FourierTorsion"];
		parameters = [system parametersForInteraction: @"FourierTorsion"];
		torsions = [self _internalDataStorageForGroups: groups
				parameters: parameters];
		
		for(i=0; i<torsions->no_rows; i++)
		{
			for(j=0; j<(int)[groups numberOfColumns]; j++)
				torsions->matrix[i][j] = [[groups elementAtRow: i column: j] doubleValue];

			torsions->matrix[i][4] = [[parameters elementAtRow: i 
							ofColumnWithHeader: @"Constant"] doubleValue];
			torsions->matrix[i][5] = [[parameters elementAtRow: i 
							ofColumnWithHeader: @"Periodicity"] doubleValue];
			torsions->matrix[i][6] = [[parameters elementAtRow: i 
							ofColumnWithHeader: @"Phase"] doubleValue];
		}
		
		[availableTerms addObject: @"FourierTorsion"];
	}	
	else
		fourierTorsion = NO;	
	
	if([interactionTypes containsObject: @"HarmonicImproperTorsion"])
	{
		improperTorsion = YES;
	
		groups = [system groupsForInteraction: @"HarmonicImproperTorsion"];
		parameters = [system parametersForInteraction: @"HarmonicImproperTorsion"];
		improperTorsions = [self _internalDataStorageForGroups: groups
					parameters: parameters];
		
		for(i=0; i<improperTorsions->no_rows; i++)
		{
			for(j=0; j<(int)[groups numberOfColumns]; j++)
				improperTorsions->matrix[i][j] = [[groups elementAtRow: i column: j] doubleValue];

			improperTorsions->matrix[i][4] = [[parameters elementAtRow: i 
								ofColumnWithHeader: @"Constant"] doubleValue];
			improperTorsions->matrix[i][5] = [[parameters elementAtRow: i 
								ofColumnWithHeader: @"Angle"] doubleValue];
		}
		
		[availableTerms addObject: @"HarmonicImproperTorsion"];
	}	
	else
		improperTorsion = NO;	

	/*
	 * For VDW and Electrostatic interactions simply check
	 * if they exist. The actual calculation will be done by
	 * a nonbonded list handler object
	 */

	if([interactionTypes containsObject: @"CoulombElectrostatic"] &&
		 [interactionTypes containsObject: vdwInteractionType])
	{
		nonbonded = YES;
		[availableTerms addObject: @"Nonbonded"];
	}	
	else
		nonbonded = NO;	
}

/**
Called when we recieve an AdSystemContentsDidChangeNotification
due to the system reloading its data source.
We dont know what exactly changed so we have to reinitialise
everything.
*/

- (void) _handleSystemContentsChange: (NSNotification*) aNotification
{
	NSEnumerator* inactiveTermsEnum;
	NSMutableArray* inactiveTerms;
	NSMutableArray* removedTerms = [NSMutableArray array];
	NSString* termName;
	AdMemoryManager* memoryManager = [AdMemoryManager appMemoryManager];

	/*
	 * 1) Remove the system dependant terms from available terms.
	 * 2) Assume that custom terms (including nonbonded terms) 
	 * will handle their own updating.
	 * 3) Free topology matrices
	 * 4) Reacquire the system topology matrices.
	 * 5) Update inactive terms
	 * 6) Update the custom terms & nonbonded term with new force matrix
	 */

	NSDebugLLog(@"AdMolecularMechanicsForceField", @"System is %@", [system systemName]);
	NSDebugLLog(@"AdMolecularMechanicsForceField", @"Received an system contents change message"); 
	NSDebugLLog(@"AdMolecularMechanicsForceField", @"Currently available terms %@", availableTerms); 

	[availableTerms removeAllObjects];
	
	NSDebugLLog(@"AdMolecularMechanicsForceField", @"Freeing topology and force related matrices");
	
	[memoryManager freeMatrix: bonds];
	[memoryManager freeMatrix: angles];
	[memoryManager freeMatrix: torsions];
	[memoryManager freeMatrix: improperTorsions];
	[memoryManager freeMatrix: forceMatrix];
	[memoryManager freeMatrix: accelerationMatrix];
	[memoryManager freeArray: reciprocalMasses];

	harmonicBond = harmonicAngle = fourierTorsion = improperTorsion = nonbonded = NO;
	bnd_pot = ang_pot = tor_pot = vdw_pot = est_pot = itor_pot = total_energy = 0;
	bonds = angles = torsions = improperTorsions = forceMatrix = accelerationMatrix = NULL;
	reciprocalMasses = NULL;

	NSDebugLLog(@"AdMolecularMechanicsForceField", @"Reaquiring system information");
	
	[self _initialisationForSystem];

	NSDebugLLog(@"AdMolecularMechanicsForceField", @"Rebuilding available terms");
	
	//Add custom terms back into available terms
	[availableTerms addObjectsFromArray: [customTerms allKeys]];

	NSDebugLLog(@"AdMolecularMechanicsForceField", 
		@"Available terms after reinitialising %@", availableTerms);

	//Check if all inactive terms are still present
	//If they are make sure they have the same state 
	inactiveTerms = [state objectForKey: @"InactiveTerms"];
	NSDebugLLog(@"AdMolecularMechanicsForceField", @"Previous inactive terms %@", inactiveTerms); 
	NSDebugLLog(@"AdMolecularMechanicsForceField",
		@"Updating inactive terms and resetting state where necessary");

	inactiveTermsEnum = [inactiveTerms objectEnumerator];
	while((termName = [inactiveTermsEnum nextObject]))
	{
		if(![availableTerms containsObject: termName])
			[removedTerms addObject: termName];
		else
		{
			if([termName isEqual: @"HarmonicBond"])
				harmonicBond = NO;
			if([termName isEqual: @"HarmonicAngle"])
				harmonicAngle = NO;
			if([termName isEqual: @"FourierTorsion"])
				fourierTorsion = NO;
			if([termName isEqual: @"HarmonicImproperTorsion"])
				improperTorsion = NO;
			if([termName isEqual: @"Nonbonded"])
				nonbonded = NO;
		}
	}	
				
	[inactiveTerms removeObjectsInArray: removedTerms];
	
	NSDebugLLog(@"AdMolecularMechanicsForceField", 
		@"Current inactive terms %@", inactiveTerms); 
	NSDebugLLog(@"AdMolecularMechanicsForceField"
		, @"Updating nonbonded term with new force matrix");
	[nonbondedTerm setExternalForceMatrix: forceMatrix];
	NSDebugLLog(@"AdMolecularMechanicsForceField", @"Update complete");
}

- (void) _updateAccelerations
{
	int i,j;

	for(i=0; i<accelerationMatrix->no_rows; i++)
		for(j=0; j<3; j++)
			accelerationMatrix->matrix[i][j] = forceMatrix->matrix[i][j]*reciprocalMasses[i];
}

@end