Get the RMS of the JointFragments pair frag

@param ca1 the array of all atoms of structure1
@param ca2 the array of all atoms of structure1
@param frag the JointFragments object that contains the list of identical positions
@return the rms
482533
public static double getRMS(Atom[] ca1, Atom[]ca2,JointFragments frag) throws StructureException {
		//      now svd ftmp and check if the rms is < X ...
		AlternativeAlignment ali = new AlternativeAlignment();
		ali.apairs_from_idxlst(frag);
		double rms = 999;

		int[] idx1 = ali.getIdx1();
		int[] idx2 = ali.getIdx2();

		Atom[] ca1subset = AlignUtils.getFragmentFromIdxList(ca1, idx1);

		Atom[] ca2subset = AlignUtils.getFragmentFromIdxList(ca2,idx2);

		ali.calculateSuperpositionByIdx(ca1,ca2);

		Matrix rot = ali.getRotationMatrix();
		Atom atom = ali.getShift();

		for (Atom a : ca2subset) {
			Calc.rotate(a, rot);
			Calc.shift(a, atom);
		}

		rms = Calc.rmsd(ca1subset,ca2subset);

		return rms;
	}
736730
private static double calculateExactMass(List<AbstractMolecule> molecules) throws CTKException, ChemistryException, BuilderMoleculeException {
    Double result = 0.0;
    for (AbstractMolecule molecule : molecules) {
        molecule = BuilderMolecule.mergeRgroups(molecule);
      result += Chemistry.getInstance().getManipulator().getMoleculeInfo(molecule).getExactMass();
    }
    return result;
  }
1213388
def vcas2mach(cas, h):
    
    tas = vcas2tas(cas, h)
    M   = vtas2mach(tas, h)
    return M
173418
private static double getEdgeFragmentCost(Node node, Arborescence<Node> arborescence,
                                              Map<Node, Map<Node, Fragment>> edgeToFragment) {

        Fragment fragment = getEdgeFragment(node, arborescence, edgeToFragment);
        if (fragment != null) return fragment.fragmentCost();

        return 0D;
    }
794862
public double getRmsd() {

		if (alignment == null)
			return -1.0;
		if (alignment.getScore(MultipleAlignmentScorer.RMSD) == null)
			return MultipleAlignmentScorer.getRMSD(alignment);

		return alignment.getScore(MultipleAlignmentScorer.RMSD);
	}
331440
public static final  void sortAfps(AFPChain afpChain, Atom[] ca1, Atom[] ca2)
	{


		List<AFP> afpSet = afpChain.getAfpSet();

		if ( debug)
			System.err.println("entering sortAfps");

		int pro1Len = ca1.length;
		int pro2Len = ca2.length;

		afpChain.setAfpIndex(      new int[pro1Len][pro2Len]); //the index of (i,j) pair in AFP list, otherwise -1
		afpChain.setAfpAftIndex(   new int[pro1Len][pro2Len]);  //the index of AFP (i,j*) nearest to (i,j), j*<j. if a AFP exits for (i,j), it equals to afpIndex
		afpChain.setAfpBefIndex(   new int[pro1Len][pro2Len]); //the index of AFP (i,j*) nearest to (i,j), j*>j. if a AFP exits for (i,j), it equals to afpIndex

		int[][] afpIndex       = afpChain.getAfpIndex();
		int[][] afpAftIndex    = afpChain.getAfpAftIndex();
		int[][] afpBefIndex    = afpChain.getAfpBefIndex();

		for(int i = 0; i < pro1Len; i ++)   {
			for(int j = 0; j < pro2Len; j ++)   {

				afpIndex[i][j] = afpAftIndex[i][j] = afpBefIndex[i][j] = -1;
			}
		}

		//index the AFP for easy extraction of compatible AFPs
		int afpNum = afpSet.size();

		int     b0 = 0;
		for(int a = 0; a < afpNum; a ++)    {
			if(a == afpNum - 1 || afpSet.get(a).getP1() != afpSet.get(a+1).getP1())   {
				int i = afpSet.get(a).getP1();
				for(int b = b0; b <= a; b ++)       {
					int j = afpSet.get(b).getP2();
					afpIndex[i][j]=b ;
					afpBefIndex[i][j]=b;
					afpAftIndex[i][j]=b;
					if(afpSet.get(b).getP1() != i)    {
						System.err.println(String.format("Warning: wrong afp index %d %d\n", i, afpSet.get(b).getP1()));
						return;
					}
				}
				for(int k = 1; k < pro2Len; k ++)   {
					if( afpBefIndex[i][k] == -1){
						afpBefIndex[i][k] = afpBefIndex[i][k-1];
					}
				}
				for(int k = pro2Len - 2; k >= 0; k --)      {
					if(afpAftIndex[i][k] == -1) {
						afpAftIndex[i][k] =  afpAftIndex[i][k+1];
					}
				}
				b0 = a + 1;
			}
		}

		if ( debug)
			System.err.println("done sortAfps");


	}
