Align without penalizing end-gaps. Return alignment and score

@param sim the similarity matrix
@param params the structure alignment parameters to be used
@return an Alignable
7187
public static Alignable align_NPE(Matrix sim,StrucAligParameters params){
		//System.out.println("align_NPE");

		float gapOpen = params.getGapOpen();
		float gapExtension = params.getGapExtension();

		int rows = sim.getRowDimension();
		int cols = sim.getColumnDimension();

		Alignable al = new StrCompAlignment(rows,cols);
		al.setGapExtCol(gapExtension);
		al.setGapExtRow(gapExtension);
		al.setGapOpenCol(gapOpen);
		al.setGapOpenRow(gapOpen);
		//System.out.println("size of aligmat: " + rows+1 + " " + cols+1);
		//AligMatEl[][] aligmat = new AligMatEl[rows+1][cols+1];
		AligMatEl[][] aligmat = al.getAligMat();

		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {

				int e=0;
				//if ( ( i < rows) &&
				//        ( j < cols)) {
					//TODO: the ALIGFACTOR calc should be hidden in Gotoh!!

				e = (int)Math.round(Gotoh.ALIGFACTOR * sim.get(i,j));
				//}
				//System.out.println(e);
				AligMatEl am = new AligMatEl();
				am.setValue(e);
				//am.setTrack(new IndexPair((short)-99,(short)-99));
				aligmat[i+1][j+1] = am;

			}
		}
		//al.setAligMat(aligmat);

		 new Gotoh(al);

		return al;
	}
