File: PCAstats.c

package info (click to toggle)
theseus 3.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 6,152 kB
  • ctags: 2,447
  • sloc: ansic: 42,404; makefile: 250; sh: 131
file content (701 lines) | stat: -rw-r--r-- 23,854 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
/*
    Theseus - maximum likelihood superpositioning of macromolecular structures

    Copyright (C) 2004-2014 Douglas L. Theobald

    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, write to the:

    Free Software Foundation, Inc.,
    59 Temple Place, Suite 330,
    Boston, MA  02111-1307  USA

    -/_|:|_|_\-
*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include "CovMat.h"
#include "DLTutils.h"
#include "DLTmath.h"
#include "Error.h"
#include "PCAstats.h"
#include "pdbIO.h"
#include "pdbMalloc.h"
#include "Cds.h"
#include "PDBCds.h"
#include "pdbStats.h"
#include "pdbUtils.h"


void
CalcPCA(CdsArray *cdsA)
{
    int            i, j;
    int            vlen = (int) cdsA->vlen;
    int            pcanum;
    double       **CovMat = cdsA->CovMat;
    double         sum, runsum;
    PDBCds        *pdbave = NULL;
    char           pcafile_name[256];
    FILE          *pcavecs_fp = NULL, *pcastats_fp = NULL;
    double         biggest, bstick;
    char           aster;
    char          *cov_name = NULL, *cor_name = NULL, *pcvecs_name = NULL, *pcstats_name = NULL;


    pdbave = cdsA->pdbA->avecds;
    pcanum = algo->pca;

    if (pcanum > cdsA->vlen)
        pcanum = algo->pca = cdsA->vlen;

    if (pcanum > cdsA->cnum - 1)
        pcanum = algo->pca = cdsA->cnum - 1;

    cov_name = mystrcat(algo->rootname, "_cov.mat");
    PrintCovMatGnuPlot((const double **) CovMat, vlen, cov_name);

    /* convert it to a correlation matrix */
    if (algo->cormat)
    {
        CovMat2CorMat(CovMat, vlen);
        cor_name = mystrcat(algo->rootname, "_cor.mat");
        PrintCovMatGnuPlot((const double **) CovMat, vlen, cor_name);
    }

