private static void replaceReferencesWithClones(final IChemModel chemModel) throws CDKException { // we make references in products/reactants clones, since same compounds // in different reactions need separate layout (different positions etc) if (chemModel.getReactionSet() != null) { for (final IReaction reaction : chemModel.getReactionSet() .reactions()) { int i = 0; final IAtomContainerSet products = reaction.getProducts(); for (final IAtomContainer product : products.atomContainers()) { try { products.replaceAtomContainer(i, product.clone()); } catch (final CloneNotSupportedException e) { } i++; } i = 0; final IAtomContainerSet reactants = reaction.getReactants(); for (final IAtomContainer reactant : reactants.atomContainers()) { try { reactants.replaceAtomContainer(i, reactant.clone()); } catch (final CloneNotSupportedException e) { } i++; } } } }
/** {@inheritDoc} */ @Override @TestMethod("testEmptyReaction") public IRenderingElement generate(IReaction reaction, RendererModel model) { if (!model.getParameter(ShowReactionBoxes.class).getValue()) return null; double separation = model.getParameter(BondLength.class).getValue() / model.getParameter(Scale.class).getValue(); Rectangle2D totalBounds = BoundsCalculator.calculateBounds(reaction); if (totalBounds == null) return null; ElementGroup diagram = new ElementGroup(); Color foregroundColor = model.getParameter(BasicSceneGenerator.ForegroundColor.class).getValue(); diagram.add( new RectangleElement( totalBounds.getMinX() - separation, totalBounds.getMinY() - separation, totalBounds.getMaxX() + separation, totalBounds.getMaxY() + separation, foregroundColor)); if (reaction.getID() != null) { diagram.add( new TextElement( (totalBounds.getMinX() + totalBounds.getMaxX()) / 2, totalBounds.getMinY() - separation, reaction.getID(), foregroundColor)); } return diagram; }
private double caclModelScale(IReaction rxn) { List<IAtomContainer> mols = new ArrayList<>(); for (IAtomContainer mol : rxn.getReactants().atomContainers()) mols.add(mol); for (IAtomContainer mol : rxn.getProducts().atomContainers()) mols.add(mol); for (IAtomContainer mol : rxn.getAgents().atomContainers()) mols.add(mol); return caclModelScale(mols); }
private synchronized double calRelation(IReaction reaction, IMappingAlgorithm theory) { try { Map<Integer, IAtomContainer> educts = synchronizedSortedMap(new TreeMap<Integer, IAtomContainer>()); for (int i = 0; i < reaction.getReactantCount(); i++) { educts.put(i, reaction.getReactants().getAtomContainer(i)); } Map<Integer, IAtomContainer> products = synchronizedSortedMap(new TreeMap<Integer, IAtomContainer>()); for (int i = 0; i < reaction.getProductCount(); i++) { products.put(i, reaction.getProducts().getAtomContainer(i)); } GameTheoryMatrix EDSH = new GameTheoryMatrix(theory, reaction, removeHydrogen); IGameTheory gameTheory = make(theory, reaction, removeHydrogen, educts, products, EDSH); this.reactionBlastMolMapping = gameTheory.getReactionMolMapping(); EDSH.Clear(); return gameTheory.getDelta(); } catch (Exception e) { logger.error(e); return -1; } }
public String toString() { StringBuffer buffer = new StringBuffer(32); buffer.append("ReactionSet("); buffer.append(this.hashCode()); buffer.append(", R=").append(getReactionCount()).append(", "); for (IReaction reaction : reactions()) { buffer.append(reaction.toString()); } buffer.append(')'); return buffer.toString(); }
private static void setReactionIDs(final IChemModel chemModel) { // we give all reactions an ID, in case they have none // IDs are needed for handling in JCP final IReactionSet reactionSet = chemModel.getReactionSet(); if (reactionSet != null) { int i = 0; for (final IReaction reaction : reactionSet.reactions()) { if (reaction.getID() == null) { reaction.setID("Reaction " + ++i); } } } }
// ~--- constructors ------------------------------------------------------- GameTheoryMin( IReaction reaction, boolean removeHydrogen, Map<Integer, IAtomContainer> _educts, Map<Integer, IAtomContainer> _products, GameTheoryMatrix rpsh) throws Exception { if (DEBUG) { out.println("I am MIN MIX"); } this.canonLabeler = new SmilesMoleculeLabeller(); this.removeHydrogen = removeHydrogen; this.reaction = reaction; this.educts = _educts; this.products = _products; this.reactionName = reaction.getID(); this.eductList = synchronizedList(rpsh.getEductCounter()); this.productList = synchronizedList(rpsh.getProductCounter()); this.mh = rpsh.getMatrixHolder(); setReactionMolMapping(rpsh.getReactionMolMapping()); winner = new ChooseWinner(eductList, productList); this._dirSuffix = super.getSuffix(); ReactionIsomorphismHandler RIH = new ReactionIsomorphismHandler(mh, eductList, productList); if (RIH.getIsomorphismFlag()) { // System.out.println("ISOMORPHISM"); mh = RIH.getMatrixHolder(); GenerateIsoMorphismMapping(); } else { GenerateMapping(false); } }
private Bounds generateReactionConditions(IReaction chemObj, Color fg, double scale) { String title = chemObj.getProperty(CDKConstants.REACTION_CONDITIONS); if (title == null || title.isEmpty()) return new Bounds(); return new Bounds( MarkedElement.markup( StandardGenerator.embedText(font, title, fg, 1 / scale), "conditions")); }
/** {@inheritDoc} */ @Override @TestMethod("testEmptyReaction") public IRenderingElement generate(IReaction reaction, RendererModel model) { Rectangle2D totalBoundsReactants = BoundsCalculator.calculateBounds(reaction.getReactants()); Rectangle2D totalBoundsProducts = BoundsCalculator.calculateBounds(reaction.getProducts()); if (totalBoundsReactants == null || totalBoundsProducts == null) return null; double separation = model.getParameter(BondLength.class).getValue() / model.getParameter(Scale.class).getValue(); Color foregroundColor = model.getParameter(BasicSceneGenerator.ForegroundColor.class).getValue(); return new ArrowElement( totalBoundsReactants.getMaxX() + separation, totalBoundsReactants.getCenterY(), totalBoundsProducts.getMinX() - separation, totalBoundsReactants.getCenterY(), 1 / model.getParameter(Scale.class).getValue(), true, foregroundColor); }
@Override public void store(IReaction reaction) { String id = reaction.getID(); File file = new File(reactionDir, id + ".rxn"); try { FileWriter writer = new FileWriter(file); rxnWriter = new MDLV2000RXNWriter(writer); // rxnWriter.setWriter(writer); rxnWriter.write(reaction); // writer.flush(); // writer.close(); rxnWriter.close(); } catch (CDKException | IOException e) { e.printStackTrace(); } }
/** * @param removeHydrogen * @param reaction * @param algorithm */ public CalculationProcess( boolean removeHydrogen, IReaction reaction, IMappingAlgorithm algorithm) { /* * This case handles rings cases where 6 membered ring reduces to 5 membered rings Example KEGG reaction R01432 * of Isomerase class */ super(reaction); // System.out.println("I am CalculationProcess"); this.removeHydrogen = removeHydrogen; logger.debug("\n|++++++++++++++++++++++++++++|"); logger.debug("Performing Atom-Atom Mapping ....... " + reaction.getID() + " ......."); logger.debug("\n|++++++++++++++++++++++++++++|"); this.algorithm = algorithm; run(); }
@Test public void testReaction() throws Exception { String cmlString = "<reaction>" + "<reactantList><reactant><molecule id='react'/></reactant></reactantList>" + "<productList><product><molecule id='product'/></product></productList>" + "<substanceList><substance><molecule id='water'/></substance></substanceList>" + "</reaction>"; IChemFile chemFile = parseCMLString(cmlString); IReaction reaction = checkForSingleReactionFile(chemFile); Assert.assertEquals(1, reaction.getReactantCount()); Assert.assertEquals(1, reaction.getProductCount()); Assert.assertEquals(1, reaction.getAgents().getMoleculeCount()); Assert.assertEquals("react", reaction.getReactants().getMolecule(0).getID()); Assert.assertEquals("product", reaction.getProducts().getMolecule(0).getID()); Assert.assertEquals("water", reaction.getAgents().getMolecule(0).getID()); }
private IReaction readReaction(IChemObjectBuilder builder) throws CDKException { IReaction reaction = builder.newInstance(IReaction.class); readLine(); // first line should be $RXN readLine(); // second line readLine(); // third line readLine(); // fourth line int reactantCount = 0; int productCount = 0; boolean foundCOUNTS = false; while (isReady() && !foundCOUNTS) { String command = readCommand(); if (command.startsWith("COUNTS")) { StringTokenizer tokenizer = new StringTokenizer(command); try { tokenizer.nextToken(); reactantCount = Integer.valueOf(tokenizer.nextToken()).intValue(); logger.info("Expecting " + reactantCount + " reactants in file"); productCount = Integer.valueOf(tokenizer.nextToken()).intValue(); logger.info("Expecting " + productCount + " products in file"); } catch (Exception exception) { logger.debug(exception); throw new CDKException("Error while counts line of RXN file", exception); } foundCOUNTS = true; } else { logger.warn("Waiting for COUNTS line, but found: " + command); } } // now read the reactants for (int i = 1; i <= reactantCount; i++) { StringBuffer molFile = new StringBuffer(); String announceMDLFileLine = readCommand(); if (!announceMDLFileLine.equals("BEGIN REACTANT")) { String error = "Excepted start of reactant, but found: " + announceMDLFileLine; logger.error(error); throw new CDKException(error); } String molFileLine = ""; while (!molFileLine.endsWith("END REACTANT")) { molFileLine = readLine(); molFile.append(molFileLine); molFile.append(System.getProperty("line.separator")); } ; try { // read MDL molfile content MDLV3000Reader reader = new MDLV3000Reader(new StringReader(molFile.toString()), super.mode); IAtomContainer reactant = (IAtomContainer) reader.read(builder.newInstance(IAtomContainer.class)); // add reactant reaction.addReactant(reactant); } catch (Exception exception) { String error = "Error while reading reactant: " + exception.getMessage(); logger.error(error); logger.debug(exception); throw new CDKException(error, exception); } } // now read the products for (int i = 1; i <= productCount; i++) { StringBuffer molFile = new StringBuffer(); String announceMDLFileLine = readCommand(); if (!announceMDLFileLine.equals("BEGIN PRODUCT")) { String error = "Excepted start of product, but found: " + announceMDLFileLine; logger.error(error); throw new CDKException(error); } String molFileLine = ""; while (!molFileLine.endsWith("END PRODUCT")) { molFileLine = readLine(); molFile.append(molFileLine); molFile.append(System.getProperty("line.separator")); } ; try { // read MDL molfile content MDLV3000Reader reader = new MDLV3000Reader(new StringReader(molFile.toString())); IAtomContainer product = (IAtomContainer) reader.read(builder.newInstance(IAtomContainer.class)); // add product reaction.addProduct(product); } catch (Exception exception) { String error = "Error while reading product: " + exception.getMessage(); logger.error(error); logger.debug(exception); throw new CDKException(error, exception); } } return reaction; }
/** * Read a Reaction from a file in MDL RXN format * * @return The Reaction that was read from the MDL file. */ private IReaction readReaction(IChemObjectBuilder builder) throws CDKException { IReaction reaction = builder.newReaction(); try { input.readLine(); // first line should be $RXN input.readLine(); // second line input.readLine(); // third line input.readLine(); // fourth line } catch (IOException exception) { logger.debug(exception); throw new CDKException("Error while reading header of RXN file", exception); } int reactantCount = 0; int productCount = 0; try { String countsLine = input.readLine(); /* this line contains the number of reactants and products */ StringTokenizer tokenizer = new StringTokenizer(countsLine); reactantCount = Integer.valueOf(tokenizer.nextToken()).intValue(); logger.info("Expecting " + reactantCount + " reactants in file"); productCount = Integer.valueOf(tokenizer.nextToken()).intValue(); logger.info("Expecting " + productCount + " products in file"); } catch (Exception exception) { logger.debug(exception); throw new CDKException("Error while counts line of RXN file", exception); } // now read the reactants try { for (int i = 1; i <= reactantCount; i++) { StringBuffer molFile = new StringBuffer(); input.readLine(); // announceMDLFileLine String molFileLine = ""; do { molFileLine = input.readLine(); molFile.append(molFileLine); molFile.append(System.getProperty("line.separator")); } while (!molFileLine.equals("M END")); // read MDL molfile content // Changed this to mdlv2000 reader MDLV2000Reader reader = new MDLV2000Reader(new StringReader(molFile.toString()), super.mode); IMolecule reactant = (IMolecule) reader.read(builder.newMolecule()); // add reactant reaction.addReactant(reactant); } } catch (CDKException exception) { // rethrow exception from MDLReader throw exception; } catch (Exception exception) { logger.debug(exception); throw new CDKException("Error while reading reactant", exception); } // now read the products try { for (int i = 1; i <= productCount; i++) { StringBuffer molFile = new StringBuffer(); input.readLine(); // String announceMDLFileLine = String molFileLine = ""; do { molFileLine = input.readLine(); molFile.append(molFileLine); molFile.append(System.getProperty("line.separator")); } while (!molFileLine.equals("M END")); // read MDL molfile content MDLV2000Reader reader = new MDLV2000Reader(new StringReader(molFile.toString())); IMolecule product = (IMolecule) reader.read(builder.newMolecule()); // add reactant reaction.addProduct(product); } } catch (CDKException exception) { // rethrow exception from MDLReader throw exception; } catch (Exception exception) { logger.debug(exception); throw new CDKException("Error while reading products", exception); } // now try to map things, if wanted logger.info("Reading atom-atom mapping from file"); // distribute all atoms over two AtomContainer's IAtomContainer reactingSide = builder.newAtomContainer(); java.util.Iterator molecules = reaction.getReactants().molecules().iterator(); while (molecules.hasNext()) { reactingSide.add((IMolecule) molecules.next()); } IAtomContainer producedSide = builder.newAtomContainer(); molecules = reaction.getProducts().molecules().iterator(); while (molecules.hasNext()) { producedSide.add((IMolecule) molecules.next()); } // map the atoms int mappingCount = 0; // IAtom[] reactantAtoms = reactingSide.getAtoms(); // IAtom[] producedAtoms = producedSide.getAtoms(); for (int i = 0; i < reactingSide.getAtomCount(); i++) { for (int j = 0; j < producedSide.getAtomCount(); j++) { IAtom eductAtom = reactingSide.getAtom(i); IAtom productAtom = producedSide.getAtom(j); if (eductAtom.getID() != null && eductAtom.getID().equals(productAtom.getID())) { reaction.addMapping(builder.newMapping(eductAtom, productAtom)); mappingCount++; break; } } } logger.info("Mapped atom pairs: " + mappingCount); return reaction; }
/** * Depict a reaction. * * @param rxn reaction instance * @return depiction * @throws CDKException a depiction could not be generated */ public Depiction depict(IReaction rxn) throws CDKException { ensure2dLayout(rxn); // can reorder components! final Color fgcol = getParameterValue(StandardGenerator.AtomColor.class) .getAtomColor(rxn.getBuilder().newInstance(IAtom.class, "C")); final List<IAtomContainer> reactants = toList(rxn.getReactants()); final List<IAtomContainer> products = toList(rxn.getProducts()); final List<IAtomContainer> agents = toList(rxn.getAgents()); // set ids for tagging elements int molId = 0; for (IAtomContainer mol : reactants) { setIfMissing(mol, MarkedElement.ID_KEY, "mol" + ++molId); setIfMissing(mol, MarkedElement.CLASS_KEY, "reactant"); } for (IAtomContainer mol : products) { setIfMissing(mol, MarkedElement.ID_KEY, "mol" + ++molId); setIfMissing(mol, MarkedElement.CLASS_KEY, "product"); } for (IAtomContainer mol : agents) { setIfMissing(mol, MarkedElement.ID_KEY, "mol" + ++molId); setIfMissing(mol, MarkedElement.CLASS_KEY, "agent"); } final Map<IChemObject, Color> myHighlight = new HashMap<>(); if (highlightAtomMap) { myHighlight.putAll(makeHighlightAtomMap(reactants, products)); } // user highlight buffer pushes out the atom-map highlight if provided myHighlight.putAll(highlight); highlight.clear(); final List<Double> reactantScales = prepareCoords(reactants); final List<Double> productScales = prepareCoords(products); final List<Double> agentScales = prepareCoords(agents); // highlight parts for (Map.Entry<IChemObject, Color> e : myHighlight.entrySet()) e.getKey().setProperty(StandardGenerator.HIGHLIGHT_COLOR, e.getValue()); // setup the model scale based on bond length final double scale = this.caclModelScale(rxn); final DepictionGenerator copy = this.withParam(BasicSceneGenerator.Scale.class, scale); final RendererModel model = copy.getModel(); // reactant/product/agent element generation, we number the reactants, then products then agents List<Bounds> reactantBounds = copy.generate(reactants, model, 1); List<Bounds> productBounds = copy.generate(toList(rxn.getProducts()), model, rxn.getReactantCount()); List<Bounds> agentBounds = copy.generate( toList(rxn.getAgents()), model, rxn.getReactantCount() + rxn.getProductCount()); // remove current highlight buffer for (IChemObject obj : myHighlight.keySet()) obj.removeProperty(StandardGenerator.HIGHLIGHT_COLOR); // generate a 'plus' element Bounds plus = copy.generatePlusSymbol(scale, fgcol); // reset the coordinates to how they were before we invoked depict resetCoords(reactants, reactantScales); resetCoords(products, productScales); resetCoords(agents, agentScales); final Bounds emptyBounds = new Bounds(); final Bounds title = copy.getParameterValue(BasicSceneGenerator.ShowReactionTitle.class) ? copy.generateTitle(rxn, scale) : emptyBounds; final List<Bounds> reactantTitles = new ArrayList<>(); final List<Bounds> productTitles = new ArrayList<>(); if (copy.getParameterValue(BasicSceneGenerator.ShowMoleculeTitle.class)) { for (IAtomContainer reactant : reactants) reactantTitles.add(copy.generateTitle(reactant, scale)); for (IAtomContainer product : products) productTitles.add(copy.generateTitle(product, scale)); } final Bounds conditions = generateReactionConditions(rxn, fgcol, model.get(BasicSceneGenerator.Scale.class)); return new ReactionDepiction( model, reactantBounds, productBounds, agentBounds, plus, rxn.getDirection(), dimensions, reactantTitles, productTitles, title, conditions, fgcol); }
/** * Initiates the process for the given mechanism. The atoms to apply are mapped between reactants * and products. * * @param atomContainerSet * @param atomList The list of atoms taking part in the mechanism. Only allowed two atoms. The * first atom is the atom which contains the ISingleElectron and the second third is the atom * which will be removed the first atom * @param bondList The list of bonds taking part in the mechanism. Only allowed one bond. It is * the bond which is moved * @return The Reaction mechanism */ @TestMethod(value = "testInitiate_IAtomContainerSet_ArrayList_ArrayList") public IReaction initiate( IAtomContainerSet atomContainerSet, ArrayList<IAtom> atomList, ArrayList<IBond> bondList) throws CDKException { CDKAtomTypeMatcher atMatcher = CDKAtomTypeMatcher.getInstance(atomContainerSet.getBuilder()); if (atomContainerSet.getAtomContainerCount() != 1) { throw new CDKException("RadicalSiteIonizationMechanism only expects one IMolecule"); } if (atomList.size() != 3) { throw new CDKException("RadicalSiteIonizationMechanism expects three atoms in the ArrayList"); } if (bondList.size() != 2) { throw new CDKException( "RadicalSiteIonizationMechanism only expect one bond in the ArrayList"); } IAtomContainer molecule = atomContainerSet.getAtomContainer(0); IAtomContainer reactantCloned; try { reactantCloned = (IAtomContainer) molecule.clone(); } catch (CloneNotSupportedException e) { throw new CDKException("Could not clone IMolecule!", e); } IAtom atom1 = atomList.get(0); // Atom containing the ISingleElectron IAtom atom1C = reactantCloned.getAtom(molecule.getAtomNumber(atom1)); IAtom atom2 = atomList.get(1); // Atom IAtom atom2C = reactantCloned.getAtom(molecule.getAtomNumber(atom2)); IAtom atom3 = atomList.get(2); // Atom to be saved IAtom atom3C = reactantCloned.getAtom(molecule.getAtomNumber(atom3)); IBond bond1 = bondList.get(0); // Bond to increase the order int posBond1 = molecule.getBondNumber(bond1); IBond bond2 = bondList.get(1); // Bond to remove int posBond2 = molecule.getBondNumber(bond2); BondManipulator.increaseBondOrder(reactantCloned.getBond(posBond1)); reactantCloned.removeBond(reactantCloned.getBond(posBond2)); List<ISingleElectron> selectron = reactantCloned.getConnectedSingleElectronsList(atom1C); reactantCloned.removeSingleElectron(selectron.get(selectron.size() - 1)); atom1C.setHybridization(null); AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(reactantCloned); IAtomType type = atMatcher.findMatchingAtomType(reactantCloned, atom1C); if (type == null) return null; atom2C.setHybridization(null); AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(reactantCloned); type = atMatcher.findMatchingAtomType(reactantCloned, atom2C); if (type == null) return null; reactantCloned.addSingleElectron(new SingleElectron(atom3C)); atom3C.setHybridization(null); AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(reactantCloned); type = atMatcher.findMatchingAtomType(reactantCloned, atom3C); if (type == null) return null; IReaction reaction = DefaultChemObjectBuilder.getInstance().newInstance(IReaction.class); reaction.addReactant(molecule); /* mapping */ for (IAtom atom : molecule.atoms()) { IMapping mapping = DefaultChemObjectBuilder.getInstance() .newInstance( IMapping.class, atom, reactantCloned.getAtom(molecule.getAtomNumber(atom))); reaction.addMapping(mapping); } IAtomContainerSet moleculeSetP = ConnectivityChecker.partitionIntoMolecules(reactantCloned); for (int z = 0; z < moleculeSetP.getAtomContainerCount(); z++) reaction.addProduct((IAtomContainer) moleculeSetP.getAtomContainer(z)); return reaction; }