702028
public void align(Atom[] ca1, Atom[] ca2, StrucAligParameters params)
			throws StructureException {

		reset();
		this.params = params;

		long timeStart = System.currentTimeMillis();

		// step 1 get all Diagonals of length X that are similar between both
		// structures
		logger.debug(" length atoms1:" + ca1.length);
		logger.debug(" length atoms2:" + ca2.length);

		logger.debug("step 1 - get fragments with similar intramolecular distances ");

		int k = params.getDiagonalDistance();
		int k2 = params.getDiagonalDistance2();
		int fragmentLength = params.getFragmentLength();

		if (ca1.length < (fragmentLength + 1)) {
			throw new StructureException("structure 1 too short (" + ca1.length
					+ "), can not align");
		}
		if (ca2.length < (fragmentLength + 1)) {
			throw new StructureException("structure 2 too short (" + ca2.length
					+ "), can not align");
		}
		int rows = ca1.length - fragmentLength + 1;
		int cols = ca2.length - fragmentLength + 1;
		distanceMatrix = new Matrix(rows, cols, 0.0);

		double[] dist1 = AlignUtils.getDiagonalAtK(ca1, k);

		double[] dist2 = AlignUtils.getDiagonalAtK(ca2, k);
		double[] dist3 = new double[0];
		double[] dist4 = new double[0];
		if (k2 > 0) {
			dist3 = AlignUtils.getDiagonalAtK(ca1, k2);
			dist4 = AlignUtils.getDiagonalAtK(ca2, k2);
		}

		double[][] utmp = new double[][] { { 0, 0, 1 } };
		Atom unitvector = new AtomImpl();
		unitvector.setCoords(utmp[0]);

		List<FragmentPair> fragments = new ArrayList<FragmentPair>();

		for (int i = 0; i < rows; i++) {

			Atom[] catmp1 = AlignUtils.getFragment(ca1, i, fragmentLength);
			Atom center1 = AlignUtils.getCenter(ca1, i, fragmentLength);

			for (int j = 0; j < cols; j++) {

				double rdd1 = AlignUtils.rms_dk_diag(dist1, dist2, i, j,
						fragmentLength, k);
				double rdd2 = 0;
				if (k2 > 0)
					rdd2 = AlignUtils.rms_dk_diag(dist3, dist4, i, j,
							fragmentLength, k2);
				double rdd = rdd1 + rdd2;
				distanceMatrix.set(i, j, rdd);

				if (rdd < params.getFragmentMiniDistance()) {
					FragmentPair f = new FragmentPair(fragmentLength, i, j);
					Atom[] catmp2 = AlignUtils.getFragment(ca2, j,
							fragmentLength);
					Atom center2 = AlignUtils.getCenter(ca2, j,
							fragmentLength);

					f.setCenter1(center1);
					f.setCenter2(center2);

					Matrix4d t = SuperPositions.superpose(
							Calc.atomsToPoints(catmp1),
							Calc.atomsToPoints(catmp2));

					Matrix rotmat = Matrices.getRotationJAMA(t);
					f.setRot(rotmat);

					Atom aunitv = (Atom) unitvector.clone();
					Calc.rotate(aunitv, rotmat);
					f.setUnitv(aunitv);

					boolean doNotAdd = false;
					if (params.reduceInitialFragments()) {
						doNotAdd = FragmentJoiner.reduceFragments(
								fragments, f, distanceMatrix);

					}
					if (doNotAdd)
						continue;

					fragments.add(f);
				}
			}
		}

		notifyFragmentListeners(fragments);

		FragmentPair[] fp = fragments
				.toArray(new FragmentPair[fragments.size()]);
		setFragmentPairs(fp);

		logger.debug(" got # fragment pairs: {}", fp.length);

		logger.debug("step 2 - join fragments");

		// step 2 combine them to possible models
		FragmentJoiner joiner = new FragmentJoiner();

		JointFragments[] frags;

		if (params.isJoinFast()) {
			// apply the quick alignment procedure.
			// less quality in alignments, better for DB searches...
			frags = joiner.approach_ap3(ca1, ca2, fp, params);

			joiner.extendFragments(ca1, ca2, frags, params);

		} else if (params.isJoinPlo()) {
			// this approach by StrComPy (peter lackner):
			frags = joiner.frag_pairwise_compat(fp, params.getAngleDiff(),
					params.getFragCompat(), params.getMaxrefine());

		} else {

			// my first implementation
			frags = joiner.approach_ap3(ca1, ca2, fp, params);
		}

		notifyJointFragments(frags);

		logger.debug(" number joint fragments: ", frags.length);

		logger.debug("step 3 - refine alignments");

		List<AlternativeAlignment> aas = new ArrayList<AlternativeAlignment>();
		for (int i = 0; i < frags.length; i++) {
			JointFragments f = frags[i];
			AlternativeAlignment a = new AlternativeAlignment();
			a.apairs_from_idxlst(f);
			a.setAltAligNumber(i + 1);
			a.setDistanceMatrix(distanceMatrix);

			try {
				if (params.getMaxIter() > 0) {

					a.refine(params, ca1, ca2);
				} else {

					a.finish(params, ca1, ca2);

				}
			} catch (StructureException e) {
				logger.error("Refinement of fragment {} failed", i, e);
			}
			a.calcScores(ca1, ca2);
			aas.add(a);
		}

		// sort the alternative alignments
		Comparator<AlternativeAlignment> comp = new AltAligComparator();
		Collections.sort(aas, comp);
		Collections.reverse(aas);

		alts = aas.toArray(new AlternativeAlignment[aas.size()]);
		// do final numbering of alternative solutions
		int aanbr = 0;
		for (AlternativeAlignment a : alts) {
			aanbr++;
			a.setAltAligNumber(aanbr);
		}

		logger.debug("total calculation time: {} ms.",
				(System.currentTimeMillis() - timeStart));
	}
1172372
public static List<Range<Long>> matches(final AlignmentPair alignmentPair) {
        checkNotNull(alignmentPair);
        List<Range<Long>> matches = new ArrayList<Range<Long>>();
        int matchStart = -1;
        for (int i = 1, length = alignmentPair.length() + 1; i < length; i++) {
            if (isMatchSymbol(alignmentPair.symbolAt(i))) {
                if (matchStart < 0) {
                    matchStart = i;
                }
            }
            else {
                if (matchStart > 0) {
                    // biojava coordinates are 1-based
                    matches.add(Range.closedOpen(Long.valueOf(matchStart - 1L), Long.valueOf(i - 1L)));
                    matchStart = -1;
                }
            }
        }
        if (matchStart > 0) {
            matches.add(Range.closedOpen(Long.valueOf(matchStart - 1L), Long.valueOf(alignmentPair.length())));
        }
        return matches;
    }
