001/*
002 *                    BioJava development code
003 *
004 * This code may be freely distributed and modified under the
005 * terms of the GNU Lesser General Public Licence.  This should
006 * be distributed with the code.  If you do not have a copy,
007 * see:
008 *
009 *      http://www.gnu.org/copyleft/lesser.html
010 *
011 * Copyright for this code is held jointly by the individual
012 * authors.  These should be listed in @author doc comments.
013 *
014 * For more information on the BioJava project and its aims,
015 * or to join the biojava-l mailing list, visit the home page
016 * at:
017 *
018 *      http://www.biojava.org/
019 *
020 */
021package org.biojava.nbio.structure.align.util;
022
023import org.biojava.nbio.structure.*;
024import org.biojava.nbio.structure.align.AFPTwister;
025import org.biojava.nbio.structure.align.ce.CECalculator;
026import org.biojava.nbio.structure.align.fatcat.FatCatFlexible;
027import org.biojava.nbio.structure.align.fatcat.FatCatRigid;
028import org.biojava.nbio.structure.align.model.AFPChain;
029import org.biojava.nbio.structure.align.xml.AFPChainXMLParser;
030import org.biojava.nbio.structure.geometry.Matrices;
031import org.biojava.nbio.structure.geometry.SuperPositions;
032import org.biojava.nbio.structure.jama.Matrix;
033import org.slf4j.Logger;
034import org.slf4j.LoggerFactory;
035
036import java.io.IOException;
037import java.io.Writer;
038import java.util.*;
039import java.util.Map.Entry;
040import java.util.regex.Matcher;
041import java.util.regex.Pattern;
042
043import javax.vecmath.Matrix4d;
044
045/**
046 * Methods for analyzing and manipulating AFPChains and for
047 * other pairwise alignment utilities. <p>
048 * Current methods: replace optimal alignment, create new AFPChain,
049 * format conversion, update superposition, etc.
050 *
051 * @author Spencer Bliven
052 * @author Aleix Lafita
053 *
054 */
055public class AlignmentTools {
056
057        private static final Logger logger = LoggerFactory.getLogger(AlignmentTools.class);
058
059
060        public static boolean debug = false;
061
062        /**
063         * Checks that the alignment given by afpChain is sequential. This means
064         * that the residue indices of both proteins increase monotonically as
065         * a function of the alignment position (ie both proteins are sorted).
066         *
067         * This will return false for circularly permuted alignments or other
068         * non-topological alignments. It will also return false for cases where
069         * the alignment itself is sequential but it is not stored in the afpChain
070         * in a sorted manner.
071         *
072         * Since algorithms which create non-sequential alignments split the
073         * alignment into multiple blocks, some computational time can be saved
074         * by only checking block boundaries for sequentiality. Setting
075         * <code>checkWithinBlocks</code> to <code>true</code> makes this function slower,
076         * but detects AFPChains with non-sequential blocks.
077         *
078         * Note that this method should give the same results as
079         * {@link AFPChain#isSequentialAlignment()}. However, the AFPChain version
080         * relies on the StructureAlignment algorithm correctly setting this
081         * parameter, which is sadly not always the case.
082         *
083         * @param afpChain An alignment
084         * @param checkWithinBlocks Indicates whether individual blocks should be
085         *      checked for sequentiality
086         * @return True if the alignment is sequential.
087         */
088        public static boolean isSequentialAlignment(AFPChain afpChain, boolean checkWithinBlocks) {
089                int[][][] optAln = afpChain.getOptAln();
090                int[] alnLen = afpChain.getOptLen();
091                int blocks = afpChain.getBlockNum();
092
093                if(blocks < 1) return true; //trivial case
094                if ( alnLen[0] < 1) return true;
095
096                // Check that blocks are sequential
097                if(checkWithinBlocks) {
098                        for(int block = 0; block<blocks; block++) {
099                                if(alnLen[block] < 1 ) continue; //skip empty blocks
100
101                                int prevRes1 = optAln[block][0][0];
102                                int prevRes2 = optAln[block][1][0];
103
104                                for(int pos = 1; pos<alnLen[block]; pos++) {
105                                        int currRes1 = optAln[block][0][pos];
106                                        int currRes2 = optAln[block][1][pos];
107
108                                        if(currRes1 < prevRes1) {
109                                                return false;
110                                        }
111                                        if(currRes2 < prevRes2) {
112                                                return false;
113                                        }
114
115                                        prevRes1 = currRes1;
116                                        prevRes2 = currRes2;
117                                }
118                        }
119                }
120
121                // Check that blocks are sequential
122                int prevRes1 = optAln[0][0][alnLen[0]-1];
123                int prevRes2 = optAln[0][1][alnLen[0]-1];
124
125                for(int block = 1; block<blocks;block++) {
126                        if(alnLen[block] < 1 ) continue; //skip empty blocks
127
128                        if(optAln[block][0][0]<prevRes1) {
129                                return false;
130                        }
131                        if(optAln[block][1][0]<prevRes2) {
132                                return false;
133                        }
134
135                        prevRes1 = optAln[block][0][alnLen[block]-1];
136                        prevRes2 = optAln[block][1][alnLen[block]-1];
137                }
138
139                return true;
140        }
141
142        /**
143         * Creates a Map specifying the alignment as a mapping between residue indices
144         * of protein 1 and residue indices of protein 2.
145         *
146         * <p>For example,<pre>
147         * 1234
148         * 5678</pre>
149         * becomes<pre>
150         * 1->5
151         * 2->6
152         * 3->7
153         * 4->8</pre>
154         *
155         * @param afpChain An alignment
156         * @return A mapping from aligned residues of protein 1 to their partners in protein 2.
157         * @throws StructureException If afpChain is not one-to-one
158         */
159        public static Map<Integer, Integer> alignmentAsMap(AFPChain afpChain) throws StructureException {
160                Map<Integer,Integer> map = new HashMap<>();
161
162                if( afpChain.getAlnLength() < 1 ) {
163                        return map;
164                }
165                int[][][] optAln = afpChain.getOptAln();
166                int[] optLen = afpChain.getOptLen();
167                for(int block = 0; block < afpChain.getBlockNum(); block++) {
168                        for(int pos = 0; pos < optLen[block]; pos++) {
169                                int res1 = optAln[block][0][pos];
170                                int res2 = optAln[block][1][pos];
171                                if(map.containsKey(res1)) {
172                                        throw new StructureException(String.format("Residue %d aligned to both %d and %d.", res1,map.get(res1),res2));
173                                }
174                                map.put(res1,res2);
175                        }
176                }
177                return map;
178        }
179
180        /**
181         * Applies an alignment k times. Eg if alignmentMap defines function f(x),
182         * this returns a function f^k(x)=f(f(...f(x)...)).
183         *
184         * @param <T>
185         * @param alignmentMap The input function, as a map (see {@link AlignmentTools#alignmentAsMap(AFPChain)})
186         * @param k The number of times to apply the alignment
187         * @return A new alignment. If the input function is not automorphic
188         *  (one-to-one), then some inputs may map to null, indicating that the
189         *  function is undefined for that input.
190         */
191        public static <T> Map<T,T> applyAlignment(Map<T, T> alignmentMap, int k) {
192                return applyAlignment(alignmentMap, new IdentityMap<T>(), k);
193        }
194
195        /**
196         * Applies an alignment k times. Eg if alignmentMap defines function f(x),
197         * this returns a function f^k(x)=f(f(...f(x)...)).
198         *
199         * To allow for functions with different domains and codomains, the identity
200         * function allows converting back in a reasonable way. For instance, if
201         * alignmentMap represented an alignment between two proteins with different
202         * numbering schemes, the identity function could calculate the offset
203         * between residue numbers, eg I(x) = x-offset.
204         *
205         * When an identity function is provided, the returned function calculates
206         * f^k(x) = f(I( f(I( ... f(x) ... )) )).
207         *
208         * @param <S>
209         * @param <T>
210         * @param alignmentMap The input function, as a map (see {@link AlignmentTools#alignmentAsMap(AFPChain)})
211         * @param identity An identity-like function providing the isomorphism between
212         *  the codomain of alignmentMap (of type T) and the domain (type S).
213         * @param k The number of times to apply the alignment
214         * @return A new alignment. If the input function is not automorphic
215         *  (one-to-one), then some inputs may map to null, indicating that the
216         *  function is undefined for that input.
217         */
218        public static <S,T> Map<S,T> applyAlignment(Map<S, T> alignmentMap, Map<T,S> identity, int k) {
219
220                // This implementation simply applies the map k times.
221                // If k were large, it would be more efficient to do this recursively,
222                // (eg f^4 = (f^2)^2) but k will usually be small.
223
224                if(k<0) throw new IllegalArgumentException("k must be positive");
225                if(k==1) {
226                        return new HashMap<>(alignmentMap);
227                }
228                // Convert to lists to establish a fixed order
229                List<S> preimage = new ArrayList<>(alignmentMap.keySet()); // currently unmodified
230                List<S> image = new ArrayList<>(preimage);
231
232                for(int n=1;n<k;n++) {
233                        // apply alignment
234                        for(int i=0;i<image.size();i++) {
235                                S pre = image.get(i);
236                                T intermediate = (pre==null?null: alignmentMap.get(pre));
237                                S post = (intermediate==null?null: identity.get(intermediate));
238                                image.set(i, post);
239                        }
240                }
241
242                Map<S, T> imageMap = new HashMap<>(alignmentMap.size());
243
244                //TODO handle nulls consistently.
245                // assure that all the residues in the domain are valid keys
246                /*
247                for(int i=0;i<preimage.size();i++) {
248                        S pre = preimage.get(i);
249                        T intermediate = (pre==null?null: alignmentMap.get(pre));
250                        S post = (intermediate==null?null: identity.get(intermediate));
251                        imageMap.put(post, null);
252                }
253                 */
254                // now populate with actual values
255                for(int i=0;i<preimage.size();i++) {
256                        S pre = preimage.get(i);
257
258                        // image is currently f^k-1(x), so take the final step
259                        S preK1 = image.get(i);
260                        T postK = (preK1==null?null: alignmentMap.get(preK1));
261                        imageMap.put(pre,postK);
262
263                }
264                return imageMap;
265        }
266
267        /**
268         * Helper for {@link #getSymmetryOrder(Map, Map, int, float)} with a true
269         * identity function (X->X).
270         *
271         * <p>This method should only be used in cases where the two proteins
272         * aligned have identical numbering, as for self-alignments. See
273         * {@link #getSymmetryOrder(AFPChain, int, float)} for a way to guess
274         * the sequential correspondence between two proteins.
275         *
276         * @param alignment
277         * @param maxSymmetry
278         * @param minimumMetricChange
279         * @return
280         */
281        public static int getSymmetryOrder(Map<Integer, Integer> alignment,
282                                                                           final int maxSymmetry, final float minimumMetricChange) {
283                return getSymmetryOrder(alignment, new IdentityMap<>(), maxSymmetry, minimumMetricChange);
284        }
285        /**
286         * Tries to detect symmetry in an alignment.
287         *
288         * <p>Conceptually, an alignment is a function f:A->B between two sets of
289         * integers. The function may have simple topology (meaning that if two
290         * elements of A are close, then their images in B will also be close), or
291         * may have more complex topology (such as a circular permutation). This
292         * function checks <i>alignment</i> against a reference function
293         * <i>identity</i>, which should have simple topology. It then tries to
294         * determine the symmetry order of <i>alignment</i> relative to
295         * <i>identity</i>, up to a maximum order of <i>maxSymmetry</i>.
296         *
297         *
298         * <p><strong>Details</strong><br/>
299         * Considers the offset (in number of residues) which a residue moves
300         * after undergoing <i>n</i> alternating transforms by alignment and
301         * identity. If <i>n</i> corresponds to the intrinsic order of the alignment,
302         * this will be small. This algorithm tries increasing values of <i>n</i>
303         * and looks for abrupt decreases in the root mean squared offset.
304         * If none are found at <i>n</i>&lt;=maxSymmetry, the alignment is reported as
305         * non-symmetric.
306         *
307         * @param alignment The alignment to test for symmetry
308         * @param identity An alignment with simple topology which approximates
309         *  the sequential relationship between the two proteins. Should map in the
310         *  reverse direction from alignment.
311         * @param maxSymmetry Maximum symmetry to consider. High values increase
312         *  the calculation time and can lead to overfitting.
313         * @param minimumMetricChange Percent decrease in root mean squared offsets
314         *  in order to declare symmetry. 0.4f seems to work well for CeSymm.
315         * @return The order of symmetry of alignment, or 1 if no order &lt;=
316         *  maxSymmetry is found.
317         *
318         * @see IdentityMap For a simple identity function
319         */
320        public static int getSymmetryOrder(Map<Integer, Integer> alignment, Map<Integer,Integer> identity,
321                                                                           final int maxSymmetry, final float minimumMetricChange) {
322                List<Integer> preimage = new ArrayList<>(alignment.keySet()); // currently unmodified
323                List<Integer> image = new ArrayList<>(preimage);
324
325                int bestSymmetry = 1;
326                double bestMetric = Double.POSITIVE_INFINITY; //lower is better
327                boolean foundSymmetry = false;
328
329                if(debug) {
330                        logger.trace("Symm\tPos\tDelta");
331                }
332
333                for(int n=1;n<=maxSymmetry;n++) {
334                        int deltasSq = 0;
335                        int numDeltas = 0;
336                        // apply alignment
337                        for(int i=0;i<image.size();i++) {
338                                Integer pre = image.get(i);
339                                Integer intermediate = (pre==null?null: alignment.get(pre));
340                                Integer post = (intermediate==null?null: identity.get(intermediate));
341                                image.set(i, post);
342
343                                if(post != null) {
344                                        int delta = post-preimage.get(i);
345
346                                        deltasSq += delta*delta;
347                                        numDeltas++;
348
349                                        if(debug) {
350                                                logger.debug("%d\t%d\t%d\n",n,preimage.get(i),delta);
351                                        }
352                                }
353
354                        }
355
356                        // Metrics: RMS compensates for the trend of smaller numDeltas with higher order
357                        // Not normalizing by numDeltas favors smaller orders
358
359                        double metric = Math.sqrt((double)deltasSq/numDeltas); // root mean squared distance
360
361                        if(!foundSymmetry && metric < bestMetric * minimumMetricChange) {
362                                // n = 1 is never the best symmetry
363                                if(bestMetric < Double.POSITIVE_INFINITY) {
364                                        foundSymmetry = true;
365                                }
366                                bestSymmetry = n;
367                                bestMetric = metric;
368                        }
369
370                        // When debugging need to loop over everything. Unneeded in production
371                        if(!debug && foundSymmetry) {
372                                break;
373                        }
374
375                }
376                if(foundSymmetry) {
377                        return bestSymmetry;
378                } else {
379                        return 1;
380                }
381        }
382
383
384        /**
385         * Guesses the order of symmetry in an alignment
386         *
387         * <p>Uses {@link #getSymmetryOrder(Map alignment, Map identity, int, float)}
388         * to determine the the symmetry order. For the identity alignment, sorts
389         * the aligned residues of each protein sequentially, then defines the ith
390         * residues of each protein to be equivalent.
391         *
392         * <p>Note that the selection of the identity alignment here is <i>very</i>
393         * naive, and only works for proteins with very good coverage. Wherever
394         * possible, it is better to construct an identity function explicitly
395         * from a sequence alignment (or use an {@link IdentityMap} for internally
396         * symmetric proteins) and use {@link #getSymmetryOrder(Map, Map, int, float)}.
397         */
398        public static int getSymmetryOrder(AFPChain afpChain, int maxSymmetry, float minimumMetricChange) throws StructureException {
399                // alignment comes from the afpChain alignment
400                Map<Integer,Integer> alignment = AlignmentTools.alignmentAsMap(afpChain);
401
402                // Now construct identity to map aligned residues in sequential order
403                Map<Integer, Integer> identity = guessSequentialAlignment(alignment, true);
404
405
406                return AlignmentTools.getSymmetryOrder(alignment,
407                                identity,
408                                maxSymmetry, minimumMetricChange);
409        }
410
411        /**
412         * Takes a potentially non-sequential alignment and guesses a sequential
413         * version of it. Residues from each structure are sorted sequentially and
414         * then compared directly.
415         *
416         * <p>The results of this method are consistent with what one might expect
417         * from an identity function, and are therefore useful with
418         * {@link #getSymmetryOrder(Map, Map identity, int, float)}.
419         * <ul>
420         *  <li>Perfect self-alignments will have the same pre-image and image,
421         *      so will map X->X</li>
422         *  <li>Gaps and alignment errors will cause errors in the resulting map,
423         *      but only locally. Errors do not propagate through the whole
424         *      alignment.</li>
425         * </ul>
426         *
427         * <h4>Example:</h4>
428         * A non sequential alignment, represented schematically as
429         * <pre>
430         * 12456789
431         * 78912345</pre>
432         * would result in a map
433         * <pre>
434         * 12456789
435         * 12345789</pre>
436         * @param alignment The non-sequential input alignment
437         * @param inverseAlignment If false, map from structure1 to structure2. If
438         *  true, generate the inverse of that map.
439         * @return A mapping from sequential residues of one protein to those of the other
440         * @throws IllegalArgumentException if the input alignment is not one-to-one.
441         */
442        public static Map<Integer, Integer> guessSequentialAlignment(
443                        Map<Integer,Integer> alignment, boolean inverseAlignment) {
444                Map<Integer,Integer> identity = new HashMap<>();
445
446                SortedSet<Integer> aligned1 = new TreeSet<>();
447                SortedSet<Integer> aligned2 = new TreeSet<>();
448
449                for(Entry<Integer,Integer> pair : alignment.entrySet()) {
450                        aligned1.add(pair.getKey());
451                        if( !aligned2.add(pair.getValue()) )
452                                throw new IllegalArgumentException("Alignment is not one-to-one for residue "+pair.getValue()+" of the second structure.");
453                }
454
455                Iterator<Integer> it1 = aligned1.iterator();
456                Iterator<Integer> it2 = aligned2.iterator();
457                while(it1.hasNext()) {
458                        if(inverseAlignment) { // 2->1
459                                identity.put(it2.next(),it1.next());
460                        } else { // 1->2
461                                identity.put(it1.next(),it2.next());
462                        }
463                }
464                return identity;
465        }
466
467        /**
468         * Retrieves the optimum alignment from an AFPChain and returns it as a
469         * java collection. The result is indexed in the same way as
470         * {@link AFPChain#getOptAln()}, but has the correct size().
471         * <pre>{@code
472         * List<List<List<Integer>>> aln = getOptAlnAsList(AFPChain afpChain);
473         * aln.get(blockNum).get(structureNum={0,1}).get(pos)
474         * }</pre>
475         *
476         * @param afpChain
477         * @return
478         */
479        public static List<List<List<Integer>>> getOptAlnAsList(AFPChain afpChain) {
480                int[][][] optAln = afpChain.getOptAln();
481                int[] optLen = afpChain.getOptLen();
482                List<List<List<Integer>>> blocks = new ArrayList<>(afpChain.getBlockNum());
483                for(int blockNum=0;blockNum<afpChain.getBlockNum();blockNum++) {
484                        //TODO could improve speed an memory by wrapping the arrays with
485                        // an unmodifiable list, similar to Arrays.asList(...) but with the
486                        // correct size parameter.
487                        List<Integer> align1 = new ArrayList<>(optLen[blockNum]);
488                        List<Integer> align2 = new ArrayList<>(optLen[blockNum]);
489                        for(int pos=0;pos<optLen[blockNum];pos++) {
490                                align1.add(optAln[blockNum][0][pos]);
491                                align2.add(optAln[blockNum][1][pos]);
492                        }
493                        List<List<Integer>> block = new ArrayList<>(2);
494                        block.add(align1);
495                        block.add(align2);
496                        blocks.add(block);
497                }
498
499                return blocks;
500        }
501
502
503
504        /**
505         * A {@code Map<K,V>} can be viewed as a function from K to V. This class represents
506         * the identity function. Getting a value results in the value itself.
507         *
508         * <p>The class is a bit inconsistent when representing its contents. On
509         * the one hand, containsKey(key) is true for all objects. However,
510         * attempting to iterate through the values returns an empty set.
511         *
512         * @author Spencer Bliven
513         *
514         * @param <K>
515         */
516        public static class IdentityMap<K> extends AbstractMap<K,K> {
517                public IdentityMap() {}
518
519                /**
520                 * @param key
521                 * @return the key
522                 * @throws ClassCastException if key is not of type K
523                 */
524                @SuppressWarnings("unchecked")
525                @Override
526                public K get(Object key) {
527                        return (K)key;
528                }
529
530                /**
531                 * Always returns the empty set
532                 */
533                @Override
534                public Set<java.util.Map.Entry<K, K>> entrySet() {
535                        return Collections.emptySet();
536                }
537
538                @Override
539                public boolean containsKey(Object key) {
540                        return true;
541                }
542        }
543
544        /**
545         * Fundamentally, an alignment is just a list of aligned residues in each
546         * protein. This method converts two lists of ResidueNumbers into an
547         * AFPChain.
548         *
549         * <p>Parameters are filled with defaults (often null) or sometimes
550         * calculated.
551         *
552         * <p>For a way to modify the alignment of an existing AFPChain, see
553         * {@link AlignmentTools#replaceOptAln(AFPChain, Atom[], Atom[], Map)}
554         * @param ca1 CA atoms of the first protein
555         * @param ca2 CA atoms of the second protein
556         * @param aligned1 A list of aligned residues from the first protein
557         * @param aligned2 A list of aligned residues from the second protein.
558         *  Must be the same length as aligned1.
559         * @return An AFPChain representing the alignment. Many properties may be
560         *  null or another default.
561         * @throws StructureException if an error occured during superposition
562         * @throws IllegalArgumentException if aligned1 and aligned2 have different
563         *  lengths
564         * @see AlignmentTools#replaceOptAln(AFPChain, Atom[], Atom[], Map)
565         */
566        public static AFPChain createAFPChain(Atom[] ca1, Atom[] ca2,
567                                                                                  ResidueNumber[] aligned1, ResidueNumber[] aligned2 ) throws StructureException {
568                //input validation
569                int alnLen = aligned1.length;
570                if(alnLen != aligned2.length) {
571                        throw new IllegalArgumentException("Alignment lengths are not equal");
572                }
573
574                AFPChain a = new AFPChain(AFPChain.UNKNOWN_ALGORITHM);
575                try {
576                        a.setName1(ca1[0].getGroup().getChain().getStructure().getName());
577                        if(ca2[0].getGroup().getChain().getStructure() != null) {
578                                // common case for cloned ca2
579                                a.setName2(ca2[0].getGroup().getChain().getStructure().getName());
580                        }
581                } catch(Exception e) {
582                        // One of the structures wasn't fully created. Ignore
583                }
584                a.setBlockNum(1);
585                a.setCa1Length(ca1.length);
586                a.setCa2Length(ca2.length);
587
588                a.setOptLength(alnLen);
589                a.setOptLen(new int[] {alnLen});
590
591
592                Matrix[] ms = new Matrix[a.getBlockNum()];
593                a.setBlockRotationMatrix(ms);
594                Atom[] blockShiftVector = new Atom[a.getBlockNum()];
595                a.setBlockShiftVector(blockShiftVector);
596
597                String[][][] pdbAln = new String[1][2][alnLen];
598                for(int i=0;i<alnLen;i++) {
599                        pdbAln[0][0][i] = aligned1[i].getChainName()+":"+aligned1[i];
600                        pdbAln[0][1][i] = aligned2[i].getChainName()+":"+aligned2[i];
601                }
602
603                a.setPdbAln(pdbAln);
604
605                // convert pdbAln to optAln, and fill in some other basic parameters
606                AFPChainXMLParser.rebuildAFPChain(a, ca1, ca2);
607
608                return a;
609
610                // Currently a single block. Split into several blocks by sequence if needed
611                //              return AlignmentTools.splitBlocksByTopology(a,ca1,ca2);
612        }
613
614        /**
615         *
616         * @param a
617         * @param ca1
618         * @param ca2
619         * @return
620         * @throws StructureException if an error occurred during superposition
621         */
622        public static AFPChain splitBlocksByTopology(AFPChain a, Atom[] ca1, Atom[] ca2) throws StructureException {
623                int[][][] optAln = a.getOptAln();
624                int blockNum = a.getBlockNum();
625                int[] optLen = a.getOptLen();
626
627                // Determine block lengths
628                // Split blocks if residue indices don't increase monotonically
629                List<Integer> newBlkLen = new ArrayList<>();
630                boolean blockChanged = false;
631                for(int blk=0;blk<blockNum;blk++) {
632                        int currLen=1;
633                        for(int pos=1;pos<optLen[blk];pos++) {
634                                if( optAln[blk][0][pos] <= optAln[blk][0][pos-1]
635                                                || optAln[blk][1][pos] <= optAln[blk][1][pos-1] )
636                                {
637                                        //start a new block
638                                        newBlkLen.add(currLen);
639                                        currLen = 0;
640                                        blockChanged = true;
641                                }
642                                currLen++;
643                        }
644                        if(optLen[blk] < 2 ) {
645                                newBlkLen.add(optLen[blk]);
646                        } else {
647                                newBlkLen.add(currLen);
648                        }
649                }
650
651                // Check if anything needs to be split
652                if( !blockChanged ) {
653                        return a;
654                }
655
656                // Split blocks
657                List<int[][]> blocks = new ArrayList<>( newBlkLen.size() );
658
659                int oldBlk = 0;
660                int pos = 0;
661                for(int blkLen : newBlkLen) {
662                        if( blkLen == optLen[oldBlk] ) {
663                                assert(pos == 0); //should be the whole block
664                                // Use the old block
665                                blocks.add(optAln[oldBlk]);
666                        } else {
667                                int[][] newBlock = new int[2][blkLen];
668                                assert( pos+blkLen <= optLen[oldBlk] ); // don't overrun block
669                                for(int i=0; i<blkLen;i++) {
670                                        newBlock[0][i] = optAln[oldBlk][0][pos + i];
671                                        newBlock[1][i] = optAln[oldBlk][1][pos + i];
672                                }
673                                pos += blkLen;
674                                blocks.add(newBlock);
675
676                                if( pos == optLen[oldBlk] ) {
677                                        // Finished this oldBlk, start the next
678                                        oldBlk++;
679                                        pos = 0;
680                                }
681                        }
682                }
683
684                // Store new blocks
685                int[][][] newOptAln = blocks.toArray(new int[0][][]);
686                int[] newBlockLens = new int[newBlkLen.size()];
687                for(int i=0;i<newBlkLen.size();i++) {
688                        newBlockLens[i] = newBlkLen.get(i);
689                }
690
691                return replaceOptAln(a, ca1, ca2, blocks.size(), newBlockLens, newOptAln);
692        }
693
694        /**
695         * It replaces an optimal alignment of an AFPChain and calculates all the new alignment scores and variables.
696         */
697        public static AFPChain replaceOptAln(int[][][] newAlgn, AFPChain afpChain, Atom[] ca1, Atom[] ca2) throws StructureException {
698
699                //The order is the number of groups in the newAlgn
700                int order = newAlgn.length;
701
702                //Calculate the alignment length from all the subunits lengths
703                int[] optLens = new int[order];
704                for(int s=0;s<order;s++) {
705                        optLens[s] = newAlgn[s][0].length;
706                }
707                int optLength = 0;
708                for(int s=0;s<order;s++) {
709                        optLength += optLens[s];
710                }
711
712                //Create a copy of the original AFPChain and set everything needed for the structure update
713                AFPChain copyAFP = (AFPChain) afpChain.clone();
714
715                //Set the new parameters of the optimal alignment
716                copyAFP.setOptLength(optLength);
717                copyAFP.setOptLen(optLens);
718                copyAFP.setOptAln(newAlgn);
719
720                //Set the block information of the new alignment
721                copyAFP.setBlockNum(order);
722                copyAFP.setBlockSize(optLens);
723                copyAFP.setBlockResList(newAlgn);
724                copyAFP.setBlockResSize(optLens);
725                copyAFP.setBlockGap(calculateBlockGap(newAlgn));
726
727                //Recalculate properties: superposition, tm-score, etc
728                Atom[] ca2clone = StructureTools.cloneAtomArray(ca2); // don't modify ca2 positions
729                AlignmentTools.updateSuperposition(copyAFP, ca1, ca2clone);
730
731                //It re-does the sequence alignment strings from the OptAlgn information only
732                copyAFP.setAlnsymb(null);
733                AFPAlignmentDisplay.getAlign(copyAFP, ca1, ca2clone);
734
735                return copyAFP;
736        }
737
738        /**
739         * Takes an AFPChain and replaces the optimal alignment based on an alignment map
740         *
741         * <p>Parameters are filled with defaults (often null) or sometimes
742         * calculated.
743         *
744         * <p>For a way to create a new AFPChain, see
745         * {@link AlignmentTools#createAFPChain(Atom[], Atom[], ResidueNumber[], ResidueNumber[])}
746         *
747         * @param afpChain The alignment to be modified
748         * @param alignment The new alignment, as a Map
749         * @throws StructureException if an error occurred during superposition
750         * @see AlignmentTools#createAFPChain(Atom[], Atom[], ResidueNumber[], ResidueNumber[])
751         */
752        public static AFPChain replaceOptAln(AFPChain afpChain, Atom[] ca1, Atom[] ca2,
753                                                                                 Map<Integer, Integer> alignment) throws StructureException {
754
755                // Determine block lengths
756                // Sort ca1 indices, then start a new block whenever ca2 indices aren't
757                // increasing monotonically.
758                Integer[] res1 = alignment.keySet().toArray(new Integer[0]);
759                Arrays.sort(res1);
760                List<Integer> blockLens = new ArrayList<>(2);
761                int optLength = 0;
762                Integer lastRes = alignment.get(res1[0]);
763                int blkLen = lastRes==null?0:1;
764                for(int i=1;i<res1.length;i++) {
765                        Integer currRes = alignment.get(res1[i]); //res2 index
766                        assert(currRes != null);// could be converted to if statement if assertion doesn't hold; just modify below as well.
767                        if(lastRes<currRes) {
768                                blkLen++;
769                        } else {
770                                // CP!
771                                blockLens.add(blkLen);
772                                optLength+=blkLen;
773                                blkLen = 1;
774                        }
775                        lastRes = currRes;
776                }
777                blockLens.add(blkLen);
778                optLength+=blkLen;
779
780                // Create array structure for alignment
781                int[][][] optAln = new int[blockLens.size()][][];
782                int pos1 = 0; //index into res1
783                for(int blk=0;blk<blockLens.size();blk++) {
784                        optAln[blk] = new int[2][];
785                        blkLen = blockLens.get(blk);
786                        optAln[blk][0] = new int[blkLen];
787                        optAln[blk][1] = new int[blkLen];
788                        int pos = 0; //index into optAln
789                        while(pos<blkLen) {
790                                optAln[blk][0][pos]=res1[pos1];
791                                Integer currRes = alignment.get(res1[pos1]);
792                                optAln[blk][1][pos]=currRes;
793                                pos++;
794                                pos1++;
795                        }
796                }
797                assert(pos1 == optLength);
798
799                // Create length array
800                int[] optLens = new int[blockLens.size()];
801                for(int i=0;i<blockLens.size();i++) {
802                        optLens[i] = blockLens.get(i);
803                }
804
805                return replaceOptAln(afpChain, ca1, ca2, blockLens.size(), optLens, optAln);
806        }
807
808        /**
809         * @param afpChain Input afpchain. UNMODIFIED
810         * @param ca1
811         * @param ca2
812         * @param optLens
813         * @param optAln
814         * @return A NEW AfpChain based off the input but with the optAln modified
815         * @throws StructureException if an error occured during superposition
816         */
817        public static AFPChain replaceOptAln(AFPChain afpChain, Atom[] ca1, Atom[] ca2,
818                                                                                 int blockNum, int[] optLens, int[][][] optAln) throws StructureException {
819                int optLength = 0;
820                for( int blk=0;blk<blockNum;blk++) {
821                        optLength += optLens[blk];
822                }
823
824                //set everything
825                AFPChain refinedAFP = (AFPChain) afpChain.clone();
826                refinedAFP.setOptLength(optLength);
827                refinedAFP.setBlockSize(optLens);
828                refinedAFP.setOptLen(optLens);
829                refinedAFP.setOptAln(optAln);
830                refinedAFP.setBlockNum(blockNum);
831
832                //TODO recalculate properties: superposition, tm-score, etc
833                Atom[] ca2clone = StructureTools.cloneAtomArray(ca2); // don't modify ca2 positions
834                AlignmentTools.updateSuperposition(refinedAFP, ca1, ca2clone);
835
836                AFPAlignmentDisplay.getAlign(refinedAFP, ca1, ca2clone);
837                return refinedAFP;
838        }
839
840
841        /**
842         * After the alignment changes (optAln, optLen, blockNum, at a minimum),
843         * many other properties which depend on the superposition will be invalid.
844         *
845         * This method re-runs a rigid superposition over the whole alignment
846         * and repopulates the required properties, including RMSD (TotalRMSD) and
847         * TM-Score.
848         * @param afpChain
849         * @param ca1
850         * @param ca2 Second set of ca atoms. Will be modified based on the superposition
851         * @throws StructureException
852         * @see CECalculator#calc_rmsd(Atom[], Atom[], int, boolean)
853         *  contains much of the same code, but stores results in a CECalculator
854         *  instance rather than an AFPChain
855         */
856        public static void updateSuperposition(AFPChain afpChain, Atom[] ca1,
857                        Atom[] ca2) throws StructureException {
858
859                //Update ca information, because the atom array might also be changed
860                afpChain.setCa1Length(ca1.length);
861                afpChain.setCa2Length(ca2.length);
862
863                //We need this to get the correct superposition
864                int[] focusRes1 = afpChain.getFocusRes1();
865                int[] focusRes2 = afpChain.getFocusRes2();
866                if (focusRes1 == null) {
867                        focusRes1 = new int[afpChain.getCa1Length()];
868                        afpChain.setFocusRes1(focusRes1);
869                }
870                if (focusRes2 == null) {
871                        focusRes2 = new int[afpChain.getCa2Length()];
872                        afpChain.setFocusRes2(focusRes2);
873                }
874
875                if (afpChain.getNrEQR() == 0) return;
876
877                // create new arrays for the subset of atoms in the alignment.
878                Atom[] ca1aligned = new Atom[afpChain.getOptLength()];
879                Atom[] ca2aligned = new Atom[afpChain.getOptLength()];
880
881                fillAlignedAtomArrays(afpChain, ca1, ca2, ca1aligned, ca2aligned);
882
883                //Superimpose the two structures in correspondance to the new alignment
884                Matrix4d trans = SuperPositions.superpose(Calc.atomsToPoints(ca1aligned),
885                                Calc.atomsToPoints(ca2aligned));
886
887                Matrix matrix = Matrices.getRotationJAMA(trans);
888                Atom shift = Calc.getTranslationVector(trans);
889
890                Matrix[] blockMxs = new Matrix[afpChain.getBlockNum()];
891                Arrays.fill(blockMxs, matrix);
892                afpChain.setBlockRotationMatrix(blockMxs);
893                Atom[] blockShifts = new Atom[afpChain.getBlockNum()];
894                Arrays.fill(blockShifts, shift);
895                afpChain.setBlockShiftVector(blockShifts);
896
897                for (Atom a : ca2aligned) {
898                        Calc.rotate(a, matrix);
899                        Calc.shift(a, shift);
900                }
901
902                //Calculate the RMSD and TM score for the new alignment
903                double rmsd = Calc.rmsd(ca1aligned, ca2aligned);
904                double tmScore = Calc.getTMScore(ca1aligned, ca2aligned, ca1.length, ca2.length);
905                afpChain.setTotalRmsdOpt(rmsd);
906                afpChain.setTMScore(tmScore);
907
908                int[] blockLens = afpChain.getOptLen();
909                int[][][] optAln = afpChain.getOptAln();
910
911                //Calculate the RMSD and TM score for every block of the new alignment
912                double[] blockRMSD = new double[afpChain.getBlockNum()];
913                double[] blockScore = new double[afpChain.getBlockNum()];
914                for (int k=0; k<afpChain.getBlockNum(); k++){
915                        //Create the atom arrays corresponding to the aligned residues in the block
916                        Atom[] ca1block = new Atom[afpChain.getOptLen()[k]];
917                        Atom[] ca2block = new Atom[afpChain.getOptLen()[k]];
918                        int position=0;
919                        for(int i=0;i<blockLens[k];i++) {
920                                int pos1 = optAln[k][0][i];
921                                int pos2 = optAln[k][1][i];
922                                Atom a1 = ca1[pos1];
923                                Atom a2 = (Atom) ca2[pos2].clone();
924                                ca1block[position] = a1;
925                                ca2block[position] = a2;
926                                position++;
927                        }
928                        if (position != afpChain.getOptLen()[k]){
929                                logger.warn("AFPChainScorer getTMScore: Problems reconstructing block alignment! nr of loaded atoms is " + position + " but should be " + afpChain.getOptLen()[k]);
930                                // we need to resize the array, because we allocated too many atoms earlier on.
931                                ca1block = (Atom[]) resizeArray(ca1block, position);
932                                ca2block = (Atom[]) resizeArray(ca2block, position);
933                        }
934                        //Superimpose the two block structures
935                        Matrix4d transb = SuperPositions.superpose(Calc.atomsToPoints(ca1block),
936                                        Calc.atomsToPoints(ca2block));
937
938                        blockMxs[k] = Matrices.getRotationJAMA(trans);
939                        blockShifts[k] = Calc.getTranslationVector(trans);
940
941                        Calc.transform(ca2block, transb);
942
943                        //Calculate the RMSD and TM score for the block
944                        double rmsdb = Calc.rmsd(ca1block, ca2block);
945                        double tmScoreb = Calc.getTMScore(ca1block, ca2block, ca1.length, ca2.length);
946                        blockRMSD[k] = rmsdb;
947                        blockScore[k] = tmScoreb;
948                }
949                afpChain.setOptRmsd(blockRMSD);
950                afpChain.setBlockRmsd(blockRMSD);
951                afpChain.setBlockScore(blockScore);
952        }
953
954        /**
955         * Reallocates an array with a new size, and copies the contents
956         * of the old array to the new array.
957         * @param oldArray  the old array, to be reallocated.
958         * @param newSize   the new array size.
959         * @return          A new array with the same contents.
960         */
961        public static Object resizeArray (Object oldArray, int newSize) {
962                int oldSize = java.lang.reflect.Array.getLength(oldArray);
963                @SuppressWarnings("rawtypes")
964                Class elementType = oldArray.getClass().getComponentType();
965                Object newArray = java.lang.reflect.Array.newInstance(
966                                elementType,newSize);
967                int preserveLength = Math.min(oldSize,newSize);
968                if (preserveLength > 0)
969                        System.arraycopy (oldArray,0,newArray,0,preserveLength);
970                return newArray;
971        }
972
973        /**
974         * Print an alignment map in a concise representation. Edges are given
975         * as two numbers separated by '>'. They are chained together where possible,
976         * or separated by spaces where disjoint or branched.
977         *
978         * <p>Note that more concise representations may be possible.</p>
979         *
980         * Examples:
981         * <ul>
982         * <li>1>2>3>1</li>
983         * <li>1>2>3>2 4>3</li>
984         * </ul>
985         * @param alignment The input function, as a map (see {@link AlignmentTools#alignmentAsMap(AFPChain)})
986         * @param identity An identity-like function providing the isomorphism between
987         *  the codomain of alignment (of type T) and the domain (type S).
988         * @return
989         */
990        public static <S,T> String toConciseAlignmentString(Map<S,T> alignment, Map<T,S> identity) {
991                // Clone input to prevent changes
992                Map<S,T> alig = new HashMap<>(alignment);
993
994                // Generate inverse alignment
995                Map<S,List<S>> inverse = new HashMap<>();
996                for(Entry<S,T> e: alig.entrySet()) {
997                        S val = identity.get(e.getValue());
998                        if( inverse.containsKey(val) ) {
999                                List<S> l = inverse.get(val);
1000                                l.add(e.getKey());
1001                        } else {
1002                                List<S> l = new ArrayList<>();
1003                                l.add(e.getKey());
1004                                inverse.put(val,l);
1005                        }
1006                }
1007
1008                StringBuilder str = new StringBuilder();
1009
1010                while(!alig.isEmpty()){
1011                        // Pick an edge and work upstream to a root or cycle
1012                        S seedNode = alig.keySet().iterator().next();
1013                        S node = seedNode;
1014                        if( inverse.containsKey(seedNode)) {
1015                                node = inverse.get(seedNode).iterator().next();
1016                                while( node != seedNode && inverse.containsKey(node)) {
1017                                        node = inverse.get(node).iterator().next();
1018                                }
1019                        }
1020
1021                        // Now work downstream, deleting edges as we go
1022                        seedNode = node;
1023                        str.append(node);
1024
1025                        while(alig.containsKey(node)) {
1026                                S lastNode = node;
1027                                node = identity.get( alig.get(lastNode) );
1028
1029                                // Output
1030                                str.append('>');
1031                                str.append(node);
1032
1033                                // Remove edge
1034                                alig.remove(lastNode);
1035                                List<S> inv = inverse.get(node);
1036                                if(inv.size() > 1) {
1037                                        inv.remove(node);
1038                                } else {
1039                                        inverse.remove(node);
1040                                }
1041                        }
1042                        if(!alig.isEmpty()) {
1043                                str.append(' ');
1044                        }
1045                }
1046
1047                return str.toString();
1048        }
1049
1050        /**
1051         * @see #toConciseAlignmentString(Map, Map)
1052         */
1053        public static <T> String toConciseAlignmentString(Map<T, T> alignment) {
1054                return toConciseAlignmentString(alignment, new IdentityMap<T>());
1055        }
1056
1057        /**
1058         * @see #toConciseAlignmentString(Map, Map)
1059         */
1060        public static Map<Integer, Integer> fromConciseAlignmentString(String string) {
1061                Map<Integer, Integer> map = new HashMap<>();
1062                boolean matches = true;
1063                while (matches) {
1064                        Pattern pattern = Pattern.compile("(\\d+)>(\\d+)");
1065                        Matcher matcher = pattern.matcher(string);
1066                        matches = matcher.find();
1067                        if (matches) {
1068                                Integer from = Integer.parseInt(matcher.group(1));
1069                                Integer to = Integer.parseInt(matcher.group(2));
1070                                map.put(from, to);
1071                                string = string.substring(matcher.end(1) + 1);
1072                        }
1073                }
1074                return map;
1075        }
1076
1077        /**
1078         * Method that calculates the number of gaps in each subunit block of an optimal AFP alignment.
1079         * @param optAln
1080         *                              an optimal alignment in the format int[][][]
1081         * @return an int[] array of order length containing the gaps in each block as int[block]
1082         */
1083        public static int[] calculateBlockGap(int[][][] optAln){
1084
1085                //Initialize the array to be returned
1086                int [] blockGap = new int[optAln.length];
1087
1088                //Loop for every block and look in both chains for non-contiguous residues.
1089                for (int i=0; i<optAln.length; i++){
1090                        int gaps = 0; //the number of gaps in that block
1091                        int last1 = 0; //the last residue position in chain 1
1092                        int last2 = 0; //the last residue position in chain 2
1093                        //Loop for every position in the block
1094                        for (int j=0; j<optAln[i][0].length; j++){
1095                                //If the first position is evaluated initialize the last positions
1096                                if (j==0){
1097                                        last1 = optAln[i][0][j];
1098                                        last2 = optAln[i][1][j];
1099                                }
1100                                else{
1101                                        //If one of the positions or both are not contiguous increment the number of gaps
1102                                        if (optAln[i][0][j] > last1+1 || optAln[i][1][j] > last2+1){
1103                                                gaps++;
1104                                                last1 = optAln[i][0][j];
1105                                                last2 = optAln[i][1][j];
1106                                        }
1107                                        //Otherwise just set the last position to the current one
1108                                        else{
1109                                                last1 = optAln[i][0][j];
1110                                                last2 = optAln[i][1][j];
1111                                        }
1112                                }
1113                        }
1114                        blockGap[i] = gaps;
1115                }
1116                return blockGap;
1117        }
1118
1119        /**
1120         * Creates a simple interaction format (SIF) file for an alignment.
1121         *
1122         * The SIF file can be read by network software (eg Cytoscape) to analyze
1123         * alignments as graphs.
1124         *
1125         * This function creates a graph with residues as nodes and two types of edges:
1126         *   1. backbone edges, which connect adjacent residues in the aligned protein
1127         *   2. alignment edges, which connect aligned residues
1128         *
1129         * @param out Stream to write to
1130         * @param afpChain alignment to write
1131         * @param ca1 First protein, used to generate node names
1132         * @param ca2 Second protein, used to generate node names
1133         * @param backboneInteraction Two-letter string used to identify backbone edges
1134         * @param alignmentInteraction Two-letter string used to identify alignment edges
1135         * @throws IOException
1136         */
1137        public static void alignmentToSIF(Writer out,AFPChain afpChain,
1138                                                                          Atom[] ca1,Atom[] ca2, String backboneInteraction,
1139                                                                          String alignmentInteraction) throws IOException {
1140
1141                //out.write("Res1\tInteraction\tRes2\n");
1142                String name1 = afpChain.getName1();
1143                String name2 = afpChain.getName2();
1144                if(name1==null) name1=""; else name1+=":";
1145                if(name2==null) name2=""; else name2+=":";
1146
1147                // Print alignment edges
1148                int nblocks = afpChain.getBlockNum();
1149                int[] blockLen = afpChain.getOptLen();
1150                int[][][] optAlign = afpChain.getOptAln();
1151                for(int b=0;b<nblocks;b++) {
1152                        for(int r=0;r<blockLen[b];r++) {
1153                                int res1 = optAlign[b][0][r];
1154                                int res2 = optAlign[b][1][r];
1155
1156                                ResidueNumber rn1 = ca1[res1].getGroup().getResidueNumber();
1157                                ResidueNumber rn2 = ca2[res2].getGroup().getResidueNumber();
1158
1159                                String node1 = name1+rn1.getChainName()+rn1.toString();
1160                                String node2 = name2+rn2.getChainName()+rn2.toString();
1161
1162                                out.write(String.format("%s\t%s\t%s\n",node1, alignmentInteraction, node2));
1163                        }
1164                }
1165
1166                // Print first backbone edges
1167                ResidueNumber rn = ca1[0].getGroup().getResidueNumber();
1168                String last = name1+rn.getChainName()+rn.toString();
1169                for(int i=1;i<ca1.length;i++) {
1170                        rn = ca1[i].getGroup().getResidueNumber();
1171                        String curr = name1+rn.getChainName()+rn.toString();
1172                        out.write(String.format("%s\t%s\t%s\n",last, backboneInteraction, curr));
1173                        last = curr;
1174                }
1175
1176                // Print second backbone edges, if the proteins differ
1177                // Do some quick checks for whether the proteins differ
1178                // (Not perfect, but should detect major differences and CPs.)
1179                if(!name1.equals(name2) ||
1180                                ca1.length!=ca2.length ||
1181                                (ca1.length>0 && ca1[0].getGroup()!=null && ca2[0].getGroup()!=null &&
1182                                                !ca1[0].getGroup().getResidueNumber().equals(ca2[0].getGroup().getResidueNumber()) ) ) {
1183                        rn = ca2[0].getGroup().getResidueNumber();
1184                        last = name2+rn.getChainName()+rn.toString();
1185                        for(int i=1;i<ca2.length;i++) {
1186                                rn = ca2[i].getGroup().getResidueNumber();
1187                                String curr = name2+rn.getChainName()+rn.toString();
1188                                out.write(String.format("%s\t%s\t%s\n",last, backboneInteraction, curr));
1189                                last = curr;
1190                        }
1191                }
1192        }
1193
1194
1195
1196        /** get an artificial List of chains containing the Atoms and groups.
1197         * Does NOT rotate anything.
1198         * @param ca
1199         * @return a list of Chains that is built up from the Atoms in the ca array
1200         */
1201        public static final List<Chain> getAlignedModel(Atom[] ca){
1202
1203                List<Chain> model = new ArrayList<>();
1204                for ( Atom a: ca){
1205
1206                        Group g = a.getGroup();
1207                        Chain parentC = g.getChain();
1208
1209                        Chain newChain = null;
1210                        for ( Chain c :  model) {
1211                                if ( c.getId().equals(parentC.getId())){
1212                                        newChain = c;
1213                                        break;
1214                                }
1215                        }
1216                        if ( newChain == null){
1217
1218                                newChain = new ChainImpl();
1219
1220                                newChain.setId(parentC.getId());
1221
1222                                model.add(newChain);
1223                        }
1224
1225                        newChain.addGroup(g);
1226
1227                }
1228
1229                return model;
1230        }
1231
1232
1233        /** Get an artifical Structure containing both chains.
1234         * Does NOT rotate anything
1235         * @param ca1
1236         * @param ca2
1237         * @return a structure object containing two models, one for each set of Atoms.
1238         * @throws StructureException
1239         */
1240        public static final Structure getAlignedStructure(Atom[] ca1, Atom[] ca2) throws StructureException{
1241
1242                /* Previous implementation commented
1243
1244                Structure s = new StructureImpl();
1245
1246
1247                List<Chain>model1 = getAlignedModel(ca1);
1248                List<Chain>model2 = getAlignedModel(ca2);
1249                s.addModel(model1);
1250                s.addModel(model2);
1251
1252                return s;*/
1253
1254                Structure s = new StructureImpl();
1255
1256                List<Chain>model1 = getAlignedModel(ca1);
1257                s.addModel(model1);
1258                List<Chain> model2 = getAlignedModel(ca2);
1259                s.addModel(model2);
1260
1261                return s;
1262        }
1263
1264        /** Rotate the Atoms/Groups so they are aligned for the 3D visualisation
1265         *
1266         * @param afpChain
1267         * @param ca1
1268         * @param ca2
1269         * @return an array of Groups that are transformed for 3D display
1270         * @throws StructureException
1271         */
1272        public static Group[] prepareGroupsForDisplay(AFPChain afpChain, Atom[] ca1, Atom[] ca2) throws StructureException{
1273
1274
1275                if ( afpChain.getBlockRotationMatrix().length == 0 ) {
1276                        // probably the alignment is too short!
1277                        System.err.println("No rotation matrix found to rotate 2nd structure!");
1278                        afpChain.setBlockRotationMatrix(new Matrix[]{Matrix.identity(3, 3)});
1279                        afpChain.setBlockShiftVector(new Atom[]{new AtomImpl()});
1280                }
1281
1282                // List of groups to be rotated according to the alignment
1283                Group[] twistedGroups = new Group[ ca2.length];
1284
1285                //int blockNum = afpChain.getBlockNum();
1286
1287                int i = -1;
1288
1289                // List of groups from the structure not included in ca2 (e.g. ligands)
1290                // Will be rotated according to first block
1291                List<Group> hetatms2 = StructureTools.getUnalignedGroups(ca2);
1292
1293                if (  (afpChain.getAlgorithmName().equals(FatCatRigid.algorithmName) ) || (afpChain.getAlgorithmName().equals(FatCatFlexible.algorithmName) ) ){
1294
1295                        for (Atom a: ca2){
1296                                i++;
1297                                twistedGroups[i]=a.getGroup();
1298
1299                        }
1300
1301                        twistedGroups = AFPTwister.twistOptimized(afpChain, ca1, ca2);
1302
1303                        //} else  if  (( blockNum == 1 ) || (afpChain.getAlgorithmName().equals(CeCPMain.algorithmName))) {
1304                } else {
1305
1306                        Matrix m   =  afpChain.getBlockRotationMatrix()[ 0];
1307                        Atom shift =  afpChain.getBlockShiftVector()   [ 0 ];
1308
1309                        shiftCA2(afpChain, ca2, m,shift, twistedGroups);
1310
1311                }
1312
1313                if ( afpChain.getBlockNum() > 0){
1314
1315                        // Superimpose ligands relative to the first block
1316                        if( hetatms2.size() > 0 ) {
1317
1318                                if ( afpChain.getBlockRotationMatrix().length > 0 ) {
1319
1320                                        Matrix m1      = afpChain.getBlockRotationMatrix()[0];
1321                                        //m1.print(3,3);
1322                                        Atom   vector1 = afpChain.getBlockShiftVector()[0];
1323                                        //System.out.println("shift vector:" + vector1);
1324
1325                                        for ( Group g : hetatms2){
1326                                                Calc.rotate(g, m1);
1327                                                Calc.shift(g,vector1);
1328                                        }
1329                                }
1330                        }
1331                }
1332
1333                return twistedGroups;
1334        }
1335
1336        /** only shift CA positions.
1337         *
1338         */
1339        public static void shiftCA2(AFPChain afpChain, Atom[] ca2,  Matrix m, Atom shift, Group[] twistedGroups) {
1340
1341                int i = -1;
1342                for (Atom a: ca2){
1343                        i++;
1344                        Group g = a.getGroup();
1345
1346                        Calc.rotate(g,m);
1347                        Calc.shift(g, shift);
1348
1349                        if (g.hasAltLoc()){
1350                                for (Group alt: g.getAltLocs()){
1351                                        for (Atom alta : alt.getAtoms()){
1352                                                if ( g.getAtoms().contains(alta))
1353                                                        continue;
1354                                                Calc.rotate(alta,m);
1355                                                Calc.shift(alta,shift);
1356                                        }
1357                                }
1358                        }
1359                        twistedGroups[i]=g;
1360                }
1361        }
1362
1363        /**
1364         * Fill the aligned Atom arrays with the equivalent residues in the afpChain.
1365         * @param afpChain
1366         * @param ca1
1367         * @param ca2
1368         * @param ca1aligned
1369         * @param ca2aligned
1370         */
1371        public static void fillAlignedAtomArrays(AFPChain afpChain, Atom[] ca1,
1372                        Atom[] ca2, Atom[] ca1aligned, Atom[] ca2aligned) {
1373
1374                int pos=0;
1375                int[] blockLens = afpChain.getOptLen();
1376                int[][][] optAln = afpChain.getOptAln();
1377                assert(afpChain.getBlockNum() <= optAln.length);
1378
1379                for (int block=0; block < afpChain.getBlockNum(); block++) {
1380                        for(int i=0;i<blockLens[block];i++) {
1381                                int pos1 = optAln[block][0][i];
1382                                int pos2 = optAln[block][1][i];
1383                                Atom a1 = ca1[pos1];
1384                                Atom a2 = (Atom) ca2[pos2].clone();
1385                                ca1aligned[pos] = a1;
1386                                ca2aligned[pos] = a2;
1387                                pos++;
1388                        }
1389                }
1390
1391                // this can happen when we load an old XML serialization which did not support modern ChemComp representation of modified residues.
1392                if (pos != afpChain.getOptLength()){
1393                        logger.warn("AFPChainScorer getTMScore: Problems reconstructing alignment! nr of loaded atoms is " + pos + " but should be " + afpChain.getOptLength());
1394                        // we need to resize the array, because we allocated too many atoms earlier on.
1395                        ca1aligned = (Atom[]) resizeArray(ca1aligned, pos);
1396                        ca2aligned = (Atom[]) resizeArray(ca2aligned, pos);
1397                }
1398
1399        }
1400
1401        /**
1402         * Find the alignment position with the highest atomic distance between the
1403         * equivalent atomic positions of the arrays and remove it from the
1404         * alignment.
1405         *
1406         * @param afpChain
1407         *            original alignment, will be modified
1408         * @param ca1
1409         *            atom array, will not be modified
1410         * @param ca2
1411         *            atom array, will not be modified
1412         * @return the original alignment, with the alignment position at the
1413         *         highest distance removed
1414         * @throws StructureException
1415         */
1416        public static AFPChain deleteHighestDistanceColumn(AFPChain afpChain,
1417                        Atom[] ca1, Atom[] ca2) throws StructureException {
1418
1419                int[][][] optAln = afpChain.getOptAln();
1420
1421                int maxBlock = 0;
1422                int maxPos = 0;
1423                double maxDistance = Double.MIN_VALUE;
1424
1425                for (int b = 0; b < optAln.length; b++) {
1426                        for (int p = 0; p < optAln[b][0].length; p++) {
1427                                Atom ca2clone = ca2[optAln[b][1][p]];
1428                                Calc.rotate(ca2clone, afpChain.getBlockRotationMatrix()[b]);
1429                                Calc.shift(ca2clone, afpChain.getBlockShiftVector()[b]);
1430
1431                                double distance = Calc.getDistance(ca1[optAln[b][0][p]],
1432                                                ca2clone);
1433                                if (distance > maxDistance) {
1434                                        maxBlock = b;
1435                                        maxPos = p;
1436                                        maxDistance = distance;
1437                                }
1438                        }
1439                }
1440
1441                return deleteColumn(afpChain, ca1, ca2, maxBlock, maxPos);
1442        }
1443
1444        /**
1445         * Delete an alignment position from the original alignment object.
1446         *
1447         * @param afpChain
1448         *            original alignment, will be modified
1449         * @param ca1
1450         *            atom array, will not be modified
1451         * @param ca2
1452         *            atom array, will not be modified
1453         * @param block
1454         *            block of the alignment position
1455         * @param pos
1456         *            position index in the block
1457         * @return the original alignment, with the alignment position removed
1458         * @throws StructureException
1459         */
1460        public static AFPChain deleteColumn(AFPChain afpChain, Atom[] ca1,
1461                        Atom[] ca2, int block, int pos) throws StructureException {
1462
1463                // Check validity of the inputs
1464                if (afpChain.getBlockNum() <= block) {
1465                        throw new IndexOutOfBoundsException(String.format(
1466                                        "Block index requested (%d) is higher than the total number of AFPChain blocks (%d).",
1467                                        block, afpChain.getBlockNum()));
1468                }
1469                if (afpChain.getOptAln()[block][0].length <= pos) {
1470                        throw new IndexOutOfBoundsException(String.format(
1471                                        "Position index requested (%d) is higher than the total number of aligned position in the AFPChain block (%d).",
1472                                        block, afpChain.getBlockSize()[block]));
1473                }
1474
1475                int[][][] optAln = afpChain.getOptAln();
1476
1477                int[] newPos0 = new int[optAln[block][0].length - 1];
1478                int[] newPos1 = new int[optAln[block][1].length - 1];
1479
1480                int position = 0;
1481                for (int p = 0; p < optAln[block][0].length; p++) {
1482
1483                        if (p == pos)
1484                                continue;
1485
1486                        newPos0[position] = optAln[block][0][p];
1487                        newPos1[position] = optAln[block][1][p];
1488
1489                        position++;
1490                }
1491
1492                optAln[block][0] = newPos0;
1493                optAln[block][1] = newPos1;
1494
1495                return AlignmentTools.replaceOptAln(optAln, afpChain, ca1, ca2);
1496        }
1497}