//    write_C_mat((const double **) CovMat, vlen, 8, 0);

    /* find the total variance */
    sum = 0.0;
    for (i = 0; i < vlen; ++i)
       sum += CovMat[i][i];

    cdsA->pcamat = MatAlloc(vlen, vlen);
    cdsA->pcavals = malloc(vlen * sizeof(double));

    EigenGSLDest(CovMat, vlen, cdsA->pcavals, cdsA->pcamat, 1);
    MatTransIp(cdsA->pcamat, vlen);
    //MatPrint(cdsA->pcamat, vlen);

    /* LAPACK DSYEVR() computes selected eigenvalues, and optionally, eigenvectors of a
       real symmetric matrix.  Find all eigenvalues (w[]) and eigenvectors (mat[][]).
       The pcanum eigenvalues are in the first pcanum elements of the w[] vector,
       ordered smallest to biggest.  Weird and horrible, but true (and in fact
       makes sense if you think about it). */
    //dsyevr_dest(CovMat, vlen, lower, upper, cdsA->pcavals, cdsA->pcamat, 1e-8);

    //MatPrint(cdsA->pcamat, vlen);

    pcvecs_name = mystrcat(algo->rootname, "_pcvecs.txt");
    pcstats_name = mystrcat(algo->rootname, "_pcstats.txt");
    pcavecs_fp = myfopen(pcvecs_name, "w");
    pcastats_fp = myfopen(pcstats_name, "w");

    if (pcavecs_fp == NULL || pcastats_fp == NULL)
    {
        fprintf(stderr, "\n  ERROR: Could not open PCA files \n");
        PrintTheseusTag();
        exit(EXIT_FAILURE);
    }

    runsum = 0.0;
    fprintf(pcastats_fp, "eigenv   bstick     raw    raw_%%  cumul_%% \n");

    for (i = 0; i < pcanum; ++i)
    {
        bstick = 0.0;
        for (j = i+1; j <= vlen; ++j)
            bstick += (1.0 / (double) j);

        if (bstick < cdsA->pcavals[i] && cdsA->pcavals[i] > 1.0)
            aster = '*';
        else
            aster = ' ';

        runsum += cdsA->pcavals[i];
        fprintf(pcastats_fp, "%-6i %8.3f %8.3f %8.3f %8.3f %c\n",
                i+1, bstick, cdsA->pcavals[i],
                cdsA->pcavals[i] * 100.0 / sum, runsum * 100.0 / sum, aster);
    }
    fputc('\n', pcastats_fp);

    fprintf(pcavecs_fp, "atom ");
    for (j = 0; j < pcanum; ++j)
        fprintf(pcavecs_fp, "     %3d ", j+1);
    fputc('\n', pcavecs_fp);

    for (i = 0; i < vlen; ++i)
    {
        fprintf(pcavecs_fp, "%-4d ", i+1);

        for (j = 0; j < pcanum; ++j)
            fprintf(pcavecs_fp, "%8.3f ", sqrt(cdsA->pcavals[j]) * cdsA->pcamat[j][i]);

        fputc('\n', pcavecs_fp);
    }

    CopyCds2PDB(pdbave, cdsA->avecds);

    for (i = 0; i < pcanum; ++i)
    {
        //printf("\neigenval %d: %g\n", i, cdsA->pcavals[i]);
        /* find largest absolute value in the eigenvector PCA */
        biggest = -DBL_MAX;
        for (j = 0; j < vlen; ++j)
            if (biggest < fabs(cdsA->pcamat[i][j]))
                biggest = fabs(cdsA->pcamat[i][j]);

        /* rescale (for rasmol really) so that the largest eigenvalue component
           is = 99.99, i.e. the largest value allowable in the b-value column
           of a PDB file */
        /* biggest = 1.0; */
        for (j = 0; j < vlen; ++j)
            cdsA->pdbA->avecds->tempFactor[j] = cdsA->pcamat[i][j] * (99.99 / biggest);

        sprintf(pcafile_name, "%s_pc%d_ave.pdb", algo->rootname, i+1);

        //strcpy(pcafile_name, mystrcat(algo->rootname, "_pc"));
        //pcafile_name[11] = '\0';
        //strncat(pcafile_name, itoa(i+1, &numstring[0], 10), 5);
        //strncat(pcafile_name, "_ave.pdb", 8);

        WriteAvePDBCdsFile(cdsA->pdbA, pcafile_name);
    }

    if (pcanum == vlen)
    {
        char *pcvecs_mat_name = mystrcat(algo->rootname, "_pcvecs.mat");

        for (i = 0; i < vlen; ++i)
            for (j = 0; j < pcanum; ++j)
                cdsA->pcamat[j][i] *= sqrt(cdsA->pcavals[j]);

        PrintCovMatGnuPlot((const double **) cdsA->pcamat, vlen, pcvecs_mat_name);
        free(pcvecs_mat_name);
    }

    fclose(pcastats_fp);
    fclose(pcavecs_fp);

    if (cov_name != NULL)
        free(cov_name);

    if (cor_name != NULL)
        free(cor_name);

    if (pcvecs_name != NULL)
        free(pcvecs_name);

    if (pcstats_name != NULL)
        free(pcstats_name);
}