1138112
def _compile_params(params, im1):
    
    
    # Compile parameters
    p = _get_fixed_params(im1) + get_advanced_params()
    p = p + params
    params = p.as_dict()
    
    # Check parameter dimensions
    if isinstance(im1, np.ndarray):
        lt = (list, tuple)
        for key in [    'FinalGridSpacingInPhysicalUnits',
                        'FinalGridSpacingInVoxels' ]:
            if key in params.keys() and not isinstance(params[key], lt):
                params[key] = [params[key]] * im1.ndim
    
    # Check parameter removal
    if 'FinalGridSpacingInVoxels' in params:
        if 'FinalGridSpacingInPhysicalUnits' in params:
            params.pop('FinalGridSpacingInPhysicalUnits')
    
    # Done
    return params
1173531
def simxSetArrayParameter(clientID, paramIdentifier, paramValues, operationMode):
    '''
    
    '''

    c_paramValues = (ct.c_float*3)(*paramValues)
    return c_SetArrayParameter(clientID, paramIdentifier, c_paramValues, operationMode)
821498
public void align(Object... o) {
    int i = 0;
    String s[] = new String[o.length];

    for (int ii = 0; ii < o.length; ii++) { if (o[ii] != null) { s[ii] = o[ii].toString(); } }

    while (i < s.length && i < maxColumnLength.size()) {
      int l = (s[i] == null ? 0 : s[i].length());

      if (maxColumnLength.get(i) < l) {
        maxColumnLength.set(i, l);
      }

      i++;
    }

    while (i < s.length) {
      maxColumnLength.add((s[i] == null ? 0 : s[i].length()));
      i++;
    }

    rows.add(s);
  }
697952
def retrieve_with_score(self, s):
        
        all_sim = []
        use_max_n = self.max_n is not None
        for comparison_string in self._get_comparison_strings(s):
            score = self.comparison_func(s, comparison_string)
            if score >= self.cutoff:
                all_sim.append((comparison_string, score))
                if use_max_n and len(all_sim) >= self.max_n:
                    return all_sim
        return all_sim
4374
public static double[] computeSimilarityMatrix(DependenceMeasure sim, Relation<? extends NumberVector> rel) {
    final int dim = RelationUtil.dimensionality(rel);
    // TODO: we could use less memory (no copy), but this would likely be
    // slower. Maybe as a fallback option?
    double[][] data = new double[dim][rel.size()];
    int r = 0;
    for(DBIDIter it = rel.iterDBIDs(); it.valid(); it.advance(), r++) {
      NumberVector v = rel.get(it);
      for(int d = 0; d < dim; d++) {
        data[d][r] = v.doubleValue(d);
      }
    }
    return sim.dependence(DoubleArrayAdapter.STATIC, Arrays.asList(data));
  }
724707
private void align() {
		max = aligner.getPair().getLength();
		score = aligner.getPair().getNumIdenticals();
		aligner = null;
	}
826814
def create_alignment(self, x_align=0, y_align=0, x_scale=0, y_scale=0):
        
        align = Gtk.Alignment()
        align.set(x_align, y_align, x_scale, y_scale)
        return align
497468
public static void updateSymmetryScores(MultipleAlignment symm)
			throws StructureException {

		// Multiply by the order of symmetry to normalize score
		double tmScore = MultipleAlignmentScorer.getAvgTMScore(symm)
				* symm.size();
		double rmsd = MultipleAlignmentScorer.getRMSD(symm);

		symm.putScore(MultipleAlignmentScorer.AVGTM_SCORE, tmScore);
		symm.putScore(MultipleAlignmentScorer.RMSD, rmsd);
	}
916001
def simxSetSphericalJointMatrix(clientID, jointHandle, matrix, operationMode):
    '''
    
    '''
    matrix = (ct.c_float*12)(*matrix)
    return c_SetSphericalJointMatrix(clientID, jointHandle, matrix, operationMode)
