org.biojava.nbio.structure.Atom Java Examples

The following examples show how to use org.biojava.nbio.structure.Atom. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RotationOrderDetector.java    From symmetry with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected static double[] getSuperpositionDistances(Atom[] ca, RotationAxis axis, double[] angles) throws StructureException {
	int steps = angles.length;

	double[] distances = new double[steps];
	if(steps < 1) return distances;

	Atom[] ca2 = StructureTools.cloneAtomArray(ca);

	// step 0
	if(angles[0] > 0) {
		axis.rotate(ca2, angles[0]);
	}
	distances[0] = superpositionDistance(ca, ca2);
	for (int step=1; step<steps;step++) {
		axis.rotate(ca2, angles[step]-angles[step-1]);
		distances[step] = superpositionDistance(ca, ca2);
	}

	return distances;
}
 
Example #2
Source File: TestShortLines.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testLINK() throws IOException {
	Structure s;
	PDBFileParser pdbPars = new PDBFileParser();
	FileParsingParameters params = pdbPars.getFileParsingParameters();
	params.setCreateAtomBonds(true);

	StringBuilder sb = new StringBuilder();
	sb.append("ATOM   2412  C21 2EG A   7       0.888  44.973  72.238  1.00 29.17           C \n");
	sb.append("ATOM   2413  C22 2EG B  19       0.888  44.973  72.238  1.00 29.17           C \n");
	//sb.append("LINK         C21 2EG A   7                 C22 2EG B  19     1555   1555  1.56 ");
	sb.append("LINK         C21 2EG A   7                 C22 2EG B  19\n");
	String shortLine = sb.toString();

	// Parse short
	try(InputStream is = new ByteArrayInputStream(shortLine.getBytes())) {
		s = pdbPars.parsePDBFile(is);
	}

	// Should be a bond present in the Atoms.
	Chain c = s.getChainByIndex(0, 0);
	Group g = c.getAtomGroups().get(0);
	Atom a = g.getAtom(0);
	assertEquals(1, a.getBonds().size());
}
 