void
Calc3NPCA(CdsArray *cdsA)
{
    int                      i, j;
    int                      vlen = (int) 3 * cdsA->vlen;
    double                 **mat = NULL;
    int                      pcanum;
    double                 **evecs = NULL, *evals = NULL;
    double                   sum, runsum;
    PDBCds               *pdbave = NULL;
    char                     pcafile_name[256];
    FILE                    *pcavecs_fp = NULL, *pcastats_fp = NULL;
    double                   biggest, bstick;
    char                     aster;

    pdbave = cdsA->pdbA->avecds;
    mat = MatAlloc(vlen, vlen);

    if (algo->pca > cdsA->cnum - 1)
        pcanum = algo->pca = cdsA->cnum - 1;
    else
        pcanum = algo->pca;

    /* copy over the covariance matrix */
    memcpy(mat[0], cdsA->FullCovMat[0], vlen * vlen * sizeof(double));
    /* MatPrint(cdsA->FullCovMat, vlen); */
    /* fflush(NULL); */

    /* convert it to a correlation matrix */
    if (algo->cormat)
        CovMat2CorMat(mat, vlen);

    /* find the total variance */
    sum = 0.0;
    for (i = 0; i < vlen; ++i)
       sum += mat[i][i];

    evecs = MatAlloc(vlen, vlen);
    evals = malloc(vlen * sizeof(double));

    /* LAPACK DSYEVR() computes selected eigenvalues, and optionally, eigenvectors of a
       real symmetric matrix.  Find all eigenvalues (w[]) and eigenvectors (mat[][]).
       The pcanum eigenvalues are in the first pcanum elements of the w[] vector,
       ordered smallest to biggest.  Weird and horrible, but true (and in fact
       makes sense if you think about it). */
    //dsyevr_opt_dest(mat, vlen, lower, upper, evals, evecs, 1e-8);

    EigenGSLDest(mat, vlen, evals, evecs, 1);
    MatTransIp(cdsA->pcamat, vlen);

    PrintCovMatGnuPlot((const double **) evecs, vlen, "evecs.mat");

    pcavecs_fp = fopen("pcavecs.txt", "w");
    pcastats_fp = fopen("pcastats.txt", "w");
    if (pcavecs_fp == NULL || pcastats_fp == NULL)
    {
        fprintf(stderr, "\n  ERROR1000: Could not open PCA files \n");
        PrintTheseusTag();
        exit(EXIT_FAILURE);
    }

    runsum = 0.0;
    fprintf(pcastats_fp, "eigenv   bstick     raw    raw_%%  cumul_%% \n");

    for (i = 0; i < pcanum; ++i)
    {
        bstick = 0.0;
        for (j = i+1; j <= vlen; ++j)
            bstick += (1.0 / (double) j);

        if (bstick < evals[i] && evals[i] > 1.0)
            aster = '*';
        else
            aster = ' ';

        runsum += cdsA->pcavals[i];
        fprintf(pcastats_fp, "%-6i %8.3f %8.3f %8.3f %8.3f %c\n",
                i+1, bstick, evals[i],
                evals[i] * 100.0 / sum, runsum * 100.0 / sum, aster);
    }
    fputc('\n', pcastats_fp);

    fprintf(pcavecs_fp, "atom ");
    for (j = 0; j < pcanum; ++j)
        fprintf(pcavecs_fp, "     %3d ", j+1);
    fputc('\n', pcavecs_fp);

    for (i = 0; i < vlen; ++i)
    {
        fprintf(pcavecs_fp, "%-4d ", i+1);

        for (j = 0; j < pcanum; ++j)
            fprintf(pcavecs_fp, "%8.3f ", sqrt(evals[j]) * evecs[j][i]);

        fputc('\n', pcavecs_fp);
    }

    CopyCds2PDB(pdbave, cdsA->avecds);

    for (i = 0; i < pcanum; ++i)
    {
        /* find largest absolute value in the eigenvector PCA */
        biggest = -DBL_MAX;
        for (j = 0; j < vlen; ++j)
            if (biggest < fabs(evecs[i][j]))
                biggest = fabs(evecs[i][j]);

        /* rescale (for rasmol really) so that the largest eigenvalue component
           is = 99.99, i.e. the largest value allowable in the b-value column
           of a PDB file */
        for (j = 0; j < vlen; ++j)
            cdsA->pdbA->avecds->tempFactor[j] = evecs[i][j] * (99.99 / biggest);

        sprintf(pcafile_name, "%s_pc%d", algo->rootname, i+1);

        //strncpy(pcafile_name, mystrcat(algo->rootname, "_pc"), 11);
        //pcafile_name[11] = '\0';
        //strncat(pcafile_name, itoa(i+1, &numstring[0], 10), 5);

        WriteAvePDBCdsFile(cdsA->pdbA, pcafile_name);
    }

    cdsA->pcamat = evecs; /* DLT debug -- this should be copied or dealt with better */
    cdsA->pcavals = evals;

    fclose(pcastats_fp);
    fclose(pcavecs_fp);

    MatDestroy(&mat);
}