1018656
public void align(Structure s1, String chainId1, Structure s2,
			String chainId2) throws StructureException {
		align(s1, chainId1, s2, chainId2, params);
	}
443330
def compute_expansion_alignment(satz_a, satz_b, satz_c, satz_d):
    """"""
    zeta_a = satz_a
    zeta_b = satz_b

    phi_a = compute_phi(zeta_a)
    phi_b = compute_phi(zeta_b)
    theta_a = compute_theta(zeta_a, phi_a)
    theta_b = compute_theta(zeta_b, phi_b)
    phi = (phi_a + phi_b) / 2
    zeta = compute_zeta(phi)
    theta = compute_theta(zeta, phi)

    c_expansion = 4 * (((theta_a + theta_b) / 2 - theta) / (theta_a - theta_b))

    sin_beta_2 = scan_width / (2 * H)

    d = ((R + H) / R * np.cos(phi) - np.cos(zeta)) * sin_beta_2
    e = np.cos(zeta) - np.sqrt(np.cos(zeta) ** 2 - d ** 2)

    c_alignment = 4 * e * np.sin(zeta) / (theta_a - theta_b)

    return c_expansion, c_alignment
408627
public void align() {

        Matrix tmp;

        // get center of gravity and translate both to 0,0,0
        this.cm1 = new Point3d();
        this.cm2 = new Point3d();

        this.cm1 = getCenterOfMass(p1, atwt1);
        this.cm2 = getCenterOfMass(p2, atwt2);

        // move the points
        for (int i = 0; i < this.npoint; i++) {
            p1[i].x = p1[i].x - this.cm1.x;
            p1[i].y = p1[i].y - this.cm1.y;
            p1[i].z = p1[i].z - this.cm1.z;

            p2[i].x = p2[i].x - this.cm2.x;
            p2[i].y = p2[i].y - this.cm2.y;
            p2[i].z = p2[i].z - this.cm2.z;
        }

        // get the R matrix
        double[][] tR = new double[3][3];
        for (int i = 0; i < this.npoint; i++) {
            wts[i] = 1.0;
        }
        for (int i = 0; i < this.npoint; i++) {
            tR[0][0] += p1[i].x * p2[i].x * wts[i];
            tR[0][1] += p1[i].x * p2[i].y * wts[i];
            tR[0][2] += p1[i].x * p2[i].z * wts[i];

            tR[1][0] += p1[i].y * p2[i].x * wts[i];
            tR[1][1] += p1[i].y * p2[i].y * wts[i];
            tR[1][2] += p1[i].y * p2[i].z * wts[i];

            tR[2][0] += p1[i].z * p2[i].x * wts[i];
            tR[2][1] += p1[i].z * p2[i].y * wts[i];
            tR[2][2] += p1[i].z * p2[i].z * wts[i];
        }
        double[][] R = new double[3][3];
        tmp = new Matrix(tR);
        R = tmp.transpose().getArray();

        // now get the RtR (=R'R) matrix
        double[][] RtR = new double[3][3];
        Matrix jamaR = new Matrix(R);
        tmp = tmp.times(jamaR);
        RtR = tmp.getArray();

        // get eigenvalues of RRt (a's)
        Matrix jamaRtR = new Matrix(RtR);
        EigenvalueDecomposition ed = jamaRtR.eig();
        double[] mu = ed.getRealEigenvalues();
        double[][] a = ed.getV().getArray();

        // Jama returns the eigenvalues in increasing order so
        // swap the eigenvalues and vectors
        double tmp2 = mu[2];
        mu[2] = mu[0];
        mu[0] = tmp2;
        for (int i = 0; i < 3; i++) {
            tmp2 = a[i][2];
            a[i][2] = a[i][0];
            a[i][0] = tmp2;
        }

        // make sure that the a3 = a1 x a2
        a[0][2] = (a[1][0] * a[2][1]) - (a[1][1] * a[2][0]);
        a[1][2] = (a[0][1] * a[2][0]) - (a[0][0] * a[2][1]);
        a[2][2] = (a[0][0] * a[1][1]) - (a[0][1] * a[1][0]);

        // lets work out the b vectors
        double[][] b = new double[3][3];
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                for (int k = 0; k < 3; k++) {
                    b[i][j] += R[i][k] * a[k][j];
                }
                b[i][j] = b[i][j] / Math.sqrt(mu[j]);
            }
        }

        // normalize and set b3 = b1 x b2
        double norm1 = 0.;
        double norm2 = 0.;
        for (int i = 0; i < 3; i++) {
            norm1 += b[i][0] * b[i][0];
            norm2 += b[i][1] * b[i][1];
        }
        norm1 = Math.sqrt(norm1);
        norm2 = Math.sqrt(norm2);
        for (int i = 0; i < 3; i++) {
            b[i][0] = b[i][0] / norm1;
            b[i][1] = b[i][1] / norm2;
        }
        b[0][2] = (b[1][0] * b[2][1]) - (b[1][1] * b[2][0]);
        b[1][2] = (b[0][1] * b[2][0]) - (b[0][0] * b[2][1]);
        b[2][2] = (b[0][0] * b[1][1]) - (b[0][1] * b[1][0]);

        // get the rotation matrix
        double[][] tU = new double[3][3];
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                for (int k = 0; k < 3; k++) {
                    tU[i][j] += b[i][k] * a[j][k];
                }
            }
        }

        // take the transpose
        U = new double[3][3];
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                U[i][j] = tU[j][i];
            }
        }

        // now eval the RMS error
        // first, rotate the second set of points and ...
        this.rp = new Point3d[this.npoint];
        for (int i = 0; i < this.npoint; i++) {
            this.rp[i] = new Point3d(U[0][0] * p2[i].x + U[0][1] * p2[i].y + U[0][2] * p2[i].z, U[1][0] * p2[i].x
                    + U[1][1] * p2[i].y + U[1][2] * p2[i].z, U[2][0] * p2[i].x + U[2][1] * p2[i].y + U[2][2] * p2[i].z);
        }

        // ... then eval rms
        double rms = 0.;
        for (int i = 0; i < this.npoint; i++) {
            rms += (p1[i].x - this.rp[i].x) * (p1[i].x - this.rp[i].x) + (p1[i].y - this.rp[i].y)
                    * (p1[i].y - this.rp[i].y) + (p1[i].z - this.rp[i].z) * (p1[i].z - this.rp[i].z);
        }
        this.rmsd = Math.sqrt(rms / this.npoint);
    }