873883
private static double combineRmsd(int b1, int b2, AFPChain afpChain,Atom[] ca1,Atom[] ca2)
	{
		int     i;
		int     afpn = 0;

		int[] afpChainList =afpChain.getAfpChainList();

		int[] block2Afp = afpChain.getBlock2Afp();
		int[] blockSize = afpChain.getBlockSize();


		int[]   list = new int[blockSize[b1]+blockSize[b2]];
		for(i = block2Afp[b1]; i < block2Afp[b1] + blockSize[b1]; i ++) {
			list[afpn ++] = afpChainList[i];
		}
		for(i = block2Afp[b2]; i < block2Afp[b2] + blockSize[b2]; i ++) {
			list[afpn ++] = afpChainList[i];
		}
		double  rmsd = AFPChainer.calAfpRmsd(afpn, list,0, afpChain,ca1,ca2);

		afpChain.setBlock2Afp(block2Afp);
		afpChain.setBlockSize(blockSize);
		afpChain.setAfpChainList(afpChainList);

		return rmsd;
	}
787138
def zoom_in_frag(self, curr_frag):
        
        level = curr_frag[1]
        frag = curr_frag[0]
        output = []
        if level > 0:
            str_level = str(level)
            sub_low = self.spec_level[str_level]["fragments_dict"][frag][
                "sub_low_index"
            ]
            sub_high = self.spec_level[str_level]["fragments_dict"][frag][
                "sub_high_index"
            ]
            new_level = level - 1
            for i in range(sub_low, sub_high + 1):
                output.append((i, new_level))
        else:
            output.append(curr_frag)
        return output
214941
public static int find(
		MemorySegment[] segments1, int offset1, int numBytes1,
		MemorySegment[] segments2, int offset2, int numBytes2) {
		if (numBytes2 == 0) { // quick way 1.
			return offset1;
		}
		if (inFirstSegment(segments1, offset1, numBytes1) &&
			inFirstSegment(segments2, offset2, numBytes2)) {
			byte first = segments2[0].get(offset2);
			int end = numBytes1 - numBytes2 + offset1;
			for (int i = offset1; i <= end; i++) {
				// quick way 2: equal first byte.
				if (segments1[0].get(i) == first &&
					segments1[0].equalTo(segments2[0], i, offset2, numBytes2)) {
					return i;
				}
			}
			return -1;
		} else {
			return findInMultiSegments(segments1, offset1, numBytes1, segments2, offset2, numBytes2);
		}
	}
527663
private List<IAtomContainer> mergeAtomicIons(final List<IAtomContainer> frags) {
        final List<IAtomContainer> res = new ArrayList<>(frags.size());
        for (IAtomContainer frag : frags) {

            IChemObjectBuilder bldr = frag.getBuilder();

            if (frag.getBondCount() > 0 || res.isEmpty()) {
                res.add(bldr.newInstance(IAtomContainer.class, frag));
            } else {
                // try to find matching atomic ion
                int i = 0;
                while (i < res.size()) {
                    IAtom iAtm = frag.getAtom(0);
                    if (res.get(i).getBondCount() == 0) {
                        IAtom jAtm = res.get(i).getAtom(0);
                        if (nullAsZero(iAtm.getFormalCharge()) == nullAsZero(jAtm.getFormalCharge()) &&
                            nullAsZero(iAtm.getAtomicNumber()) == nullAsZero(jAtm.getAtomicNumber()) &&
                            nullAsZero(iAtm.getImplicitHydrogenCount()) == nullAsZero(jAtm.getImplicitHydrogenCount())) {
                            break;
                        }
                    }
                    i++;
                }

                if (i < res.size()) {
                    res.get(i).add(frag);
                } else {
                    res.add(bldr.newInstance(IAtomContainer.class, frag));
                }
            }
        }
        return res;
    }