void
WritePCAFile(PDBCdsArray *parray, CdsArray *cdsA, const char *outfile_root)
{
    FILE           *pdbfile = NULL;
    char            pcafile_name[256];
    int             i, j, k, m;
    double          biggest = -DBL_MAX;
    const double  **mat = (const double **) cdsA->pcamat;
    const int       cvlen = cdsA->vlen;
    const int       pvlen = parray->vlen;
    double          tempFactor;
    //char            numstring[5];
    char            covcor_str[16] = "correlation";

    /* find largest absolute value in the eigenvector PCA */
    for (i = 0; i < algo->pca; ++i)
    {
        biggest = -DBL_MAX;
        for (j = 0; j < cvlen; ++j)
        {
            /* printf("\n%3d %3d % f", i, j, mat[i][j]); */
            if (biggest < fabs(mat[algo->pca - 1 - i][j]))
                biggest = fabs(mat[algo->pca - 1 - i][j]);
        }
/*     } */
        biggest = 99.99 / biggest;

/*     for (i = 0; i < algo->pca; ++i) */
/*     { */
        /* rescale (for rasmol really) so that the largest eigenvector component
           is = 99.99, i.e. the largest value allowable in the b-value column
           of a PDB file */
       if (algo->atoms == 0)
       {
            m = 0;
            for (j = 0; j < cvlen; ++j)
            {
                /* skip inital PDBCds that may have been selected out */ /* DLT debug fix */
                while (/* strncmp(cdsA->cds[0]->resName[j], parray->cds[0]->resName[m], 3) != 0 || */
                       cdsA->cds[0]->chainID[j] != parray->cds[0]->chainID[m] ||
                       cdsA->cds[0]->resSeq[j] != parray->cds[0]->resSeq[m])
                {
                    ++m;

                    if (m >= pvlen)
                        break;
                }

                /* while they match, set the B-factor according to the given PC */
                while (/* strncmp(cdsA->cds[0]->resName[j], parray->cds[0]->resName[m], 3) == 0 && */
                       cdsA->cds[0]->chainID[j] == parray->cds[0]->chainID[m] &&
                       cdsA->cds[0]->resSeq[j] == parray->cds[0]->resSeq[m])
                {
                    tempFactor = mat[algo->pca - 1 - i][j] * biggest;
                    /* printf("\n%4d %4d % f", j, m, tempFactor); */
                    for (k = 0; k < parray->cnum; ++k)
                        parray->cds[k]->tempFactor[m] = tempFactor;

                    ++m;

                    if (m >= pvlen)
                        break;
                }

                if (m >= pvlen)
                    break;
            }
        }
        else
        {
            for (j = 0; j < cvlen; ++j)
            {
                tempFactor = mat[algo->pca - 1 - i][j] * biggest;

                for (k = 0; k < parray->cnum; ++k)
                    parray->cds[k]->tempFactor[j] = tempFactor;
            }
        }

        sprintf(pcafile_name, "%s_pc%d.pdb", outfile_root, i+1);

/*         strncpy(pcafile_name, outfile_root, strlen(outfile_root)); */
/*         pcafile_name[strlen(outfile_root)] = '\0'; */
/*         strncat(pcafile_name, "_pc", 4); */
/*         strncat(pcafile_name, itoa(i+1, &numstring[0], 10), 5); */
/*         strcat(pcafile_name, ".pdb"); */

        pdbfile = fopen(pcafile_name, "w");
        if (pdbfile ==NULL)
        {
            perror("\n  ERROR");
            fprintf(stderr,
                    "\n  ERROR99: could not open file '%s' for writing. \n", pcafile_name);
            PrintTheseusTag();
            exit(EXIT_FAILURE);
        }

        if (algo->cormat == 0)
            strncpy(covcor_str, "covariance", 10);

        fprintf(pdbfile, "REMARK ===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-=\n");
        fprintf(pdbfile, "REMARK + File made by Douglas Theobald's THESEUS program\n");
        fprintf(pdbfile, "REMARK + Multiple maximum likelihood superpositioning\n");
        fprintf(pdbfile, "REMARK + Principal component %3d of %s matrix in B-factor column\n", i+1, covcor_str);
        fprintf(pdbfile, "REMARK + All B-factors scaled by %12.3f\n", biggest);
        fprintf(pdbfile, "REMARK + dtheobald@brandeis.edu\n");
        fprintf(pdbfile, "REMARK =-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===\n");

        for (j = 0; j < parray->cnum; ++j)
        {
            fprintf(pdbfile, "MODEL %8d\n", j+1);
            PrintPDBCds(pdbfile, parray->cds[j]);
            fprintf(pdbfile, "ENDMDL\n");
        }
        fprintf(pdbfile, "END\n");

        fclose(pdbfile);
    }

    PCADestroy(cdsA);
}


