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++;
				}
			}
		}
	}
Пример #2
0
 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);
 }
Пример #3
0
  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;
    }
  }
Пример #4
0
  @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());
  }
Пример #5
0
  /** {@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);
  }
  /**
   * 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;
  }
Пример #7
0
  /**
   * 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);
  }