36986
private static AFPChain partitionAFPchain(AFPChain afpChain,
			Atom[] ca1, Atom[] ca2, int order) throws StructureException{

		int[][][] newAlgn = new int[order][][];
		int repeatLen = afpChain.getOptLength()/order;

		//Extract all the residues considered in the first chain of the alignment
		List<Integer> alignedRes = new ArrayList<Integer>();
		for (int su=0; su<afpChain.getBlockNum(); su++){
			for (int i=0; i<afpChain.getOptLen()[su]; i++){
				alignedRes.add(afpChain.getOptAln()[su][0][i]);
			}
		}

		//Build the new alignment
		for (int su=0; su<order; su++){
			newAlgn[su] = new int[2][];
			newAlgn[su][0] = new  int[repeatLen];
			newAlgn[su][1] = new  int[repeatLen];
			for (int i=0; i<repeatLen; i++){
				newAlgn[su][0][i] = alignedRes.get(repeatLen*su+i);
				newAlgn[su][1][i] = alignedRes.get(
						(repeatLen*(su+1)+i)%alignedRes.size());
			}
		}

		return AlignmentTools.replaceOptAln(newAlgn, afpChain, ca1, ca2);
	}
1256863
public static IMolecularFormula getMaximalFormula(MolecularFormulaRange mfRange, IChemObjectBuilder builder) {
        IMolecularFormula formula = builder.newInstance(IMolecularFormula.class);

        for (IIsotope isotope : mfRange.isotopes()) {
            formula.addIsotope(isotope, mfRange.getIsotopeCountMax(isotope));
        }

        return formula;
    }
698634
public double displace(IAtomContainer ac, Vector overlappingAtoms, Vector overlappingBonds) {
        double bondLength = GeometryUtil.getBondLengthAverage(ac);

        OverlapPair op = null;
        IAtom a1 = null, a2 = null;
        Vector2d v1 = null, v2 = null;
        int steps = 0;
        int p = 0;
        double overlapScore = 0;
        double choice = 0;
        logger.debug("We are here because of an overlap situation.");
        //logger.debug("Overlap score: " + overlapScore);

        do {
            /*
             * we take a random overlapping pair of atoms
             */
            p = (int) (Math.random() * overlappingAtoms.size());
            logger.debug("Taking overlap pair no. " + p);
            op = (OverlapPair) overlappingAtoms.elementAt(p);
            /*
             * Now we have an overlapping pair of atoms We calculate the 2D
             * vector formed by the positions of both and translate one of the
             * atoms by one tenth of a bond length
             */
            a1 = (IAtom) op.chemObject1;
            a2 = (IAtom) op.chemObject2;
            v1 = new Vector2d(a1.getPoint2d());
            v2 = new Vector2d(a2.getPoint2d());
            v2.sub(v1);
            v2.normalize();

            if (Double.isNaN(v2.x)) v2.x = 0.01;
            if (Double.isNaN(v2.y)) v2.y = 0.01;

            v2.scale(bondLength / 20.0);
            logger.debug("Calculation translation vector " + v2);
            choice = Math.random();
            if (choice > 0.5) {
                a2.getPoint2d().add(v2);
                logger.debug("Random variable: " + choice + ", displacing first atom");
            } else {
                a1.getPoint2d().sub(v2);
                logger.debug("Random variable: " + choice + ", displacing second atom");
            }
            overlapScore = getOverlapScore(ac, overlappingAtoms, overlappingBonds);
            steps++;
        } while (overlapScore > 0 && !(steps > maxSteps));

        if (steps < 100) {
            logger.debug("Overlap situation resolved");
            logger.debug("Overlap score: " + overlapScore);
            logger.debug(steps + " steps needed to clear situation");
        } else {
            logger.debug("Could not resolve overlap situation");
            logger.debug("Number of " + steps + " steps taken exceeds limit of " + maxSteps);
            logger.debug("Overlap score: " + overlapScore);
        }
        return overlapScore;
    }