Example #3
Source File: OptimalCECPMainTest.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Basic test that alignPermuted(..., 0) is equivalent to a normal CE alignment.
 *
 * Also checks that {@link AFPChain#equals(Object)} is working the way we expect.
 * @throws IOException
 * @throws StructureException
 */
@Test
public void testUnpermuted() throws IOException, StructureException {
	String name1, name2;

	//small case
	name1 = "d1qdmA1";
	name2 = "d1nklA_";

	Atom[] ca1 = cache.getAtoms(name1);
	Atom[] ca2 = cache.getAtoms(name2);

	// Calculate all alignments initially
	OptimalCECPMain cecp = new OptimalCECPMain();
	Atom[] ca2clone = cache.getAtoms(name2);
	AFPChain cp0 = cecp.alignPermuted(ca1, ca2clone, cecp.getParameters(), 0);

	CeMain ce = new CeMain();
	AFPChain nocp = ce.align(ca1,ca2);

	Assert.assertEquals(nocp, cp0);
}
 
Example #4
Source File: RotationOrderDetector.java    From symmetry with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns an array of {@link #superpositionDistance(Atom[], Atom[]) superposition distances} of rotations of {@code ca}.
 * The {@code n}th element in the array corresponds to a rotation by {@code degreesIncrement * n} degrees.
 */
public static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement) throws StructureException {
	final double angleIncr = Math.toRadians(degreesIncrement);
	final int steps = (int)floor(2*PI/angleIncr);

	double[] angles = new double[steps];
	double[] distances = new double[steps];

	Atom[] ca2 = StructureTools.cloneAtomArray(ca);
	double angle = 0;

	for (int step=0; step<steps;step++) {
		angles[step] = angle;
		double dist = superpositionDistance(ca, ca2);
		distances[step] = dist;
		// Rotate for next step
		axis.rotate(ca2, angleIncr);
		angle += angleIncr;
	}

	return new Pair<double[], double[]>(angles, distances);

}
 
Example #5
Source File: TestSequenceFunctionOrderDetector.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testGetSymmetryOrder() throws IOException, StructureException, RefinerFailedException {
	// List of alignments to try, along with proper symmetry
	Map<String,Integer> orderMap = new HashMap<String,Integer>();
	orderMap.put("1itb.A",3); // b-trefoil, C3
	orderMap.put("1tim.A",2); // tim-barrel, C8
	//orderMap.put("d1p9ha_",-1); // not rotational symmetry
	orderMap.put("3HKE.A",2); // very questionable alignment
	orderMap.put("d1jlya1",3); // a very nice trefoil

	AtomCache cache = new AtomCache();

	for(String name : orderMap.keySet()) {
		CESymmParameters params = new CESymmParameters();
		params.setRefineMethod(RefineMethod.NOT_REFINED);
		Atom[] ca1 = cache.getAtoms(name);

		CeSymmResult result = CeSymm.analyzeLevel(ca1, params);
		AFPChain afpChain = result.getSelfAlignment();

		int order = new SequenceFunctionOrderDetector().calculateOrder(afpChain, ca1);

		assertEquals("Wrong order for "+name,orderMap.get(name).intValue(), order);
	}
}
 
Example #6
Source File: BioJavaStructureAlignment.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public AFPChain align(Atom[] ca1, Atom[] ca2, Object params)
		throws StructureException {
	if ( ! (params instanceof StrucAligParameters)){
		throw new IllegalArgumentException("BioJava structure alignment requires a StrucAligParameters class for the arguments.");
	}
	this.params = (StrucAligParameters) params;

	AFPChain afpChain = new AFPChain(algorithmName);
	StructurePairAligner aligner = new StructurePairAligner();
	aligner.align(ca1,ca2,this.params);

	// copy the results over into the AFPChain...
	AlternativeAlignment[] aligs = aligner.getAlignments();
	if ( aligs.length > 0){

		AlternativeAlignment altAlig = aligs[0];
		// copy the results over!
		copyResults(afpChain,altAlig,ca1,ca2);


	}

	return afpChain;

}
 
Example #7
Source File: OptimalCECPMainTest.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Very basic test of {@link OptimalCECPMain#permuteOptAln(AFPChain, int)}
 *
 * It should do nothing on unpermuted alignments.
 * @throws NoSuchMethodException
 * @throws SecurityException
 * @throws StructureException
 * @throws IOException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
@Test
public void testPermuteOptAlnUnpermuted() throws SecurityException, NoSuchMethodException, StructureException, IOException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
	//test private member using reflection
	Method permuteOptAln = OptimalCECPMain.class.getDeclaredMethod(
			"permuteOptAln", AFPChain.class, int.class);
	permuteOptAln.setAccessible(true);

	String name1, name2;
	name1 = "d1qdmA1";
	name2 = "d1nklA_";

	CeCPMain ce = (CeCPMain) StructureAlignmentFactory.getAlgorithm(CeCPMain.algorithmName);
	CECPParameters param = (CECPParameters)ce.getParameters();
	param.setDuplicationHint(DuplicationHint.RIGHT);

	Atom[] ca1 = cache.getAtoms(name1);
	Atom[] ca2 = cache.getAtoms(name2);

	AFPChain afpChain = ce.align(ca1, ca2);
	AFPChain afpChain2 = (AFPChain) afpChain.clone();

	permuteOptAln.invoke(null, afpChain2, 0);

	Assert.assertEquals("Permuting by 0 changed the alignment!", afpChain, afpChain2);
}
 
Example #8
Source File: RotationOrderDetectorTest.java    From symmetry with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testTrySingleCuspFixedByAmp() throws IOException,
		StructureException {
	String name;
	RotationOrderDetector detector = new RotationOrderDetector(8,
			SINGLE_CUSP_FIXED_AMP);

	// Perform alignment to determine axis
	Atom[] ca1;
	AFPChain alignment;
	RotationAxis axis;
	double[] coefs, expectedHarmonics;

	name = "1MER.A";
	ca1 = StructureTools.getAtomCAArray(StructureTools.getStructure(name));
	alignment = CeSymm.analyze(ca1, params).getSelfAlignment();
	axis = new RotationAxis(alignment);

	coefs = detector.trySingleOrdersByAmp(ca1, axis);
	expectedHarmonics = new double[] { 0.1287134, 1.030371, -0.5324238,
			-0.4618442, -0.5114463, -0.4755183, -0.4395435, -0.3174656 };

	assertArrayEquals(name, expectedHarmonics, coefs, 1e-4);
}
 
Example #9
Source File: FileConvert.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Prints the connections in PDB style
 *
 * Rewritten since 5.0 to use {@link Bond}s
 * Will produce strictly one CONECT record per bond (won't group several bonds in one line)
 */
private String printPDBConnections(){

	StringBuilder str = new StringBuilder();

	for (Chain c:structure.getChains()) {
		for (Group g:c.getAtomGroups()) {
			for (Atom a:g.getAtoms()) {
				if (a.getBonds()!=null) {
					for (Bond b:a.getBonds()) {				//7890123456789012345678901234567890123456789012345678901234567890
						str.append(String.format("CONECT%5d%5d                                                                "+newline, b.getAtomA().getPDBserial(), b.getAtomB().getPDBserial()));
					}
				}
			}
		}
	}

	return str.toString();
}
 
Example #10
Source File: SymmetryCalc.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void run() {

	CESymmParameters params = parent.getParameters();

	try {

		Atom[] atoms = SymmetryTools.getRepresentativeAtoms(structure);

		CeSymmResult result = CeSymm.analyze(atoms, params);
		SymmetryDisplay.display(result);

	} catch (StructureException e) {
		logger.warn(e.getMessage());
	}
	parent.notifyCalcFinished();
}
 
Example #11
Source File: Grid.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Adds a set of atoms, subsequent call to {@link #getIndicesContacts()} or {@link #getAtomContacts()} will produce the interatomic contacts.
 * The bounds calculated elsewhere can be passed, or if null they are computed.
 * @param atoms
 * @param bounds
 */
public void addAtoms(Atom[] atoms, BoundingBox bounds) {
	this.iAtoms = Calc.atomsToPoints(atoms);
	this.iAtomObjects = atoms;

	if (bounds!=null) {
		this.ibounds = bounds;
	} else {
		this.ibounds = new BoundingBox(iAtoms);
	}

	this.jAtoms = null;
	this.jAtomObjects = null;
	this.jbounds = null;

	fillGrid();
}
 
Example #12
Source File: SubunitCluster.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @return A List of size {@link #size()} of Atom arrays of length
 *         {@link #length()} with the aligned Atoms for each Subunit in the
 *         cluster
 */
public List<Atom[]> getAlignedAtomsSubunits() {

	List<Atom[]> alignedAtoms = new ArrayList<>();

	// Loop through all subunits and add the aligned positions
	for (int s = 0; s < subunits.size(); s++)
		alignedAtoms.add(getAlignedAtomsSubunit(s));

	return alignedAtoms;
}
 
Example #13
Source File: MultipleAlignmentEnsembleImpl.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Copy constructor. This copies recursively all member variables, including
 * MultipleAlignments, Atom arrays and cached variables.
 *
 * @param e
 *            MultipleAlignmentEnsemble to copy.
 * @return MultipleAlignmentEnsemble identical copy of the input ensemble.
 */
public MultipleAlignmentEnsembleImpl(MultipleAlignmentEnsembleImpl e) {

	super(e); // Copy the scores
	algorithmName = e.algorithmName;
	version = e.version;
	ioTime = e.ioTime;
	calculationTime = e.calculationTime;

	distanceMatrix = null;
	if (e.distanceMatrix != null) {
		// Make a deep copy of everything
		distanceMatrix = new ArrayList<Matrix>();
		for (Matrix mat : e.distanceMatrix) {
			distanceMatrix.add((Matrix) mat.clone());
		}
	}

	multipleAlignments = null;
	if (e.multipleAlignments != null) {
		// Make a deep copy of everything
		multipleAlignments = new ArrayList<MultipleAlignment>();
		for (MultipleAlignment msa : e.multipleAlignments) {
			MultipleAlignment newMSA = msa.clone();
			newMSA.setEnsemble(this);
			multipleAlignments.add(newMSA);
		}
	}

	if (e.atomArrays != null) {
		atomArrays = new ArrayList<Atom[]>(e.atomArrays);
	}
	if (e.structureIdentifiers != null) {
		structureIdentifiers = new ArrayList<StructureIdentifier>(
				e.structureIdentifiers);
	}
}
 
Example #14
Source File: CECalculator.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void nextStep( AFPChain afpChain,
		Atom[] ca1, Atom[] ca2) throws StructureException{


	if(nBestTrace>0) {
		checkBestTraces(afpChain,ca1,ca2);
	} else {
		noBestTrace();
	}

	convertAfpChain(afpChain, ca1, ca2);
	AFPAlignmentDisplay.getAlign(afpChain, ca1, ca2);
	double tmScore = AFPChainScorer.getTMScore(afpChain, ca1, ca2,false);
	afpChain.setTMScore(tmScore);
}
 
Example #15
Source File: MultipleAlignmentScorer.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Calculates the average RMSD from all structures to a reference s
 * tructure, given a set of superimposed atoms.
 * <p>
 * Complexity: T(n,l) = O(l*n), if n=number of structures and l=alignment
 * length.
 * <p>
 * For ungapped alignments, this is just the sqroot of the average distance
 * from an atom to the aligned atom from the reference. Thus, for R
 * structures aligned over C columns (with structure 0 as the reference), we
 * have:
 *
 * <pre>
 * RefRMSD = \sqrt{ 1/(C*(R-1)) * \sum_{r=1}^{R-1} \sum_{j=0}^{C-1}
 * (atom[1][c]-atom[r][c])^2 }
 * </pre>
 * <p>
 * For gapped alignments, null atoms are omitted from consideration, so that
 * the RMSD is the average over all columns with non-null reference of the
 * average RMSD within the non-null elements of the column.
 *
 * @param transformed
 * @param reference
 * @return
 */
public static double getRefRMSD(List<Atom[]> transformed, int reference) {

	double sumSqDist = 0;
	int totalLength = 0;
	for (int c = 0; c < transformed.get(reference).length; c++) {
		Atom refAtom = transformed.get(reference)[c];
		if (refAtom == null)
			continue;

		double nonNullSqDist = 0;
		int nonNullLength = 0;
		for (int r = 0; r < transformed.size(); r++) {
			if (r == reference)
				continue;
			Atom atom = transformed.get(r)[c];
			if (atom != null) {
				nonNullSqDist += Calc.getDistanceFast(refAtom, atom);
				nonNullLength++;
			}
		}

		if (nonNullLength > 0) {
			totalLength++;
			sumSqDist += nonNullSqDist / nonNullLength;
		}
	}
	return Math.sqrt(sumSqDist / totalLength);
}
 
Example #16
Source File: CeMain.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public AFPChain align(Atom[] ca1, Atom[] ca2) throws StructureException {

	if (params == null)
		params = new CeParameters();

	return align(ca1,ca2,params);
}
 
Example #17
Source File: TestSubunitCluster.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testMergeIdenticalByEntityId() {

	// Create 2 Atom Arrays, with same entity id
	Structure structure = mockStructure();
	Atom[] reprAtoms1 = getAtomArray(structure.getChain("A"));
	Atom[] reprAtoms2 = getAtomArray(structure.getChain("B"));

	// Create two SubunitCluster with same entity id
	SubunitCluster sc1 = new SubunitCluster(new Subunit(reprAtoms1,
			"A", null, structure));
	SubunitCluster sc2 = new SubunitCluster(new Subunit(reprAtoms2,
			"B", null, structure));

	boolean merged = sc1.mergeIdenticalByEntityId(sc2);

	// Merged have to be true, and the merged SubunitCluster is sc1
	assertTrue(merged);
	assertEquals(2, sc1.size());
	assertEquals(1, sc2.size());
	assertEquals(9, sc1.length());

	// Create an Atom Array of poly-glycine with a different entity id
	Atom[] reprAtoms3 = getAtomArray(structure.getChain("C"));

	SubunitCluster sc3 = new SubunitCluster(new Subunit(reprAtoms3,
			"C", null, structure));

	merged = sc1.mergeIdenticalByEntityId(sc3);

	// Merged have to be false, and Clusters result unmodified
	assertFalse(merged);
	assertEquals(2, sc1.size());
	assertEquals(1, sc2.size());
	assertEquals(9, sc1.length());

}
 
Example #18
Source File: AngleOrderDetectorPlus.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public int calculateOrder(AFPChain afpChain, Atom[] ca)
		throws RefinerFailedException {
	final double tol = 1e-6; // tolerance to floating point errors
	try {
		RotationAxis axis = new RotationAxis(afpChain);
		double theta = axis.getAngle();

		double bestDelta = error;
		int bestOrder = 1;
		for (int order = 1; order <= maxOrder; order++) {
			// Triangle wave starting at 0 with period 2pi/order
			double delta = abs(abs(theta * order / (2 * PI) - .5) % 1.0 - .5);
			// Triangle waves have amplitude 1, so need to un-normalize
			if (!normalizeError)
				delta *= 2 * PI / order;

			if (delta < bestDelta - tol) {
				bestOrder = order;
				bestDelta = delta;
			}
		}
		return bestOrder;
	} catch (Exception e) {
		throw new RefinerFailedException(e);
	}
}
 
Example #19
Source File: DisplayAFP.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void showAlignmentPanel(AFPChain afpChain, Atom[] ca1, Atom[] ca2, AbstractAlignmentJmol jmol) throws StructureException {

		AligPanel me = new AligPanel();
		me.setAlignmentJmol(jmol);
		me.setAFPChain(afpChain);
		me.setCa1(ca1);
		me.setCa2(ca2);

		JFrame frame = new JFrame();

		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setTitle(afpChain.getName1() + " vs. " + afpChain.getName2() + " | " + afpChain.getAlgorithmName() + " V. " + afpChain.getVersion());
		me.setPreferredSize(new Dimension(me.getCoordManager().getPreferredWidth() , me.getCoordManager().getPreferredHeight()));

		JMenuBar menu = MenuCreator.getAlignmentPanelMenu(frame,me,afpChain,null);
		frame.setJMenuBar(menu);

		JScrollPane scroll = new JScrollPane(me);
		scroll.setAutoscrolls(true);

		StatusDisplay status = new StatusDisplay();
		status.setAfpChain(afpChain);
		status.setCa1(ca1);
		status.setCa2(ca2);
		me.addAlignmentPositionListener(status);

		Box vBox = Box.createVerticalBox();
		vBox.add(scroll);
		vBox.add(status);

		frame.getContentPane().add(vBox);

		frame.pack();
		frame.setVisible(true);
		// make sure they get cleaned up correctly:
		frame.addWindowListener(me);
		frame.addWindowListener(status);
	}
 
Example #20
Source File: TestMultipleAlignmentScorer.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Generates an identity MultipleAlignment: 3 structures with
 * the same Atoms and perfectly aligned, so that TM-score = 1
 * and RMSD = 0.
 * @return MultipleAlignment identity
 * @throws StructureException
 */
private MultipleAlignment identityMSTA() throws StructureException {

	//Generate the identical Atom arrays
	List<Atom[]> atomArrays = new ArrayList<Atom[]>(20);
	for (int i=0; i<3; i++) atomArrays.add(makeDummyCA(20));

	//Generate the identity alignment (1-1-1,2-2-2,etc)
	List<List<Integer>> alnRes = new ArrayList<List<Integer>>(3);
	for (int str=0; str<3; str++){
		List<Integer> chain = new ArrayList<Integer>(20);
		for (int res=0; res<20; res++) chain.add(res);
		alnRes.add(chain);
	}

	//MultipleAlignment generation
	MultipleAlignment msa = new MultipleAlignmentImpl();
	msa.getEnsemble().setAtomArrays(atomArrays);
	BlockSet bs = new BlockSetImpl(msa);
	Block b = new BlockImpl(bs);
	b.setAlignRes(alnRes);

	//Superimpose the alignment (which should give the identity matrices)
	ReferenceSuperimposer imposer = new ReferenceSuperimposer();
	imposer.superimpose(msa);

	return msa;
}
 
Example #21
Source File: FragmentJoiner.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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
 */
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;
}
 
Example #22
Source File: MultipleAlignmentJmol.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void printJmolScript4Block(Atom[] atoms,
		List<List<Integer>> alignRes, Color blockColor, StringWriter jmol,
		int str, int colorPos, int blockNum) {

	// Obtain the residues aligned in this block of the structure
	List<String> pdb = new ArrayList<String>();
	for (int i = 0; i < alignRes.get(str).size(); i++) {

		// Handle gaps - only color if it is not null
		if (alignRes.get(str).get(i) != null) {
			int pos = alignRes.get(str).get(i);
			pdb.add(JmolTools.getPdbInfo(atoms[pos]));
		}
	}

	// Select the aligned residues
	StringBuffer buf = new StringBuffer("select ");
	int count = 0;
	for (String res : pdb) {
		if (count > 0)
			buf.append(",");
		buf.append(res);
		buf.append("/" + (str + 1));
		count++;
	}

	buf.append("; backbone 0.3 ; color [" + blockColor.getRed() + ","
			+ blockColor.getGreen() + "," + blockColor.getBlue() + "]; ");

	jmol.append(buf);
}
 
Example #23
Source File: GroupToSDF.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static List<Number> getAtomCharges(Group group) {
	// The list to store the answer
	List<Number> outArr = new ArrayList<Number>();
	// Get the atom charge Information
	for(Atom a: group.getAtoms()){
		outArr.add(a.getCharge());
	}
	return outArr;
}
 
Example #24
Source File: TestSubunitCluster.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test {@link SubunitCluster#mergeIdentical(SubunitCluster)}.
 */
@Test
public void testMergeIdentical() {

	// Create an Atom Array of poly-alanine
	Atom[] reprAtoms = mockAtomArray(10, "ALA", -1, null);

	// Create two identical SubunitCluster
	SubunitCluster sc1 = new SubunitCluster(new Subunit(reprAtoms,
			"subunit 1", null, null));
	SubunitCluster sc2 = new SubunitCluster(new Subunit(reprAtoms,
			"subunit 2", null, null));

	boolean merged = sc1.mergeIdentical(sc2);

	// Merged have to be true, and the merged SubunitCluster is sc1
	assertTrue(merged);
	assertEquals(2, sc1.size());
	assertEquals(1, sc2.size());
	assertEquals(10, sc1.length());

	// Create an Atom Array of poly-glycine
	Atom[] reprAtoms2 = mockAtomArray(10, "GLY", -1, null);

	SubunitCluster sc3 = new SubunitCluster(new Subunit(reprAtoms2,
			"subunit 1", null, null));

	merged = sc1.mergeIdentical(sc3);

	// Merged have to be false, and Clusters result inmodified
	assertFalse(merged);
	assertEquals(2, sc1.size());
	assertEquals(1, sc2.size());
	assertEquals(10, sc1.length());

}
 
Example #25
Source File: MultipleAlignmentScorer.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Calculates the RMSD of all-to-all structure comparisons (distances),
 * given a set of superimposed atoms.
 *
 * @param transformed
 * @return double RMSD
 * @see #getRMSD(MultipleAlignment)
 */
public static double getRMSD(List<Atom[]> transformed) {

	double sumSqDist = 0;
	int comparisons = 0;

	for (int r1 = 0; r1 < transformed.size(); r1++) {
		for (int c = 0; c < transformed.get(r1).length; c++) {
			Atom refAtom = transformed.get(r1)[c];
			if (refAtom == null)
				continue;

			double nonNullSqDist = 0;
			int nonNullLength = 0;
			for (int r2 = r1 + 1; r2 < transformed.size(); r2++) {
				Atom atom = transformed.get(r2)[c];
				if (atom != null) {
					nonNullSqDist += Calc.getDistanceFast(refAtom, atom);
					nonNullLength++;
				}
			}

			if (nonNullLength > 0) {
				comparisons++;
				sumSqDist += nonNullSqDist / nonNullLength;
			}
		}
	}
	return Math.sqrt(sumSqDist / comparisons);
}
 
Example #26
Source File: AFPChainXMLConverter.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void printXMLMatrixShift(PrettyXMLWriter xml,
		AFPChain afpChain, int blockNr)  throws IOException {

	Matrix[] ms     = afpChain.getBlockRotationMatrix();
	if ( ms == null || ms.length == 0)
		return;

	Matrix matrix = ms[blockNr];
	if ( matrix == null)
		return;
	xml.openTag("matrix");


	for (int x=0;x<3;x++){
		for (int y=0;y<3;y++){
			String key = "mat"+(x+1)+(y+1);
			xml.attribute(key,String.format("%.6f",matrix.get(x,y)));
		}
	}
	xml.closeTag("matrix");

	Atom[]   shifts = afpChain.getBlockShiftVector();
	Atom shift = shifts[blockNr];
	xml.openTag("shift");
	xml.attribute("x", String.format("%.3f",shift.getX()));
	xml.attribute("y", String.format("%.3f",shift.getY()));
	xml.attribute("z", String.format("%.3f",shift.getZ()));
	xml.closeTag("shift");

}
 
Example #27
Source File: RotationAxis.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Create a rotation axis from a Matrix4d containing a rotational
 * component and a translational component.
 *
 * @param transform
 */
public RotationAxis(Matrix4d transform) {

	Matrix rot = Matrices.getRotationJAMA(transform);
	Atom transl = Calc.getTranslationVector(transform);
	init(rot,transl);
}
 
Example #28
Source File: MultipleAlignmentScorer.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Calculates the average TMScore from all structures to a reference
 * structure, given a set of superimposed atoms.
 * <p>
 * Complexity: T(n,l) = O(l*n^2), if n=number of structures and l=alignment
 * length.
 *
 * @param transformed
 *            Arrays of aligned atoms, after superposition
 * @param lengths
 *            lengths of the full input structures
 * @param reference
 *            Index of the reference structure
 * @return
 * @throws StructureException
 */
public static double getRefTMScore(List<Atom[]> transformed,
		List<Integer> lengths, int reference) throws StructureException {

	if (transformed.size() != lengths.size())
		throw new IllegalArgumentException("Input sizes differ");

	double sumTM = 0;
	int comparisons = 0;

	int len = transformed.get(reference).length;
	for (int r = 0; r < transformed.size(); r++) {
		if (r == reference)
			continue;
		// remove nulls from both arrays
		Atom[] ref = new Atom[len];
		Atom[] aln = new Atom[len];
		int nonNullLen = 0;
		for (int c = 0; c < len; c++) {
			if (transformed.get(reference)[c] != null
					&& transformed.get(r)[c] != null) {
				ref[nonNullLen] = transformed.get(reference)[c];
				aln[nonNullLen] = transformed.get(r)[c];
				nonNullLen++;
			}
		}
		// truncate nulls
		if (nonNullLen < len) {
			ref = Arrays.copyOf(ref, nonNullLen);
			aln = Arrays.copyOf(aln, nonNullLen);
		}
		sumTM += Calc.getTMScore(ref, aln,
				lengths.get(reference), lengths.get(r));
		comparisons++;
	}
	return sumTM / comparisons;
}
 
Example #29
Source File: MmtfUtils.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Get summary information for the structure.
 * @param structure the structure for which to get the information.
 */
public static MmtfSummaryDataBean getStructureInfo(Structure structure) {
	MmtfSummaryDataBean mmtfSummaryDataBean = new MmtfSummaryDataBean();
	// Get all the atoms
	List<Atom> theseAtoms = new ArrayList<>();
	List<Chain> allChains = new ArrayList<>();
	Map<String, Integer> chainIdToIndexMap = new LinkedHashMap<>();
	int chainCounter = 0;
	int bondCount = 0;
	mmtfSummaryDataBean.setAllAtoms(theseAtoms);
	mmtfSummaryDataBean.setAllChains(allChains);
	mmtfSummaryDataBean.setChainIdToIndexMap(chainIdToIndexMap);
	for (int i=0; i<structure.nrModels(); i++){
		List<Chain> chains = structure.getModel(i);
		allChains.addAll(chains);
		for (Chain chain : chains) {
			String idOne = chain.getId();
			if (!chainIdToIndexMap.containsKey(idOne)) {
				chainIdToIndexMap.put(idOne, chainCounter);
			}
			chainCounter++;
			for (Group g : chain.getAtomGroups()) {
				for(Atom atom: getAtomsForGroup(g)){
					theseAtoms.add(atom);
					// If both atoms are in the group
					if (atom.getBonds()!=null){
						bondCount+=atom.getBonds().size();
					}
				}
			}
		}
	}
	// Assumes all bonds are referenced twice
	mmtfSummaryDataBean.setNumBonds(bondCount/2);
	return mmtfSummaryDataBean;

}
 
Example #30
Source File: CeSymm.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Analyze the symmetries of the input Atom array using the provided
 * parameters.
 *
 * @param atoms
 *            representative Atom array of the Structure
 * @param param
 *            CeSymmParameters bean
 * @return CeSymmResult
 * @throws StructureException
 */
public static CeSymmResult analyze(Atom[] atoms, CESymmParameters params)
		throws StructureException {

	if (atoms.length < 1)
		throw new IllegalArgumentException("Empty Atom array given.");

	// If the SSE information is needed, we calculate it if the user did not
	if (params.getSSEThreshold() > 0) {
		Structure s = atoms[0].getGroup().getChain().getStructure();
		if (SecStrucTools.getSecStrucInfo(s).isEmpty()) {
			logger.info("Calculating Secondary Structure...");
			SecStrucCalc ssp = new SecStrucCalc();
			ssp.calculate(s, true);
		}
	}

	CeSymmIterative iter = new CeSymmIterative(params);
	CeSymmResult result = iter.execute(atoms);

	if (result.isRefined()) {
		// Optimize the global alignment freely once more (final step)
		if (params.getOptimization() && result.getSymmLevels() > 1) {
			try {
				SymmOptimizer optimizer = new SymmOptimizer(result);
				MultipleAlignment optimized = optimizer.optimize();
				// Set the optimized MultipleAlignment and the axes
				result.setMultipleAlignment(optimized);
			} catch (RefinerFailedException e) {
				logger.info("Final optimization failed:" + e.getMessage());
			}
		}
		result.getMultipleAlignment().getEnsemble()
				.setStructureIdentifiers(result.getRepeatsID());
	}
	return result;
}