Skip to content

Commit

Permalink
Merge pull request #316 from cdk/patch/cleanup_20170503
Browse files Browse the repository at this point in the history
  • Loading branch information
egonw committed May 7, 2017
2 parents 10c6453 + 25588a8 commit 5c43a9f
Show file tree
Hide file tree
Showing 4 changed files with 121 additions and 118 deletions.
Expand Up @@ -19,6 +19,7 @@
package org.openscience.cdk.math;

import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.openscience.cdk.SlowTest;
Expand Down Expand Up @@ -127,8 +128,7 @@ public void testRandomInt_int_int() {
Assert.assertTrue(random == 0 || random == 1 || random == 2 || random == 3 || random == 4 || random == 5);
}

@Category(SlowTest.class)
@Test
@Ignore("Test based on random probability - random failures")
public void testFlipCoin() {
int ntry = 1000000;
double p = 0.5;
Expand All @@ -144,7 +144,7 @@ public void testFlipCoin() {
Assert.assertEquals(0.5, (double) nfalse / ntry, 0.001);
}

@Test
@Ignore("Test based on random probability - random failures")
public void testGaussianFloat() {
float dev = (float) 1.0;
float epsilon = 0.01f;
Expand All @@ -168,7 +168,7 @@ public void testGaussianFloat() {
&& sd <= (dev + epsilon));
}

@Test
@Ignore("Test based on random probability - random failures")
public void testGaussianDouble() {
double dev = 2.0;
double epsilon = 0.01;
Expand All @@ -191,7 +191,7 @@ public void testGaussianDouble() {
&& sd <= (dev + epsilon));
}

@Test
@Ignore("Test based on random probability - random failures")
public void testExponentialDouble() {
double mean = 1.0f;
double epsilon = 0.01f;
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Expand Up @@ -438,7 +438,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<version>2.20</version>
<configuration>
<excludes>
<!-- not a test class -->
Expand Down
Expand Up @@ -661,6 +661,7 @@ private void writeMol(IAtomContainer mol) throws IOException, CDKException {

writer.write("END CTAB\n");
writer.writeDirect("M END\n");
writer.writer.flush();
}


Expand Down
Expand Up @@ -24,64 +24,62 @@
*/
package org.openscience.cdk.modeling.builder3d;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.StringTokenizer;
import java.util.zip.GZIPInputStream;

import javax.vecmath.Point3d;

import org.openscience.cdk.CDKConstants;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.fingerprint.FingerprinterTool;
import org.openscience.cdk.fingerprint.HybridizationFingerprinter;
import org.openscience.cdk.interfaces.IAtom;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IAtomContainerSet;
import org.openscience.cdk.interfaces.IBond;
import org.openscience.cdk.interfaces.IChemObject;
import org.openscience.cdk.interfaces.IChemObjectBuilder;
import org.openscience.cdk.interfaces.IRingSet;
import org.openscience.cdk.io.iterator.IteratingSDFReader;
import org.openscience.cdk.isomorphism.Mappings;
import org.openscience.cdk.isomorphism.Pattern;
import org.openscience.cdk.isomorphism.UniversalIsomorphismTester;
import org.openscience.cdk.isomorphism.mcss.RMap;
import org.openscience.cdk.isomorphism.matchers.IQueryAtomContainer;
import org.openscience.cdk.isomorphism.matchers.QueryAtomContainer;
import org.openscience.cdk.isomorphism.matchers.QueryAtomContainerCreator;
import org.openscience.cdk.silent.SilentChemObjectBuilder;
import org.openscience.cdk.tools.ILoggingTool;
import org.openscience.cdk.tools.LoggingToolFactory;
import org.openscience.cdk.tools.manipulator.AtomContainerManipulator;
import org.openscience.cdk.tools.manipulator.RingSetManipulator;

/**
* Helper class for ModelBuilder3D. Handles templates. This is
* our layout solution for 3D ring systems
*
* @author cho
* @author steinbeck
* @author cho
* @author steinbeck
* @author John Mayfield
* @cdk.created 2004-09-21
* @cdk.module builder3d
* @cdk.module builder3d
* @cdk.githash
*/
public class TemplateHandler3D {

private static final IChemObjectBuilder builder = SilentChemObjectBuilder.getInstance();
private static final ILoggingTool logger = LoggingToolFactory
.createLoggingTool(TemplateHandler3D.class);
private static final IChemObjectBuilder builder = SilentChemObjectBuilder.getInstance();
public static final String TEMPLATE_PATH = "data/ringTemplateStructures.sdf.gz";

IAtomContainer molecule;
IRingSet sssr;
IAtomContainerSet templates = null;
private boolean templatesLoaded = false;
private final List<IAtomContainer> templates = new ArrayList<>();
private final List<IQueryAtomContainer> queries = new ArrayList<>();
private final List<Pattern> patterns = new ArrayList<>();

private static TemplateHandler3D self = null;
private static TemplateHandler3D self = null;

private UniversalIsomorphismTester universalIsomorphismTester = new UniversalIsomorphismTester();
private UniversalIsomorphismTester universalIsomorphismTester = new UniversalIsomorphismTester();

private TemplateHandler3D() {
templates = builder.newInstance(IAtomContainerSet.class);
}

public static TemplateHandler3D getInstance() throws CDKException {
Expand All @@ -91,40 +89,37 @@ public static TemplateHandler3D getInstance() throws CDKException {
return self;
}

private void addTemplateMol(IAtomContainer mol) {
templates.add(mol);
QueryAtomContainer query = QueryAtomContainerCreator.createAnyAtomAnyBondContainer(mol, false);
queries.add(query);
for (int i = 0; i < mol.getAtomCount(); i++) {
query.getAtom(i).setPoint3d(new Point3d(mol.getAtom(i).getPoint3d()));
}
patterns.add(Pattern.findSubstructure(query));
}

/**
* Loads all existing templates into memory.
* Template file is a mdl file. Creates a Object Set of Molecules
* Load ring template
*
* @throws CDKException The template file cannot be loaded
*/
private void loadTemplates() throws CDKException {
logger.debug("Loading templates...");
IteratingSDFReader imdl;
InputStream ins;
BufferedReader fin;

try {
ins = this.getClass().getClassLoader()
.getResourceAsStream("org/openscience/cdk/modeling/builder3d/data/ringTemplateStructures.sdf.gz");
fin = new BufferedReader(new InputStreamReader(new GZIPInputStream(ins)));
imdl = new IteratingSDFReader(fin, builder);
} catch (IOException exc1) {
throw new CDKException("Problems loading file ringTemplateStructures.sdf.gz", exc1);
}
IAtomContainer molecule;
while (imdl.hasNext()) {
molecule = (IAtomContainer) imdl.next();
templates.addAtomContainer(molecule);
}
molecule = null;
try {
imdl.close();
} catch (Exception exc2) {
System.out.println("Could not close Reader due to: " + exc2.getMessage());
try (InputStream gin = getClass().getResourceAsStream(TEMPLATE_PATH);
InputStream in = new GZIPInputStream(gin);
IteratingSDFReader sdfr = new IteratingSDFReader(in, builder)) {
while (sdfr.hasNext()) {
final IAtomContainer mol = sdfr.next();
addTemplateMol(mol);
}
} catch (IOException e) {
throw new CDKException("Could not load ring templates", e);
}
templatesLoaded = true;
}

public static BitSet getBitSetFromFile(StringTokenizer st) throws Exception {

public static BitSet getBitSetFromFile(StringTokenizer st) throws
Exception {
BitSet bitSet = new BitSet(1024);
while (st.hasMoreTokens()) {
bitSet.set(Integer.parseInt(st.nextToken()));
Expand All @@ -135,13 +130,13 @@ public static BitSet getBitSetFromFile(StringTokenizer st) throws Exception {
/**
* Returns the largest (number of atoms) ring set in a molecule.
*
*@param ringSystems RingSystems of a molecule
*@return The largestRingSet
* @param ringSystems RingSystems of a molecule
* @return The largestRingSet
*/
public IRingSet getLargestRingSet(List<IRingSet> ringSystems) {
IRingSet largestRingSet = null;
int atomNumber = 0;
IAtomContainer container = null;
IRingSet largestRingSet = null;
int atomNumber = 0;
IAtomContainer container = null;
for (int i = 0; i < ringSystems.size(); i++) {
container = getAllInOneContainer(ringSystems.get(i));
if (atomNumber < container.getAtomCount()) {
Expand All @@ -153,8 +148,8 @@ public IRingSet getLargestRingSet(List<IRingSet> ringSystems) {
}

private IAtomContainer getAllInOneContainer(IRingSet ringSet) {
IAtomContainer resultContainer = ringSet.getBuilder().newInstance(IAtomContainer.class);
Iterator<IAtomContainer> containers = RingSetManipulator.getAllAtomContainers(ringSet).iterator();
IAtomContainer resultContainer = ringSet.getBuilder().newInstance(IAtomContainer.class);
Iterator<IAtomContainer> containers = RingSetManipulator.getAllAtomContainers(ringSet).iterator();
while (containers.hasNext()) {
resultContainer.add((IAtomContainer) containers.next());
}
Expand All @@ -165,77 +160,84 @@ private IAtomContainer getAllInOneContainer(IRingSet ringSet) {
* @deprecated Use {@link #mapTemplates(org.openscience.cdk.interfaces.IAtomContainer, int)}
*/
@Deprecated
public void mapTemplates(IAtomContainer ringSystems, double numberOfRingAtoms) throws CDKException,
CloneNotSupportedException {
public void mapTemplates(IAtomContainer ringSystems,
double numberOfRingAtoms) throws CDKException,
CloneNotSupportedException {
mapTemplates(ringSystems, (int) numberOfRingAtoms);
}

private boolean isExactMatch(IAtomContainer query,
Map<IChemObject, IChemObject> mapping) {
for (IAtom src : query.atoms()) {
IAtom dst = (IAtom) mapping.get(src);
if (!Objects.equals(src.getSymbol(), dst.getSymbol()))
return false;
}
for (IBond src : query.bonds()) {
IBond dst = (IBond) mapping.get(src);
if (!Objects.equals(src.getOrder(), dst.getOrder()))
return false;
}
return true;
}

/**
* Checks if one of the loaded templates is a substructure in the given
* Molecule. If so, it assigns the coordinates from the template to the
* respective atoms in the Molecule.
*
* @param ringSystems AtomContainer from the ring systems.
* @param mol AtomContainer from the ring systems.
* @param numberOfRingAtoms Number of atoms in the specified ring
* @throws CloneNotSupportedException The atomcontainer cannot be cloned.
*/
public void mapTemplates(IAtomContainer ringSystems, int numberOfRingAtoms) throws CDKException,
CloneNotSupportedException {
if (!templatesLoaded) self.loadTemplates();
public void mapTemplates(IAtomContainer mol, int numberOfRingAtoms)
throws CDKException, CloneNotSupportedException {
if (templates.isEmpty())
loadTemplates();

IAtomContainer best = null;
Map<IChemObject, IChemObject> bestMap = null;
IAtomContainer secondBest = null;
Map<IChemObject, IChemObject> secondBestMap = null;

//logger.debug("Map Template...START---Number of Ring Atoms:"+numberOfRingAtoms);
IAtomContainer ringSystemAnyBondAnyAtom = AtomContainerManipulator.anonymise(ringSystems);
for (int i = 0; i < templates.size(); i++) {

IAtomContainer query = queries.get(i);

boolean flagMaxSubstructure = false;
boolean flagSecondbest = false;
for (int i = 0; i < templates.getAtomContainerCount(); i++) {
IAtomContainer template = templates.getAtomContainer(i);
//if the atom count is different, it can't be right anyway
if (template.getAtomCount() != ringSystems.getAtomCount()) {
if (query.getAtomCount() != mol.getAtomCount()) {
continue;
}
//we compare the fingerprint with any atom and any bond
IAtomContainer templateAnyBondAnyAtom = AtomContainerManipulator.anonymise(template);
//we do the exact match with any atom and any bond
if (universalIsomorphismTester.isSubgraph(ringSystemAnyBondAnyAtom, templateAnyBondAnyAtom)) {
//if this is the case, we keep it as a guess, but look if we can do better
List<RMap> list = universalIsomorphismTester.getSubgraphAtomsMap(ringSystemAnyBondAnyAtom,
templateAnyBondAnyAtom);
boolean flagwritefromsecondbest = false;
if ((numberOfRingAtoms == list.size())
&& templateAnyBondAnyAtom.getBondCount() == ringSystems.getBondCount()) {
//so atom and bond count match, could be it's even an exact match,
//we check this with the original ring system
if (universalIsomorphismTester.isSubgraph(ringSystems, template)) {
flagMaxSubstructure = true;
list = universalIsomorphismTester.getSubgraphAtomsMap(ringSystems, template);
} else {
//if it isn't we still now it's better than just the isomorphism
flagSecondbest = true;
flagwritefromsecondbest = true;
}
}

if (!flagSecondbest || flagMaxSubstructure || flagwritefromsecondbest) {
for (int j = 0; j < list.size(); j++) {
RMap map = (RMap) list.get(j);
IAtom atom1 = ringSystems.getAtom(map.getId1());
IAtom atom2 = template.getAtom(map.getId2());
if (atom1.getFlag(CDKConstants.ISINRING)) {
atom1.setPoint3d(new Point3d(atom2.getPoint3d()));
}
}//for j
Mappings mappings = patterns.get(i).matchAll(mol);
for (Map<IChemObject, IChemObject> map : mappings.toAtomBondMap()) {
if (isExactMatch(query, map)) {
assignCoords(query, map);
return;
} else if (query.getBondCount() == mol.getBondCount()) {
best = query;
bestMap = new HashMap<>(map);
} else {
secondBest = query;
secondBestMap = new HashMap<>(map);
}
}
}

if (flagMaxSubstructure) {
break;
}
if (best != null) {
assignCoords(best, bestMap);
} else if (secondBest != null) {
assignCoords(secondBest, secondBestMap);
}

}//if subgraph
System.err.println("WARNING: Maybe RingTemplateError!");
}

}//for i
if (!flagMaxSubstructure) {
System.out.println("WARNING: Maybe RingTemplateError!");
private void assignCoords(IAtomContainer template,
Map<IChemObject, IChemObject> map) {
for (IAtom src : template.atoms()) {
IAtom dst = (IAtom) map.get(src);
dst.setPoint3d(new Point3d(src.getPoint3d()));
}
}

Expand All @@ -245,16 +247,16 @@ public void mapTemplates(IAtomContainer ringSystems, int numberOfRingAtoms) thro
* @return The templateCount value
*/
public int getTemplateCount() {
return templates.getAtomContainerCount();
return templates.size();
}

/**
* Gets the templateAt attribute of the TemplateHandler object.
* Gets the templateAt attribute of the TemplateHandler object.
*
*@param position Description of the Parameter
*@return The templateAt value
* @param position Description of the Parameter
* @return The templateAt value
*/
public IAtomContainer getTemplateAt(int position) {
return templates.getAtomContainer(position);
return templates.get(position);
}
}

0 comments on commit 5c43a9f

Please sign in to comment.