summaryrefslogtreecommitdiff
path: root/sim/src/structcompare.c
blob: 14e5e0440f71d6ec22e4bfc992443f2c05f34f03 (plain)
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
// Copyright 2005-2006 Nanorex, Inc.  See LICENSE file for details. 

#include "simulator.h"

static char const rcsid[] = "$Id$";

#define COARSE_TOLERANCE 1e-3
#define FINE_TOLERANCE 1e-8

static int atomCount;
static int allowScaling; // non-zero if a scale difference will be allowed

static struct xyz *BasePositions;
static struct xyz *InitialPositions;

// The "extra" field in this case is the array of coordinates of the
// atom positions.  The position and orientation of the structure as a
// whole is stored in the coordinate array, and it is that position
// which is minimized.  The set of atom positions is a temporary value
// used by the potential function.  This is the routine that defines
// the meaning of the transformations described by the coordinates
// being minimized.
static void
structCompareSetExtra(struct configuration *p)
{
  int i;
  struct xyz translate;
  struct xyz t;
  double rotation[9];
  double scale = 1.0;
  
  if (p->extra != NULL) {
    return;
  }
  p->extra = allocate(sizeof(struct xyz) * atomCount);

  translate.x = p->coordinate[0];
  translate.y = p->coordinate[1];
  translate.z = p->coordinate[2];
  if (allowScaling) {
    scale = p->coordinate[6];
  }

  matrixRotateXYZ(rotation, p->coordinate[3], p->coordinate[4], p->coordinate[5]);

  for (i=0; i<atomCount; i++) {
    vadd2(t, InitialPositions[i], translate);
    if (allowScaling) {
      vmulc(t, scale);
    }
    matrixTransform(&((struct xyz *)p->extra)[i], rotation, &t);
  }
}

static void
structCompareFreeExtra(struct configuration *p)
{
  if (p->extra != NULL) {
    free(p->extra);
    p->extra = NULL;
  }
}

#ifndef isnormal
int
isnormal(double a)
{
    return (a > 0.0 || a <= 0.0);
}
#endif

// Handle the final result for a structure compare.  Pass in an upper
// limit for the standard deviation of atom positions between the two
// structures, and an upper limit for the maximum distance that any
// single atom has moved between the two structures, and an upper
// limit to the scale difference between the structures.  Returns
// non-zero if the configuration exceeds any of these limits.
//
// May want to do a Chi-Squared test here, but I'm not sure of the
// applicability.  Besides, generating Chi-Square values for large
// numbers of degrees of freedom is non-trivial.
static int
structCompareResult(struct configuration *p,
                    double deviationLimit,
                    double maxDeltaLimit,
                    double maxScale)
{
  int i;
  int ret = 0;
  struct xyz delta;
  double squareSum = 0.0;
  double deltaLenSquared;
  double maxDeltaLenSquared = 0.0;
  double maxDeltaLen;
  double standardDeviation;
  double scale = 1.0;
  
  structCompareSetExtra(p);
  for (i=0; i<atomCount; i++) {
    delta = vdif(BasePositions[i], ((struct xyz *)p->extra)[i]);
    deltaLenSquared = vdot(delta, delta);
    squareSum += deltaLenSquared;
    if (maxDeltaLenSquared < deltaLenSquared) {
      maxDeltaLenSquared = deltaLenSquared;
    }
  }
  if (atomCount < 2) {
    standardDeviation = 0.0;
  } else {
    standardDeviation = squareSum / (atomCount - 1);
  }
  maxDeltaLen = sqrt(maxDeltaLenSquared);
  if (allowScaling) {
    scale = fabs(p->coordinate[6]);
    if (scale < 1.0) {
      if (scale > 0.0) {
        scale = 1.0 / scale;
      } // shouldn't ever be zero!
    }
  }
  
  printf("at: translate (%f %f %f)\n       rotate (%f %f %f)\n        scale %f,\nstandard deviation = %e, max delta = %e\n",
         p->coordinate[0], p->coordinate[1], p->coordinate[2],
         p->coordinate[3], p->coordinate[4], p->coordinate[5],
         scale, standardDeviation, maxDeltaLen);

  if (standardDeviation != 0.0 && !isnormal(standardDeviation)) {
    printf("standard deviation not defined\n");
    ret = 1;
  }
  if (standardDeviation > deviationLimit) {
    printf("standard deviation exeeded deviationLimit of %e\n", deviationLimit);
    ret = 1;
  }
  if (maxDeltaLen != 0.0 && !isnormal(maxDeltaLen)) {
    printf("maximum delta not defined\n");
    ret = 1;
  }
  if (maxDeltaLen > maxDeltaLimit) {
    printf("maximum delta exceeded max delta limit of %e\n", maxDeltaLimit);
    ret = 1;
  }
  if (scale != 0.0 && !isnormal(scale)) {
    printf("scale not defined\n");
    ret = 1;
  }
  if (scale > maxScale) {
    printf("scale exceeded limit of %e\n", maxScale);
    ret = 1;
  }
  return ret;
}

// This is the potential function which is being minimized.  We're
// basically doing a least-squares fit for the coordinates of the
// structure as a whole.
static void
structComparePotential(struct configuration *p)
{
  int i;
  struct xyz delta;
  double squareSum = 0.0;

  structCompareSetExtra(p);
  for (i=0; i<atomCount; i++) {
    delta = vdif(BasePositions[i], ((struct xyz *)p->extra)[i]);
    squareSum += vdot(delta, delta);
  }
  p->functionValue = squareSum / atomCount;
  /*
  printf("at: (%f %f %f) (%f %f %f) == %e\n",
         p->coordinate[0], p->coordinate[1], p->coordinate[2],
         p->coordinate[3], p->coordinate[4], p->coordinate[5],
         p->functionValue);
  */
}