/* Writes out PDB format files with the PC eigenvector in the coordinate field.
   Used by CNS/XPLOR in my morph script to incrementally add the PC to the
   median PDB model. */
void
WritePCAMorphFile(PDBCdsArray *parray, CdsArray *cdsA, const char *outfile_root)
{
    FILE           *pdbfile = NULL;
    char            pcafile_name[256];
    int             i, j, m, pcanum;
    double        **vecs = cdsA->pcamat;
    double         *vals = cdsA->pcavals;
    const int       cvlen = 3 * cdsA->vlen;
    const int       pvlen = parray->vlen;
    PDBCds         *pcacds = NULL;
    char            covcor_str[16] = "correlation";

    pcacds = PDBCdsInit();
    PDBCdsAlloc(pcacds, pvlen);
    PDBCdsCopyAll(pcacds, parray->cds[0]);

    memset(pcacds->x, 0, pvlen * sizeof(double));
    memset(pcacds->y, 0, pvlen * sizeof(double));
    memset(pcacds->z, 0, pvlen * sizeof(double));

    if (algo->pca > cdsA->cnum - 1)
        pcanum = algo->pca = cdsA->cnum - 1;
    else
        pcanum = algo->pca;

CalcFullCovMat(cdsA);

    /* Multiply each PCA by the sqrt of the corresponding eigenvalue.
       If correlation matrix was used, we need to get back into std deviation space,
       so multiply by the sqrt of the corresponding variance */
    if (algo->cormat)
    {
        for (i = 0; i < pcanum; ++i)
            for (j = 0; j < cvlen; ++j)
                /* vecs[i][j] *= sqrt(cdsA->FullCovMat[j][j] * vals[i]); */
                vecs[i][j] *= sqrt(cdsA->FullCovMat[j][j]);
    }
    else if (algo->cormat == 0)
    {
        for (i = 0; i < pcanum; ++i)
            for (j = 0; j < cvlen; ++j)
                vecs[i][j] *= sqrt(vals[i]);
    }

    for (i = 0; i < pcanum; ++i)
    {
        m = 0;
        for (j = 0; j < cvlen; j += 3)
        {
            /* skip inital PDBCds that may have been selected out */
            while (strncmp(cdsA->cds[0]->resName[j/3], parray->cds[0]->resName[m], 3) != 0 ||
                   cdsA->cds[0]->chainID[j/3] != parray->cds[0]->chainID[m] ||
                   cdsA->cds[0]->resSeq[j/3] != parray->cds[0]->resSeq[m])
            {
                ++m;
            }

            /* while they match */
            while (strncmp(cdsA->cds[0]->resName[j/3], parray->cds[0]->resName[m], 3) == 0 &&
                   cdsA->cds[0]->chainID[j/3] == parray->cds[0]->chainID[m] &&
                   cdsA->cds[0]->resSeq[j/3] == parray->cds[0]->resSeq[m])
            {
                pcacds->x[m] = vecs[pcanum - 1 - i][j+0];
                pcacds->y[m] = vecs[pcanum - 1 - i][j+1];
                pcacds->z[m] = vecs[pcanum - 1 - i][j+2];

                ++m;

                if (m >= pvlen)
                    break;
            }

            if (m >= pvlen)
                break;
        }

        sprintf(pcafile_name, "%s_pca%d_morph.pdb", outfile_root, i+1);

/*         strncpy(pcafile_name, outfile_root, strlen(outfile_root)); */
/*         pcafile_name[strlen(outfile_root)] = '\0'; */
/*         strncat(pcafile_name, "_pca", 4); */
/*         strncat(pcafile_name, itoa(i+1, &numstring[0], 10), 5); */
/*         strncat(pcafile_name, "_morph", 6); */
/*         strcat(pcafile_name, ".pdb"); */

        pdbfile = fopen(pcafile_name, "w");
        if (pdbfile == NULL)
        {
            perror("\n  ERROR");
            fprintf(stderr,
                    "\n  ERROR99: could not open file '%s' for writing. \n", pcafile_name);
            PrintTheseusTag();
            exit(EXIT_FAILURE);
        }

        if (algo->cormat == 0)
            strncpy(covcor_str, "covariance", 10);

        fprintf(pdbfile, "REMARK ===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-=\n");
        fprintf(pdbfile, "REMARK + File made by Douglas Theobald's THESEUS program \n");
        fprintf(pdbfile, "REMARK + Multiple maximum likelihood superpositioning \n");
        fprintf(pdbfile, "REMARK + Principal component #%d of %s matrix, one SD in cds fields \n", i+1, covcor_str);
        fprintf(pdbfile, "REMARK + dtheobald@brandeis.edu \n");
        fprintf(pdbfile, "REMARK =-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===\n");
        PrintPDBCds(pdbfile, pcacds);
        fprintf(pdbfile, "END\n");

        fclose(pdbfile);
    }

    PDBCdsDestroy(&pcacds);
    PCADestroy(cdsA);
}