937689
def mass_tot(self, rho0, Ra, Rs):
        
        Ra, Rs = self._sort_ra_rs(Ra, Rs)
        sigma0 = self.rho2sigma(rho0, Ra, Rs)
        m_tot = 2 * np.pi * sigma0 * Ra * Rs
        return m_tot
1163746
def rms(signal, fs):
    
    # if a signal contains a some silence, taking the RMS of the whole
    # signal will be calculated as less loud as a signal without a silent
    # period. I don't like this, so I am going to chunk the signals, and
    # take the value of the most intense chunk
    chunk_time = 0.001  # 1 ms chunk
    chunk_samps = int(chunk_time * fs)
    amps = []
    if chunk_samps > 10:
        for i in range(0, len(signal) - chunk_samps, chunk_samps):
            amps.append(np.sqrt(np.mean(pow(signal[i:i + chunk_samps], 2))))
        amps.append(np.sqrt(np.mean(pow(signal[len(signal) - chunk_samps:], 2))))
        return np.amax(amps)
    else:
        # samplerate low, just rms the whole thing
        return np.sqrt(np.mean(pow(signal, 2)))
731707
public static Group[] prepareGroupsForDisplay(AFPChain afpChain, Atom[] ca1, Atom[] ca2) throws StructureException{


		if ( afpChain.getBlockRotationMatrix().length == 0 ) {
			// probably the alignment is too short!
			System.err.println("No rotation matrix found to rotate 2nd structure!");
			afpChain.setBlockRotationMatrix(new Matrix[]{Matrix.identity(3, 3)});
			afpChain.setBlockShiftVector(new Atom[]{new AtomImpl()});
		}

		// List of groups to be rotated according to the alignment
		Group[] twistedGroups = new Group[ ca2.length];

		//int blockNum = afpChain.getBlockNum();

		int i = -1;

		// List of groups from the structure not included in ca2 (e.g. ligands)
		// Will be rotated according to first block
		List<Group> hetatms2 = StructureTools.getUnalignedGroups(ca2);

		if (  (afpChain.getAlgorithmName().equals(FatCatRigid.algorithmName) ) || (afpChain.getAlgorithmName().equals(FatCatFlexible.algorithmName) ) ){

			for (Atom a: ca2){
				i++;
				twistedGroups[i]=a.getGroup();

			}

			twistedGroups = AFPTwister.twistOptimized(afpChain, ca1, ca2);

			//} else  if  (( blockNum == 1 ) || (afpChain.getAlgorithmName().equals(CeCPMain.algorithmName))) {
		} else {

			Matrix m   =  afpChain.getBlockRotationMatrix()[ 0];
			Atom shift =  afpChain.getBlockShiftVector()   [ 0 ];

			shiftCA2(afpChain, ca2, m,shift, twistedGroups);

		}

		if ( afpChain.getBlockNum() > 0){

			// Superimpose ligands relative to the first block
			if( hetatms2.size() > 0 ) {

				if ( afpChain.getBlockRotationMatrix().length > 0 ) {

					Matrix m1      = afpChain.getBlockRotationMatrix()[0];
					//m1.print(3,3);
					Atom   vector1 = afpChain.getBlockShiftVector()[0];
					//System.out.println("shift vector:" + vector1);

					for ( Group g : hetatms2){
						Calc.rotate(g, m1);
						Calc.shift(g,vector1);
					}
				}
			}
		}

		return twistedGroups;
	}
863227
def getSignificance(wk1, wk2, nout, ofac):
  
  expy = exp(-wk2)
  effm = 2.0*(nout)/ofac
  sig = effm*expy
  ind = (sig > 0.01).nonzero()
  sig[ind] = 1.0-(1.0-expy[ind])**effm
  return sig