// Before starting to rotate the structures, we translate both of them
// to their respective centers of mass.  We're taking each atom as a
// unit mass, ignoring element type.
static void
translateToCenterOfMass(struct xyz *pos, int atomCount)
{
  struct xyz centerOfMass;
  int i;
  
  vsetc(centerOfMass, 0.0);
  for (i=0; i<atomCount; i++) {
    vadd(centerOfMass, pos[i]);
  }
  vdivc(centerOfMass, -atomCount);
  for (i=0; i<atomCount; i++) {
    vadd(pos[i], centerOfMass);
  }
}

static int
structCompareTermination(struct functionDefinition *fd,
                            struct configuration *previous,
                            struct configuration *current)
{
    int ret = defaultTermination(fd, previous, current);

    if (ret && fd->tolerance == COARSE_TOLERANCE) {
      fd->tolerance = FINE_TOLERANCE;
      fd->algorithm = PolakRibiereConjugateGradient;
      fd->linear_algorithm = LinearMinimize;
      return 0;
    }
    return ret;
}

static struct functionDefinition structCompareFunctions;

// Compare two structures to see if they are the same.  The atom
// positions must have been pre-loaded into BasePositions and
// InitialPositions.  The structures are translated to their
// respective centers of mass.  Then, the InitialPositions structure
// is rotated, translated, and optionally scaled (if maxScale > 1.0)
// to minimize the least-square distance between corresponding atoms
// in the two structures.  At most iterLimit iterations of the
// minimize routine are performed.
//
// Prints the final coordinates reached.  
//
// Pass in an upper limit for the standard deviation of atom positions
// between the two structures, and an upper limit for the maximum
// distance that any single atom has moved between the two
// structures, and an upper limit to the scale difference between the
// structures.  Returns non-zero if the configuration exceeds any of
// these limits.
int
doStructureCompare(int numberOfAtoms,
                   struct xyz *basePositions,
                   struct xyz *initialPositions,
                   int iterLimit,
                   double deviationLimit,
                   double maxDeltaLimit,
                   double maxScale)
{
  int iter;
  int ret;
  struct configuration *initial = NULL;
  struct configuration *final = NULL;

  atomCount = numberOfAtoms;
  BasePositions = basePositions;
  InitialPositions = initialPositions;
  allowScaling = maxScale > 1.0;

  translateToCenterOfMass(BasePositions, atomCount);
  translateToCenterOfMass(InitialPositions, atomCount);

  initializeFunctionDefinition(&structCompareFunctions,
                               structComparePotential,
                               allowScaling ? 7 : 6,
                               0);

  structCompareFunctions.gradient_delta = 1e-8;
  structCompareFunctions.freeExtra = structCompareFreeExtra;
  structCompareFunctions.termination = structCompareTermination;
  structCompareFunctions.tolerance = COARSE_TOLERANCE;
  structCompareFunctions.algorithm = SteepestDescent;
  structCompareFunctions.linear_algorithm = LinearBracket;
  structCompareFunctions.initial_parameter_guess = 0.001;

  initial = makeConfiguration(&structCompareFunctions);
  initial->coordinate[0] = 0.0;
  initial->coordinate[1] = 0.0;
  initial->coordinate[2] = 0.0;
  initial->coordinate[3] = 0.0;
  initial->coordinate[4] = 0.0;
  initial->coordinate[5] = 0.0;
  if (allowScaling) {
    initial->coordinate[6] = 1.0;
  }

  final = minimize(initial, &iter, iterLimit);
  ret = structCompareResult(final, deviationLimit, maxDeltaLimit, maxScale);
  SetConfiguration(&initial, NULL);
  SetConfiguration(&final, NULL);
  return ret;
}



#ifdef TEST

static void
testStructureCompare()
{
  int numberOfAtoms;
  struct xyz *basePositions;
  struct xyz *InitialPositions;
  
  numberOfAtoms = 3;
  basePositions = (struct xyz *)allocate(sizeof(struct xyz) * numberOfAtoms);
  InitialPositions = (struct xyz *)allocate(sizeof(struct xyz) * numberOfAtoms);

  basePositions[0].x =   30.0;
  basePositions[0].y =    0.0;
  basePositions[0].z =    0.0;
  basePositions[1].x = - 30.0;
  basePositions[1].y =    0.0;
  basePositions[1].z =   10.0;
  basePositions[2].x = - 30.0;
  basePositions[2].y =    0.0;
  basePositions[2].z =  -10.0;

  initialPositions[0].x =    0.0;
  initialPositions[0].y =   30.0;
  initialPositions[0].z =    0.0;
  initialPositions[1].x =   10.0;
  initialPositions[1].y = - 30.0;
  initialPositions[1].z =    0.0;
  initialPositions[2].x =  -10.0;
  initialPositions[2].y = - 30.0;
  initialPositions[2].z =    0.0;

  doStructureCompare(numberOfAtoms, basePositions, initialPositions, 400, 1e-2, 1e-1, 0.0);
}

int
main(int argc, char **argv)
{
  testStructureCompare();
  exit(0);
}

#endif