void
WritePCAProjections(PDBCdsArray *parray, CdsArray *cdsA, const char *outfile_root)
{
    FILE           *pdbfile = NULL;
    char            pcafile_name[256];
    int             i, j, m, pcanum;
    double          c;
    double        **vecs = cdsA->pcamat;
    double         *vals = cdsA->pcavals;
    const int       cvlen = 3 * cdsA->vlen;
    const int       pvlen = parray->vlen;
    PDBCds         *pcacds = NULL;
    //char            numstring[5], tmpstring[5];

    pcacds = PDBCdsInit();
    PDBCdsAlloc(pcacds, pvlen);
    PDBCdsCopyAll(pcacds, parray->cds[0]);

    if (algo->pca > cdsA->cnum - 1)
        pcanum = algo->pca = cdsA->cnum - 1;
    else
        pcanum = algo->pca;

CalcFullCovMat(cdsA);

    /* Multiply each PCA by the sqrt of the corresponding eigenvalue.
       If correlation matrix was used, we need to get back into std deviation space,
       so multiply by the sqrt of the corresponding variance */
    if (algo->cormat)
    {
        for (i = 0; i < pcanum; ++i)
            for (j = 0; j < cvlen; ++j)
                vecs[i][j] *= sqrt(cdsA->FullCovMat[j][j] * vals[i]);
    }
    else if (algo->cormat == 0)
    {
        for (i = 0; i < pcanum; ++i)
            for (j = 0; j < cvlen; ++j)
                vecs[i][j] *= sqrt(vals[i]);
    }

/*     for (j = 1; j <= cvlen; j++) */
/*         printf("\n%f", vals[cvlen - j]); */

/*     for (j = 0; j < cvlen; j++) */
/*         printf("\n%f", vecs[cvlen-1][j]); */

    for (i = 0; i < pcanum; ++i)
    {
        for (c = -3.0; c <= 3.0; c += 0.2)
        {
            m = 0;
            for (j = 0; j < cvlen; j += 3)
            {
                /* skip inital PDBCds that may have been selected out */
                while (strncmp(cdsA->cds[0]->resName[j/3], parray->cds[0]->resName[m], 3) ||
                       cdsA->cds[0]->chainID[j/3] != parray->cds[0]->chainID[m] ||
                       cdsA->cds[0]->resSeq[j/3] != parray->cds[0]->resSeq[m])
                {
                    ++m;
                }

                /* while they match */
                while (strncmp(cdsA->cds[0]->resName[j/3], parray->cds[0]->resName[m], 3) == 0 &&
                       cdsA->cds[0]->chainID[j/3] == parray->cds[0]->chainID[m] &&
                       cdsA->cds[0]->resSeq[j/3] == parray->cds[0]->resSeq[m])
                {
                    pcacds->x[m] = parray->cds[cdsA->cnum/2]->x[m] +
                                      c * vecs[pcanum - 1 - i][j+0];
                    pcacds->y[m] = parray->cds[cdsA->cnum/2]->y[m] +
                                      c * vecs[pcanum - 1 - i][j+1];
                    pcacds->z[m] = parray->cds[cdsA->cnum/2]->z[m] +
                                      c * vecs[pcanum - 1 - i][j+2];

                    ++m;

                    if (m >= pvlen)
                        break;
                }

                if (m >= pvlen)
                    break;
            }

            sprintf(pcafile_name, "%s_pca%d_%+3.1f.pdb", outfile_root, i+1, c);

/*             strncpy(pcafile_name, outfile_root, strlen(outfile_root)); */
/*             pcafile_name[strlen(outfile_root)] = '\0'; */
/*             strncat(pcafile_name, "_pca", 4); */
/*             strncat(pcafile_name, itoa(i+1, &numstring[0], 10), 5); */
/*             sprintf(tmpstring, "_%+3.1f", c); */
/*             strncat(pcafile_name, tmpstring, 5); */
/*             strcat(pcafile_name, ".pdb"); */

            pdbfile = fopen(pcafile_name, "w");
            if (pdbfile == NULL)
            {
                perror("\n  ERROR");
                fprintf(stderr,
                        "\n  ERROR99: could not open file '%s' for writing. \n", pcafile_name);
                PrintTheseusTag();
                exit(EXIT_FAILURE);
            }

            fprintf(pdbfile, "REMARK ===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-=\n");
            fprintf(pdbfile, "REMARK + File made by Douglas Theobald's THESEUS program \n");
            fprintf(pdbfile, "REMARK + Multiple maximum likelihood superpositioning \n");
            fprintf(pdbfile, "REMARK + Principal component %d of correlation matrix in B-factor column \n", i+1);
            fprintf(pdbfile, "REMARK + dtheobald@brandeis.edu \n");
            fprintf(pdbfile, "REMARK =-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===-===\n");
            PrintPDBCds(pdbfile, pcacds);
            fprintf(pdbfile, "END\n");

            fclose(pdbfile);
        }
    }

    PDBCdsDestroy(&pcacds);
    PCADestroy(cdsA);
}