898540
def align(s1, s2, gap=' ', eq=operator.eq):
    '''

    '''
    # first we compute the dynamic programming table
    m, n = len(s1), len(s2)
    table = []  # the table is extended lazily, one row at a time
    row = list(range(n+1))  # the first row is 0, 1, 2, ..., n
    table.append(list(row))  # copy row and insert into table
    for i in range(m):
        p = i
        row[0] = i+1
        for j in range(n):
            t = 0 if eq(s1[i], s2[j]) else 1
            p, row[j+1] = row[j+1], min(p+t, row[j]+1, row[j+1]+1)
        table.append(list(row))  # copy row and insert into table
    # now we trace the best alignment path from cell [m][n] to cell [0],[0]
    s1_, s2_ = '', ''

    i, j = m, n
    while i != 0 and j != 0:
        _, i, j, s1_, s2_ = min(
            (table[i-1][j-1], i-1, j-1, s1[i-1]+s1_, s2[j-1]+s2_),
            (table[i-1][j], i-1, j, s1[i-1]+s1_, gap+s2_),
            (table[i][j-1], i, j-1, gap+s1_, s2[j-1]+s2_)
        )
    if i != 0:
        s1_ = s1[:i]+s1_
        s2_ = gap*i+s2_
    if j != 0:
        s1_ = gap*j+s1_
        s2_ = s2[:j]+s2_
    return s1_, s2_
301622
public static boolean isMatch(Class<?> []paramA, Class<?> []paramB)
  {
    if (paramA.length != paramB.length)
      return false;
    
    for (int i = paramA.length - 1; i >= 0; i--) {
      if (! paramA[i].equals(paramB[i]))
        return false;
    }
    
    return true;
  }