Beispiel #1
0
        private static ValidationReport ValidateChargeConservation(IReaction reaction, IAtomContainer reactants, IAtomContainer products)
        {
            var report             = new ValidationReport();
            var chargeConservation = new ValidationTest(reaction, "Total formal charge is not preserved during the reaction");
            var atoms1             = reactants.Atoms;
            int totalCharge1       = 0;

            foreach (var atom1 in atoms1)
            {
                totalCharge1 = +atom1.FormalCharge.Value;
            }
            var atoms2       = products.Atoms;
            int totalCharge2 = 0;

            foreach (var atom2 in atoms2)
            {
                totalCharge2 = +atom2.FormalCharge.Value;
            }
            if (totalCharge1 != totalCharge2)
            {
                report.Errors.Add(chargeConservation);
            }
            else
            {
                report.OKs.Add(chargeConservation);
            }
            return(report);
        }
        public void TestGetReactionByAtomContainerID_IReactionSet_String()
        {
            IReactionSet set       = builder.NewReactionSet();
            IReaction    reaction1 = builder.NewReaction();

            set.Add(reaction1);
            IAtomContainer mol1a = builder.NewAtomContainer();

            mol1a.Id = "1";
            IAtomContainer mol1b = builder.NewAtomContainer();

            mol1b.Id = "2";
            reaction1.Reactants.Add(mol1a);
            reaction1.Reactants.Add(builder.NewAtomContainer());
            reaction1.Products.Add(builder.NewAtomContainer());
            reaction1.Products.Add(builder.NewAtomContainer());

            IReaction reaction2 = builder.NewReaction();

            reaction2.Reactants.Add(builder.NewAtomContainer());
            reaction2.Products.Add(mol1b);
            set.Add(reaction2);

            IReaction reaction3 = builder.NewReaction();

            reaction3.Reactants.Add(builder.NewAtomContainer());
            reaction3.Products.Add(builder.NewAtomContainer());
            set.Add(reaction3);
            Assert.AreEqual(reaction1, ReactionSetManipulator.GetReactionByAtomContainerID(set, "1"));
            Assert.AreEqual(reaction2, ReactionSetManipulator.GetReactionByAtomContainerID(set, "2"));
            Assert.IsNull(ReactionSetManipulator.GetReactionByAtomContainerID(set, "3"));
        }
Beispiel #3
0
        public void TestNewReaction()
        {
            IChemObjectBuilder builder  = RootObject.Builder;
            IReaction          reaction = builder.NewReaction();

            Assert.IsNotNull(reaction);
        }
        public void TestGetAllIDs_IReactionSet()
        {
            IReactionSet set       = builder.NewReactionSet();
            IReaction    reaction1 = builder.NewReaction();

            set.Add(reaction1);
            reaction1.Id = "r1";
            IAtomContainer water = new AtomContainer {
                Id = "m1"
            };
            Atom oxygen = new Atom("O")
            {
                Id = "a1"
            };

            water.Atoms.Add(oxygen);
            reaction1.Reactants.Add(water);
            reaction1.Products.Add(water);
            IReaction reaction2 = builder.NewReaction();

            reaction2.Id = "r2";
            set.Add(reaction2);

            var ids = ReactionSetManipulator.GetAllIDs(set);

            Assert.IsNotNull(ids);
            Assert.AreEqual(6, ids.Count());
        }
        public void TestGetRelevantReactionsAsProduct_IReactionSet_IAtomContainer()
        {
            IReactionSet set       = builder.NewReactionSet();
            IReaction    reaction1 = builder.NewReaction();

            set.Add(reaction1);
            IAtomContainer mol1a = builder.NewAtomContainer();
            IAtomContainer mol1b = builder.NewAtomContainer();

            reaction1.Reactants.Add(mol1a);
            reaction1.Reactants.Add(mol1b);
            reaction1.Products.Add(builder.NewAtomContainer());
            reaction1.Products.Add(builder.NewAtomContainer());

            IReaction reaction2 = builder.NewReaction();

            reaction2.Reactants.Add(mol1b);
            reaction2.Products.Add(builder.NewAtomContainer());
            set.Add(reaction2);

            IReaction reaction3 = builder.NewReaction();

            reaction3.Reactants.Add(builder.NewAtomContainer());
            reaction3.Products.Add(mol1a);
            set.Add(reaction3);

            Assert.AreEqual(3, set.Count);
            IReactionSet reactionSet2 = ReactionSetManipulator.GetRelevantReactionsAsProduct(set, mol1b);

            Assert.AreEqual(0, reactionSet2.Count);
            IReactionSet reactionSet1 = ReactionSetManipulator.GetRelevantReactionsAsProduct(set, mol1a);

            Assert.AreEqual(1, reactionSet1.Count);
            Assert.AreEqual(reaction3, reactionSet1[0]);
        }
Beispiel #6
0
        /// <summary> Labels the reactants and products in the Reaction m1, m2, etc, and the atoms
        /// accordingly, when no ID is given.
        /// </summary>
        public virtual void createIDs(IReaction reaction)
        {
            if (tabuList == null)
            {
                tabuList = ReactionManipulator.getAllIDs(reaction);
            }

            if (reaction.ID == null)
            {
                reactionCount++;
                while (tabuList.Contains("r" + reactionCount))
                {
                    reactionCount++;
                }
                reaction.ID = "r" + reactionCount;
            }

            IAtomContainer[] reactants = reaction.Reactants.AtomContainers;
            for (int i = 0; i < reactants.Length; i++)
            {
                createIDs(reactants[i]);
            }
            IAtomContainer[] products = reaction.Products.AtomContainers;
            for (int i = 0; i < products.Length; i++)
            {
                createIDs(products[i]);
            }
        }
Beispiel #7
0
 public void SetUp()
 {
     molecule1  = builder.NewAtomContainer();
     atomInMol1 = builder.NewAtom("Cl");
     molecule1.Atoms.Add(atomInMol1);
     molecule1.Atoms.Add(builder.NewAtom("Cl"));
     bondInMol1 = builder.NewBond(atomInMol1, molecule1.Atoms[1]);
     molecule1.Bonds.Add(bondInMol1);
     molecule2  = builder.NewAtomContainer();
     atomInMol2 = builder.NewAtom("O");
     atomInMol2.ImplicitHydrogenCount = 2;
     molecule2.Atoms.Add(atomInMol2);
     moleculeSet = builder.NewChemObjectSet <IAtomContainer>();
     moleculeSet.Add(molecule1);
     moleculeSet.Add(molecule2);
     reaction = builder.NewReaction();
     reaction.Reactants.Add(molecule1);
     reaction.Products.Add(molecule2);
     reactionSet = builder.NewReactionSet();
     reactionSet.Add(reaction);
     chemModel             = builder.NewChemModel();
     chemModel.MoleculeSet = moleculeSet;
     chemModel.ReactionSet = reactionSet;
     chemSequence1         = builder.NewChemSequence();
     chemSequence1.Add(chemModel);
     chemSequence2 = builder.NewChemSequence();
     chemFile      = builder.NewChemFile();
     chemFile.Add(chemSequence1);
     chemFile.Add(chemSequence2);
 }
Beispiel #8
0
        /// <summary> Returns a new Reaction object which is the reverse of the given
        /// Reaction.
        /// </summary>
        public static IReaction reverse(IReaction reaction)
        {
            IReaction reversedReaction = reaction.Builder.newReaction();

            if (reaction.Direction == IReaction_Fields.BIDIRECTIONAL)
            {
                reversedReaction.Direction = IReaction_Fields.BIDIRECTIONAL;
            }
            else if (reaction.Direction == IReaction_Fields.FORWARD)
            {
                reversedReaction.Direction = IReaction_Fields.BACKWARD;
            }
            else if (reaction.Direction == IReaction_Fields.BACKWARD)
            {
                reversedReaction.Direction = IReaction_Fields.FORWARD;
            }
            IMolecule[] reactants = reaction.Reactants.Molecules;
            for (int i = 0; i < reactants.Length; i++)
            {
                double coefficient = reaction.getReactantCoefficient(reactants[i]);
                reversedReaction.addProduct(reactants[i], coefficient);
            }
            IMolecule[] products = reaction.Products.Molecules;
            for (int i = 0; i < products.Length; i++)
            {
                double coefficient = reaction.getProductCoefficient(products[i]);
                reversedReaction.addReactant(products[i], coefficient);
            }
            return(reversedReaction);
        }
Beispiel #9
0
        public void TestCMLReactionList()
        {
            var filename = "NCDK.Data.CML.reactionList.1.cml";

            Trace.TraceInformation("Testing: " + filename);
            var ins      = ResourceLoader.GetAsStream(filename);
            var reader   = new CMLReader(ins);
            var chemFile = reader.Read(builder.NewChemFile());

            reader.Close();

            // test the resulting ChemFile content
            Assert.IsNotNull(chemFile);
            Assert.AreEqual(chemFile.Count, 1);
            var seq = chemFile[0];

            Assert.IsNotNull(seq);
            Assert.AreEqual(1, seq.Count);
            var model = seq[0];

            Assert.IsNotNull(model);
            Assert.AreEqual(2, model.ReactionSet.Count);
            Assert.AreEqual("1.3.2", model.ReactionSet[0].Id);

            // test the reaction
            IReaction reaction = model.ReactionSet[0];

            Assert.IsNotNull(reaction);
            Assert.AreEqual("actey", reaction.Reactants[0].Id);
            Assert.AreEqual("a14293164", reaction.Reactants[0].Atoms[0].Id);
            Assert.AreEqual(6, reaction.Products[0].Atoms.Count);
            Assert.AreEqual(6, reaction.Reactants[0].Atoms.Count);
        }
Beispiel #10
0
 /* !
   \brief Checks that two reactions have the same ATPProducer field values.
   \param reaction The reaction that will be compared to 'this'.
  */
 protected override bool PartialEquals(IReaction reaction)
 {
   ATPProducer producer = reaction as ATPProducer;
   return (producer != null)
   && base.PartialEquals(reaction)
   && (_production == producer._production);
 }
Beispiel #11
0
        public static IReaction RoundTripReaction(Convertor convertor, IReaction reaction)
        {
            string cmlString = "<!-- failed -->";
            var    cmlDOM    = convertor.CDKReactionToCMLReaction(reaction);

            cmlString = cmlDOM.ToString();

            IReaction roundTrippedReaction = null;

            Debug.WriteLine("CML string: ", cmlString);
            CMLReader reader = new CMLReader(new MemoryStream(Encoding.UTF8.GetBytes(cmlString)));

            IChemFile file = (IChemFile)reader.Read(builder.NewChemFile());

            reader.Close();
            Assert.IsNotNull(file);
            Assert.AreEqual(1, file.Count);
            IChemSequence sequence = file[0];

            Assert.IsNotNull(sequence);
            Assert.AreEqual(1, sequence.Count);
            IChemModel chemModel = sequence[0];

            Assert.IsNotNull(chemModel);
            IReactionSet reactionSet = chemModel.ReactionSet;

            Assert.IsNotNull(reactionSet);
            Assert.AreEqual(1, reactionSet.Count);
            roundTrippedReaction = reactionSet[0];
            Assert.IsNotNull(roundTrippedReaction);

            return(roundTrippedReaction);
        }
        protected override void Context()
        {
            base.Context();
            _kinetic  = new ExplicitFormula().WithFormulaString("a+b");
            _reaction = new Reaction().WithName("Ralf Reaction")
                        .WithParentContainer(_root)
                        .WithFormula(_kinetic)
                        .WithId("1")
                        .WithDimension(_reactionDimension);

            _spA = new MoleculeAmount().WithName("SpA").WithParentContainer(_root)
                   .WithId("2")
                   .WithFormula(new ExplicitFormula().WithFormulaString("1"))
                   .WithScaleFactor(1);


            _spB = new MoleculeAmount().WithName("SpB").WithParentContainer(_root)
                   .WithId("3")
                   .WithFormula(new ExplicitFormula().WithFormulaString("0"))
                   .WithScaleFactor(2);

            _reaction.AddEduct(new ReactionPartner(1, _spA));
            _reaction.AddProduct(new ReactionPartner(2, _spB));

            _volume = new Parameter().WithFormula(new ConstantFormula(10)).WithId("4").WithName(Constants.Parameters.VOLUME);
        }
Beispiel #13
0
 /* !
   \brief Checks that two reactions have the same InstantReaction field values.
   \param reaction The reaction that will be compared to 'this'.
  */
 protected override bool PartialEquals(IReaction reaction)
 {
   InstantReaction instant = reaction as InstantReaction;
   return (instant != null)
   && base.PartialEquals(reaction)
   && _reactants.Equals(instant._reactants);
 }
Beispiel #14
0
    /*!
     * \brief Adds an IReaction to a medium
     * \param mediumId The medium ID.
     * \param reaction The reaction to add.
     */
    public void addReactionToMedium(int mediumId, IReaction reaction)
    {
        Logger.Log("ReactionEngine::addReactionToMedium(" + mediumId + ", " + reaction + ")", Logger.Level.INFO);
        Medium med = ReactionEngine.getMediumFromId(mediumId, _mediums);

        if (med == null)
        {
            Logger.Log("ReactionEngine::addReactionToMedium medium #" + mediumId + "not found", Logger.Level.WARN);
            return;
        }

        /*TODO FIXME USEFULNESS?/////////////////////////////////////////////////////////////////////
         * ReactionSet reactionsSet = null;
         * string medName = med.getName()+"Reactions";
         * foreach (ReactionSet rs in _reactionsSets) {
         * if (rs.id == medName) reactionsSet = rs;
         * }
         * if (reactionsSet != null) {
         * reactionsSet.reactions.AddLast(IReaction.copyReaction(reaction));
         * } else {
         * Logger.Log("ReactionEngine::addReactionToMedium reactionsSet == null", Logger.Level.WARN);
         * }
         * //////////////////////////////////////////////////////////////////////////////////////////*/

        med.addReaction(IReaction.copyReaction(reaction));
    }
Beispiel #15
0
        public void TestGetRelevantReaction_IChemModel_IAtom()
        {
            IReaction r = ChemModelManipulator.GetRelevantReaction(chemModel, atomInMol1);

            Assert.IsNotNull(r);
            Assert.AreEqual(reaction, r);
        }
Beispiel #16
0
        /// <summary>
        /// Labels the reactants and products in the Reaction m1, m2, etc, and the atoms
        /// accordingly, when no ID is given.
        /// </summary>
        private static void CreateIDsForReaction(IReaction reaction, List <string> tabuList)
        {
            if (tabuList == null)
            {
                tabuList = ReactionManipulator.GetAllIDs(reaction).ToList();
            }

            if (null == reaction.Id)
            {
                // generate new ID
                reactionCount = SetId(REACTION_PREFIX, reactionCount, reaction, tabuList);
            }

            if (policy == UniquePolicy.Object)
            {
                // start atom and bond indices within a reaction set always from 1
                atomCount = 0;
                bondCount = 0;
            }

            foreach (var reactant in reaction.Reactants)
            {
                CreateIDsForAtomContainer(reactant, tabuList);
            }
            foreach (var product in reaction.Reactants)
            {
                CreateIDsForAtomContainer(product, tabuList);
            }
            foreach (var agent in reaction.Agents)
            {
                CreateIDsForAtomContainer(agent, tabuList);
            }
        }
Beispiel #17
0
  /*!
    \brief Adds an IReaction to a medium
    \param mediumId The medium ID.
    \param reaction The reaction to add.
   */
  public void addReactionToMedium(int mediumId, IReaction reaction)
  {
	Logger.Log("ReactionEngine::addReactionToMedium("+mediumId+", "+reaction+")", Logger.Level.INFO);
    Medium med = ReactionEngine.getMediumFromId(mediumId, _mediums);

    if (med == null) {
	  Logger.Log("ReactionEngine::addReactionToMedium medium #"+mediumId+"not found", Logger.Level.WARN);
      return ;
	}
	
	/*TODO FIXME USEFULNESS?/////////////////////////////////////////////////////////////////////
	ReactionSet reactionsSet = null;
	string medName = med.getName()+"Reactions";
	foreach (ReactionSet rs in _reactionsSets) {
	  if (rs.id == medName) reactionsSet = rs;
	}
	if (reactionsSet != null) {
	  reactionsSet.reactions.AddLast(IReaction.copyReaction(reaction));
	} else {
	  Logger.Log("ReactionEngine::addReactionToMedium reactionsSet == null", Logger.Level.WARN);
	}
	//////////////////////////////////////////////////////////////////////////////////////////*/
		
    med.addReaction(IReaction.copyReaction(reaction));
  }
Beispiel #18
0
 public void SetUp()
 {
     molecule1  = new AtomContainer();
     atomInMol1 = new Atom("Cl")
     {
         Charge                = -1.0,
         FormalCharge          = -1,
         ImplicitHydrogenCount = 1
     };
     molecule1.Atoms.Add(atomInMol1);
     molecule1.Atoms.Add(new Atom("Cl"));
     bondInMol1 = new Bond(atomInMol1, molecule1.Atoms[1]);
     molecule1.Bonds.Add(bondInMol1);
     molecule2  = new AtomContainer();
     atomInMol2 = new Atom("O")
     {
         ImplicitHydrogenCount = 2
     };
     molecule2.Atoms.Add(atomInMol2);
     moleculeSet = ChemObjectBuilder.Instance.NewAtomContainerSet();
     moleculeSet.Add(molecule1);
     moleculeSet.Add(molecule2);
     reaction = new Reaction();
     reaction.Reactants.Add(molecule1);
     reaction.Products.Add(molecule2);
     reactionSet = new ReactionSet
     {
         reaction
     };
     chemModel = new ChemModel
     {
         MoleculeSet = moleculeSet,
         ReactionSet = reactionSet
     };
 }
        protected override void Context()
        {
            _reactionMapper      = A.Fake <IReactionBuilderToReactionMapper>();
            _keywordReplacerTask = A.Fake <IKeywordReplacerTask>();
            _containerTask       = A.Fake <IContainerTask>();
            _parameterMapper     = A.Fake <IParameterBuilderCollectionToParameterCollectionMapper>();

            sut = new ReactionCreator(_reactionMapper, _keywordReplacerTask, _containerTask, _parameterMapper);

            _model           = A.Fake <IModel>();
            _reactionBuilder = A.Fake <IReactionBuilder>();
            _reactionBuilder.ContainerCriteria = new DescriptorCriteria();
            _reactionBuilder.Description       = "A great description";
            _reactionBuilder.Name = "Reaction";
            _educt1 = A.Fake <IReactionPartnerBuilder>();
            _educt1.MoleculeName = "sp1";
            _educt2 = A.Fake <IReactionPartnerBuilder>();
            _educt2.MoleculeName   = "sp2";
            _product1              = A.Fake <IReactionPartnerBuilder>();
            _product1.MoleculeName = "sp3";
            A.CallTo(() => _reactionBuilder.Educts).Returns(new[] { _educt1, _educt2 });
            A.CallTo(() => _reactionBuilder.Products).Returns(new[] { _product1 });
            A.CallTo(() => _reactionBuilder.ModifierNames).Returns(new[] { "modifier" });

            _buildConfiguration = A.Fake <IBuildConfiguration>();
            _rootContainer      = new Container().WithMode(ContainerMode.Physical);
            _model.Root         = _rootContainer;
            _globalContainer    = new Container();

            _reaction = A.Fake <IReaction>().WithName(_reactionBuilder.Name);
            A.CallTo(() => _reactionMapper.MapFromLocal(A <IReactionBuilder> ._, A <IContainer> ._, _buildConfiguration)).Returns(_reaction);
            A.CallTo(() => _containerTask.CreateOrRetrieveSubContainerByName(_rootContainer, _reactionBuilder.Name)).Returns(_globalContainer);
        }
Beispiel #20
0
        // Main function that gets triggered when a player reacts to their gamemessage
        internal async Task HandleReaction(IUserMessage socketMsg, IReaction reaction)
        {
            switch (_gamestate)
            {
            case (GameStates.StartPage):
                await HandleStartPageInput(socketMsg, reaction);

                break;

            case (GameStates.ChangingCategory):
                HandleSelectCategoryInput(socketMsg, reaction);
                break;

            case (GameStates.Playing):
                await HandlePlayingInput(socketMsg, reaction);

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            // Actually update the message with all the information we set
            // in the cases depending on the gamestate
            await UpdateMessage(socketMsg);
        }
Beispiel #21
0
 public static void PerceiveDativeBonds(IReaction reaction)
 {
     foreach (var mol in ReactionManipulator.GetAllMolecules(reaction))
     {
         AtomContainerManipulator.PerceiveDativeBonds(mol);
     }
 }
Beispiel #22
0
        public static void RemoveAtomAndConnectedElectronContainers(IReaction reaction, IAtom atom)
        {
            var reactants = reaction.Reactants;

            for (int i = 0; i < reactants.Count; i++)
            {
                IAtomContainer mol = reactants[i];
                if (mol.Contains(atom))
                {
                    mol.RemoveAtom(atom);
                }
            }
            var agents = reaction.Reactants;

            for (int i = 0; i < agents.Count; i++)
            {
                var mol = agents[i];
                if (mol.Contains(atom))
                {
                    mol.RemoveAtom(atom);
                }
            }
            var products = reaction.Products;

            for (int i = 0; i < products.Count; i++)
            {
                var mol = products[i];
                if (mol.Contains(atom))
                {
                    mol.RemoveAtom(atom);
                }
            }
        }
Beispiel #23
0
        public static IEnumerable <string> GetAllIDs(IReaction reaction)
        {
            if (reaction.Id != null)
            {
                yield return(reaction.Id);
            }
            var reactants = reaction.Reactants;

            for (int i = 0; i < reactants.Count; i++)
            {
                var mol = reactants[i];
                foreach (var id in AtomContainerManipulator.GetAllIDs(mol))
                {
                    yield return(id);
                }
            }
            var products = reaction.Products;

            for (int i = 0; i < products.Count; i++)
            {
                var mol = products[i];
                foreach (var id in AtomContainerManipulator.GetAllIDs(mol))
                {
                    yield return(id);
                }
            }
            yield break;
        }
Beispiel #24
0
        /// <summary>
        /// Converts a reaction to an 'inlined' reaction stored as a molecule. All
        /// reactants, agents, products are added to the molecule as disconnected
        /// components with atoms flagged as to their role <see cref="ReactionRole"/> and
        /// component group.
        /// </summary>
        /// <remarks>
        /// The inlined reaction, stored in a molecule can be converted back to an explicit
        /// reaction with <see cref="ToReaction(IAtomContainer)"/>. Data stored on the individual components (e.g.
        /// titles is lost in the conversion).
        /// </remarks>
        /// <param name="rxn">reaction to convert</param>
        /// <returns>inlined reaction stored in a molecule</returns>
        /// <seealso cref="ToReaction(IAtomContainer)"/>
        public static IAtomContainer ToMolecule(IReaction rxn)
        {
            if (rxn == null)
            {
                throw new ArgumentNullException(nameof(rxn), "Null reaction provided");
            }
            var bldr = rxn.Builder;
            var mol  = bldr.NewAtomContainer();

            mol.SetProperties(rxn.GetProperties());
            mol.Id = rxn.Id;
            int grpId = 0;

            foreach (IAtomContainer comp in rxn.Reactants)
            {
                AssignRoleAndGroup(comp, ReactionRole.Reactant, ++grpId);
                mol.Add(comp);
            }
            foreach (IAtomContainer comp in rxn.Agents)
            {
                AssignRoleAndGroup(comp, ReactionRole.Agent, ++grpId);
                mol.Add(comp);
            }
            foreach (IAtomContainer comp in rxn.Products)
            {
                AssignRoleAndGroup(comp, ReactionRole.Product, ++grpId);
                mol.Add(comp);
            }
            return(mol);
        }
Beispiel #25
0
        /// <summary>
        /// Returns a new Reaction object which is the reverse of the given
        /// Reaction.
        /// </summary>
        /// <param name="reaction">the reaction being considered</param>
        /// <returns>the reverse reaction</returns>
        public static IReaction Reverse(IReaction reaction)
        {
            var reversedReaction = reaction.Builder.NewReaction();

            if (reaction.Direction == ReactionDirection.Bidirectional)
            {
                reversedReaction.Direction = ReactionDirection.Bidirectional;
            }
            else if (reaction.Direction == ReactionDirection.Forward)
            {
                reversedReaction.Direction = ReactionDirection.Backward;
            }
            else if (reaction.Direction == ReactionDirection.Backward)
            {
                reversedReaction.Direction = ReactionDirection.Forward;
            }
            var reactants = reaction.Reactants;

            for (int i = 0; i < reactants.Count; i++)
            {
                double coefficient = reaction.Reactants.GetMultiplier(reactants[i]).Value;
                reversedReaction.Products.Add(reactants[i], coefficient);
            }
            var products = reaction.Products;

            for (int i = 0; i < products.Count; i++)
            {
                double coefficient = reaction.Products.GetMultiplier(products[i]).Value;
                reversedReaction.Reactants.Add(products[i], coefficient);
            }
            return(reversedReaction);
        }
Beispiel #26
0
        public static void RemoveElectronContainer(IReaction reaction, IElectronContainer electrons)
        {
            var reactants = reaction.Reactants;

            for (int i = 0; i < reactants.Count; i++)
            {
                IAtomContainer mol = reactants[i];
                if (mol.Contains(electrons))
                {
                    mol.Remove(electrons);
                }
            }
            var agents = reaction.Reactants;

            for (int i = 0; i < agents.Count; i++)
            {
                var mol = agents[i];
                if (mol.Contains(electrons))
                {
                    mol.Remove(electrons);
                }
            }
            var products = reaction.Products;

            for (int i = 0; i < products.Count; i++)
            {
                var mol = products[i];
                if (mol.Contains(electrons))
                {
                    mol.Remove(electrons);
                }
            }
        }
        public void TestGetMappedChemObject_IReaction_IBond()
        {
            var            builder  = ChemObjectBuilder.Instance;
            IReaction      reaction = builder.NewReaction();
            IAtomContainer reactant = CDK.SmilesParser.ParseSmiles("[C+]-C=C");
            IAtomContainer product  = CDK.SmilesParser.ParseSmiles("C=C=C");

            IMapping mapping = builder.NewMapping(reactant.Atoms[0], product.Atoms[0]);

            reaction.Mappings.Add(mapping);
            mapping = builder.NewMapping(reactant.Bonds[0], product.Bonds[0]);
            reaction.Mappings.Add(mapping);
            mapping = builder.NewMapping(reactant.Bonds[1], product.Bonds[1]);
            reaction.Mappings.Add(mapping);

            reaction.Reactants.Add(reactant);
            reaction.Products.Add(product);

            IBond mappedBond = (IBond)ReactionManipulator.GetMappedChemObject(reaction, reactant.Bonds[0]);

            Assert.AreEqual(mappedBond, product.Bonds[0]);

            mappedBond = (IBond)ReactionManipulator.GetMappedChemObject(reaction, product.Bonds[1]);
            Assert.AreEqual(mappedBond, reactant.Bonds[1]);
        }
Beispiel #28
0
        public void TestShiftReactionVerticalIAtomContainerRectangle2DRectangle2DDouble()
        {
            var atom1 = builder.NewAtom("C");

            atom1.Point2D = new Vector2(0, 1);
            var atom2 = builder.NewAtom("C");

            atom2.Point2D = new Vector2(1, 0);
            var react1   = builder.NewAtomContainer();
            var reaction = builder.NewReaction();

            reaction.Reactants.Add(react1);
            react1.Atoms.Add(atom1);
            react1.Atoms.Add(atom2);
            react1.AddBond(react1.Atoms[0], react1.Atoms[1], BondOrder.Single);
            IReaction      reaction2 = (IReaction)reaction.Clone();
            IAtomContainer react2    = reaction2.Reactants[0];

            // shift the second reaction up
            GeometryUtil.ShiftReactionVertical(reaction2, GeometryUtil.GetMinMax(react2), GeometryUtil.GetMinMax(react1),
                                               1.0);
            // assert all coordinates of the second reaction moved up
            AtomContainerDiff.Diff(react1, react2);
            for (int i = 0; i < 2; i++)
            {
                atom1 = react1.Atoms[0];
                atom2 = react2.Atoms[0];
                // so, x coordinates should be the same
                Assert.AreEqual(atom1.Point2D.Value.X, atom2.Point2D.Value.X, 0.0);
                // but, y coordinates should not
                Assert.IsTrue(atom1.Point2D.Value.Y < atom2.Point2D.Value.Y);
            }
        }
Beispiel #29
0
        public virtual void TestInitiate_IAtomContainerSet_IAtomContainerSet()
        {
            EntryReact entry   = (EntryReact)dictionary[entryString.ToLowerInvariant()];
            var        xmlList = entry.ExampleReactions;

            Assert.IsTrue(xmlList.Count != 0, "The representation entry for [" + entryString
                          + "]  must contain at least one example of reaction.");
            Assert.IsTrue(xmlList.Count > 0, "The representation entry for [" + entryString
                          + "]  must contain at least one example of reaction.");
            foreach (var xml in xmlList)
            {
                CMLReader reader       = new CMLReader(new MemoryStream(Encoding.UTF8.GetBytes(xml)));
                var       chemFile     = (IChemFile)reader.Read(builder.NewChemFile());
                IReaction reactionDict = chemFile[0][0].ReactionSet[0];

                var reactants = reactionDict.Reactants;
                var agents    = reactionDict.Agents;
                var products  = reactionDict.Products;
                if (agents.Count == 0)
                {
                    agents = null;
                }

                IReactionSet reactions = reaction.Initiate(reactants, agents);

                Assert.IsTrue(reactions.Count > 0, "The products for [" + entryString + "] reaction is at least one reaction expected.");

                Assert.AreEqual(products[0].Atoms.Count,
                                reactions[0].Products[0].Atoms.Count,
                                "The products for [" + entryString + "] reaction is not the expected.");
            }
        }
        /// <summary>
        /// Calculate the average bond length for the bonds in a reaction.
        /// </summary>
        /// <param name="reaction">the reaction to use</param>
        /// <returns>the average bond length</returns>
        public static double CalculateAverageBondLength(IReaction reaction)
        {
            var    reactants       = reaction.Reactants;
            double reactantAverage = 0.0;

            if (reactants != null)
            {
                reactantAverage = CalculateAverageBondLength(reactants) / reactants.Count;
            }

            var    products       = reaction.Products;
            double productAverage = 0.0;

            if (products != null)
            {
                productAverage = CalculateAverageBondLength(products) / products.Count;
            }

            if (productAverage == 0.0 && reactantAverage == 0.0)
            {
                return(1.0);
            }
            else
            {
                return((productAverage + reactantAverage) / 2.0);
            }
        }
        internal IReactionSet Initiate(IChemObjectSet <IAtomContainer> reactants, IChemObjectSet <IAtomContainer> agents, BondCheck bondChecker)
        {
            CheckInitiateParams(reactants, agents);

            IReactionSet   setOfReactions = reactants.Builder.NewReactionSet();
            IAtomContainer reactant       = reactants[0];

            // if the parameter hasActiveCenter is not fixed yet, set the active centers
            IParameterReaction ipr = base.GetParameterClass(typeof(SetReactionCenter));

            if (ipr != null && !ipr.IsSetParameter)
            {
                SetActiveCenters(reactant, bondChecker);
            }
            foreach (var bondi in reactant.Bonds)
            {
                IAtom atom1 = bondi.Begin;
                IAtom atom2 = bondi.End;
                if (bondi.IsReactiveCenter &&
                    bondChecker(bondi) &&
                    atom1.IsReactiveCenter && atom2.IsReactiveCenter &&
                    (atom1.FormalCharge ?? 0) == 0 &&
                    (atom2.FormalCharge ?? 0) == 0 &&
                    !reactant.GetConnectedSingleElectrons(atom1).Any() &&
                    !reactant.GetConnectedSingleElectrons(atom2).Any())
                {
                    for (int j = 0; j < 2; j++)
                    {
                        var atomList = new List <IAtom>();
                        if (j == 0)
                        {
                            atomList.Add(atom1);
                            atomList.Add(atom2);
                        }
                        else
                        {
                            atomList.Add(atom2);
                            atomList.Add(atom1);
                        }
                        var bondList = new List <IBond>
                        {
                            bondi
                        };

                        IChemObjectSet <IAtomContainer> moleculeSet = reactant.Builder.NewAtomContainerSet();
                        moleculeSet.Add(reactant);
                        IReaction reaction = Mechanism.Initiate(moleculeSet, atomList, bondList);
                        if (reaction == null)
                        {
                            continue;
                        }
                        else
                        {
                            setOfReactions.Add(reaction);
                        }
                    }
                }
            }
            return(setOfReactions);
        }
Beispiel #32
0
        /// <summary>
        /// Handles behaviour on reactions while in the startpage gamestate
        /// </summary>
        private async Task HandleStartPageInput(IUserMessage socketMsg, IReaction reaction)
        {
            var reactionName = reaction.Emote.Name;

            // If the player wants to change the category
            if (reactionName == _triviaGames.ReactOptions["1"].Name)
            {
                socketMsg.AddReactionAsync(_triviaGames.ReactOptions["left"]);
                socketMsg.AddReactionAsync(_triviaGames.ReactOptions["right"]);
                PrepareCategoryEmb();
                _gamestate = GameStates.ChangingCategory;
                return;
            }
            // If the player wants to change the questiontype
            if (reactionName == _triviaGames.ReactOptions["2"].Name)
            {
                // Take the current type and use set it to the next one
                var index = _triviaGames.QuestionTypes.ToList().FindIndex(q => QuestionType == q.Key);
                QuestionType = _triviaGames.QuestionTypes.ToList()[(index + 1) % _triviaGames.QuestionTypes.Count].Key;
                PrepareStartMenue(socketMsg);
            }
            // If the player wants to change the difficulty
            else if (reactionName == _triviaGames.ReactOptions["3"].Name)
            {
                // Take the current difficulty and use set it to the next one
                var index = _triviaGames.Difficulties.ToList().FindIndex(q => Difficulty == q.Key);
                Difficulty = _triviaGames.Difficulties.ToList()[(index + 1) % _triviaGames.Difficulties.Count].Key;
                PrepareStartMenue(socketMsg);
            }
            // If the player wants to start the game
            if (reactionName == _triviaGames.ReactOptions["ok"].Name)
            {
                await PreparePlayEmb(socketMsg, reaction);
            }
        }
        /// <summary>
        /// Clone and Sort the mappings based on the order of the first object
        /// in the mapping (which is assumed to be the reactant).
        /// </summary>
        /// <param name="reaction"></param>
        private static void CloneAndSortMappings(IReaction reaction, IReaction copyOfReaction,
            IReadOnlyDictionary<IAtomContainer, int[]> permutationMap)
        {
            // make a lookup for the indices of the atoms in the copy
            var indexMap = new Dictionary<IChemObject, int>();
            var all = ReactionManipulator.GetAllAtomContainers(copyOfReaction);
            int globalIndex = 0;
            foreach (var ac in all)
            {
                foreach (var atom in ac.Atoms)
                {
                    indexMap[atom] = globalIndex;
                    globalIndex++;
                }
            }

            var atomAtomMap = AtomAtomMap(reaction, copyOfReaction, permutationMap);
            var map = CloneMappings(reaction, atomAtomMap);

            var mappingSorter = new MappingSorter(indexMap);
            map.Sort(mappingSorter);
            int mappingIndex = 0;
            foreach (var mapping in map)
            {
                mapping[0].SetProperty(CDKPropertyName.AtomAtomMapping, mappingIndex);
                mapping[1].SetProperty(CDKPropertyName.AtomAtomMapping, mappingIndex);
                copyOfReaction.Mappings.Add(mapping);
                mappingIndex++;
            }
        }
Beispiel #34
0
 /* !
   \brief Checks that two reactions have the same Degradation field values.
   \param reaction The reaction that will be compared to 'this'.
  */
 protected override bool PartialEquals(IReaction reaction)
 {
   Degradation degradation = reaction as Degradation;
   return (degradation != null)
     && base.PartialEquals(reaction)
     && (_degradationRate == degradation._degradationRate)
     && (_molName == degradation._molName);
 }
Beispiel #35
0
 /*!
 \brief Add a new reaction to the medium
 \param reaction The reaction to add.
    */
 public void addReaction(IReaction reaction)
 {
     if (reaction != null)
       {
     reaction.setMedium(this);
     reaction.enableEnergy = _enableEnergy;
     _reactions.AddLast(reaction);
       }
     else
       Debug.Log("Cannot add this reaction because null was given");
 }
Beispiel #36
0
 /* !
   \brief Checks that two reactions have the same FickReaction field values.
   \param reaction The reaction that will be compared to 'this'.
  */
 protected override bool PartialEquals(IReaction reaction)
 {
   FickReaction fick = reaction as FickReaction;
   return (fick != null)
     && base.PartialEquals(reaction)
     && (_surface == fick._surface)
     && (_P       == fick._P)
     && _medium1.Equals(fick._medium1)
     && _medium2.Equals(fick._medium2);
   //TODO check Medium equality
 }
Beispiel #37
0
 //! Copy Constructor
 public IReaction(IReaction r)
 {
   _products = new LinkedList<Product>();
   foreach(Product p in r._products)
     _products.AddLast(p);
     _isActive = r._isActive;
     _reactionSpeed = r._reactionSpeed;
     _energyCost = r._energyCost;
     enableSequential = r.enableSequential;
     enableEnergy = r.enableEnergy;
     _medium = r._medium;
 }
 public static int getBondCount(IReaction reaction)
 {
     int count = 0;
     IMolecule[] reactants = reaction.Reactants.Molecules;
     for (int i = 0; i < reactants.Length; i++)
     {
         count += reactants[i].getBondCount();
     }
     IMolecule[] products = reaction.Products.Molecules;
     for (int i = 0; i < products.Length; i++)
     {
         count += products[i].getBondCount();
     }
     return count;
 }
Beispiel #39
0
 /*!
   \brief This function copies a reaction by calling its real copy constructor
   (not IReaction constructor but for example PromoterReaction constructor)
   \param r Reaction to copy
   \return Return a reference on the new reaction or null if the given reaction is unknown.
  */
 public static IReaction       copyReaction(IReaction r)
 {
   if (r as PromoterReaction != null)
     return new PromoterReaction(r as PromoterReaction);
   if (r as Allostery != null)
     return new Allostery(r as Allostery);
   if (r as InstantReaction != null)
     return new InstantReaction(r as InstantReaction);
   if (r as EnzymeReaction != null)
     return new EnzymeReaction(r as EnzymeReaction);
   if (r as ActiveTransportReaction != null)
     return new ActiveTransportReaction(r as ActiveTransportReaction);
   if (r as FickReaction != null)
     return new FickReaction(r as FickReaction);
   if (r as ATPProducer != null)
     return new ATPProducer(r as ATPProducer);
   if (r as Degradation != null)
     return new Degradation(r as Degradation);
   return null;
 }
 public static void removeAtomAndConnectedElectronContainers(IReaction reaction, IAtom atom)
 {
     IMolecule[] reactants = reaction.Reactants.Molecules;
     for (int i = 0; i < reactants.Length; i++)
     {
         IMolecule mol = reactants[i];
         if (mol.contains(atom))
         {
             mol.removeAtomAndConnectedElectronContainers(atom);
         }
     }
     IMolecule[] products = reaction.Products.Molecules;
     for (int i = 0; i < products.Length; i++)
     {
         IMolecule mol = products[i];
         if (mol.contains(atom))
         {
             mol.removeAtomAndConnectedElectronContainers(atom);
         }
     }
 }
Beispiel #41
0
 /// <summary> Procedure required by the CDOInterface. This function is only
 /// supposed to be called by the JCFL library
 /// </summary>
 public virtual void startObject(System.String objectType)
 {
     //logger.debug("START:" + objectType);
     if (objectType.Equals("Molecule"))
     {
         if (currentChemModel == null)
             currentChemModel = currentChemFile.Builder.newChemModel();
         if (currentSetOfMolecules == null)
             currentSetOfMolecules = currentChemFile.Builder.newSetOfMolecules();
         currentMolecule = currentChemFile.Builder.newMolecule();
     }
     else if (objectType.Equals("Atom"))
     {
         currentAtom = currentChemFile.Builder.newAtom("H");
         //logger.debug("Atom # " + numberOfAtoms);
         numberOfAtoms++;
     }
     else if (objectType.Equals("Bond"))
     {
         bond_id = null;
         bond_stereo = -99;
     }
     else if (objectType.Equals("Animation"))
     {
         currentChemSequence = currentChemFile.Builder.newChemSequence();
     }
     else if (objectType.Equals("Frame"))
     {
         currentChemModel = currentChemFile.Builder.newChemModel();
     }
     else if (objectType.Equals("SetOfMolecules"))
     {
         currentSetOfMolecules = currentChemFile.Builder.newSetOfMolecules();
         currentMolecule = currentChemFile.Builder.newMolecule();
     }
     else if (objectType.Equals("Crystal"))
     {
         currentMolecule = currentChemFile.Builder.newCrystal(currentMolecule);
     }
     else if (objectType.Equals("a-axis") || objectType.Equals("b-axis") || objectType.Equals("c-axis"))
     {
         crystal_axis_x = 0.0;
         crystal_axis_y = 0.0;
         crystal_axis_z = 0.0;
     }
     else if (objectType.Equals("SetOfReactions"))
     {
         currentSetOfReactions = currentChemFile.Builder.newSetOfReactions();
     }
     else if (objectType.Equals("Reaction"))
     {
         if (currentSetOfReactions == null)
             startObject("SetOfReactions");
         currentReaction = currentChemFile.Builder.newReaction();
     }
     else if (objectType.Equals("Reactant"))
     {
         if (currentReaction == null)
             startObject("Reaction");
         currentMolecule = currentChemFile.Builder.newMolecule();
     }
     else if (objectType.Equals("Product"))
     {
         if (currentReaction == null)
             startObject("Reaction");
         currentMolecule = currentChemFile.Builder.newMolecule();
     }
 }
 /// <summary>  Generate a SMILES for the given <code>Reaction</code>.
 /// 
 /// </summary>
 /// <param name="reaction">         Description of the Parameter
 /// </param>
 /// <returns>                   Description of the Return Value
 /// </returns>
 /// <exception cref="CDKException"> Description of the Exception
 /// </exception>
 //UPGRADE_NOTE: Synchronized keyword was removed from method 'createSMILES'. Lock expression was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1027'"
 public virtual System.String createSMILES(IReaction reaction)
 {
     lock (this)
     {
         System.Text.StringBuilder reactionSMILES = new System.Text.StringBuilder();
         IMolecule[] reactants = reaction.Reactants.Molecules;
         for (int i = 0; i < reactants.Length; i++)
         {
             reactionSMILES.Append(createSMILES(reactants[i]));
             if (i + 1 < reactants.Length)
             {
                 reactionSMILES.Append('.');
             }
         }
         reactionSMILES.Append('>');
         IMolecule[] agents = reaction.Agents.Molecules;
         for (int i = 0; i < agents.Length; i++)
         {
             reactionSMILES.Append(createSMILES(agents[i]));
             if (i + 1 < agents.Length)
             {
                 reactionSMILES.Append('.');
             }
         }
         reactionSMILES.Append('>');
         IMolecule[] products = reaction.Products.Molecules;
         for (int i = 0; i < products.Length; i++)
         {
             reactionSMILES.Append(createSMILES(products[i]));
             if (i + 1 < products.Length)
             {
                 reactionSMILES.Append('.');
             }
         }
         return reactionSMILES.ToString();
     }
 }
Beispiel #43
0
  /* !
    \brief Checks that two reactions have the same IReaction field values
    except for medium
    \param reaction The reaction that will be compared to 'this'.
   */
  protected virtual bool PartialEquals(IReaction reaction)
  {
    //TODO check this
        /*
    if(!hasValidData() || !reaction.hasValidData())
    {
        Logger.Log("IReaction::PartialEquals invalid reaction"
                   , Logger.Level.ERROR);
        return false;
    }
    */

    bool res =
         LinkedListExtensions.Equals(_products,reaction._products)
      && (_isActive        == reaction._isActive)
      && (_reactionSpeed   == reaction._reactionSpeed)
      && (_energyCost      == reaction._energyCost)
      && (enableSequential == reaction.enableSequential)
      && (enableEnergy     == reaction.enableEnergy)
      ;

    return res;
  }
Beispiel #44
0
 /* !
   \brief Checks that two reactions are equal.
   \param reaction The reaction that will be compared to 'this'.
   \param nameMustMatch Whether the name must be taken into account or not.
  */
 public bool Equals(IReaction reaction, bool checkNameAndMedium)
 {
   if(checkNameAndMedium)
   {
     return Equals (reaction);
   }
   return PartialEquals(reaction);
 }
 /// <summary> Returns a new Reaction object which is the reverse of the given
 /// Reaction.
 /// </summary>
 public static IReaction reverse(IReaction reaction)
 {
     IReaction reversedReaction = reaction.Builder.newReaction();
     if (reaction.Direction == IReaction_Fields.BIDIRECTIONAL)
     {
         reversedReaction.Direction = IReaction_Fields.BIDIRECTIONAL;
     }
     else if (reaction.Direction == IReaction_Fields.FORWARD)
     {
         reversedReaction.Direction = IReaction_Fields.BACKWARD;
     }
     else if (reaction.Direction == IReaction_Fields.BACKWARD)
     {
         reversedReaction.Direction = IReaction_Fields.FORWARD;
     }
     IMolecule[] reactants = reaction.Reactants.Molecules;
     for (int i = 0; i < reactants.Length; i++)
     {
         double coefficient = reaction.getReactantCoefficient(reactants[i]);
         reversedReaction.addProduct(reactants[i], coefficient);
     }
     IMolecule[] products = reaction.Products.Molecules;
     for (int i = 0; i < products.Length; i++)
     {
         double coefficient = reaction.getProductCoefficient(products[i]);
         reversedReaction.addReactant(products[i], coefficient);
     }
     return reversedReaction;
 }
    /*!
    \brief Add an IReaction to a medium
    \param mediumId The medium ID.
    \param reaction The reaction to add.
       */
    public void addReactionToMedium(int mediumId, IReaction reaction)
    {
        Medium med = ReactionEngine.getMediumFromId(mediumId, _mediums);

        if (med == null)
          return ;
        med.addReaction(reaction);
    }
 /// <deprecated> This method has a serious performace impact. Try to use
 /// other methods.
 /// </deprecated>
 public static IAtomContainer getAllInOneContainer(IReaction reaction)
 {
     IAtomContainer container = reaction.Builder.newAtomContainer();
     if (reaction == null)
     {
         return container;
     }
     IMolecule[] reactants = reaction.Reactants.Molecules;
     for (int i = 0; i < reactants.Length; i++)
     {
         IMolecule molecule = reactants[i];
         container.add(molecule);
     }
     IMolecule[] products = reaction.Products.Molecules;
     for (int i = 0; i < products.Length; i++)
     {
         IMolecule molecule = products[i];
         container.add(molecule);
     }
     return container;
 }
 /// <summary> get the IAtom which is mapped
 /// 
 /// </summary>
 /// <param name="reaction">  The IReaction which contains the mapping 
 /// </param>
 /// <param name="chemObject">The IChemObject which will be searched its mapped IChemObject
 /// </param>
 /// <returns>           The mapped IChemObject
 /// </returns>
 public static IChemObject getMappedChemObject(IReaction reaction, IChemObject chemObject)
 {
     IMapping[] mappings = reaction.Mappings;
     for (int i = 0; i < mappings.Length; i++)
     {
         IMapping mapping = mappings[i];
         IChemObject[] map = mapping.RelatedChemObjects;
         if (map[0].Equals(chemObject))
         {
             return map[1];
         }
         else if (map[1].Equals(chemObject))
             return map[0];
     }
     return null;
 }
 public static System.Collections.IList getAllChemObjects(IReaction reaction)
 {
     System.Collections.ArrayList list = new System.Collections.ArrayList();
     IMolecule[] reactants = reaction.Reactants.Molecules;
     for (int i = 0; i < reactants.Length; i++)
     {
         list.Add(reactants[i]);
     }
     IMolecule[] products = reaction.Products.Molecules;
     for (int i = 0; i < products.Length; i++)
     {
         list.Add(products[i]);
     }
     return list;
 }
 public static void setAtomProperties(IReaction reaction, System.Object propKey, System.Object propVal)
 {
     IMolecule[] reactants = reaction.Reactants.Molecules;
     for (int j = 0; j < reactants.Length; j++)
     {
         AtomContainerManipulator.setAtomProperties(reactants[j], propKey, propVal);
     }
     IMolecule[] products = reaction.Products.Molecules;
     for (int j = 0; j < products.Length; j++)
     {
         AtomContainerManipulator.setAtomProperties(products[j], propKey, propVal);
     }
 }
 public static IAtomContainer getRelevantAtomContainer(IReaction reaction, IBond bond)
 {
     IAtomContainer result = SetOfMoleculesManipulator.getRelevantAtomContainer(reaction.Reactants, bond);
     if (result != null)
     {
         return result;
     }
     return SetOfMoleculesManipulator.getRelevantAtomContainer(reaction.Products, bond);
 }
 public static System.Collections.ArrayList getAllIDs(IReaction reaction)
 {
     System.Collections.ArrayList idList = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
     if (reaction.ID != null)
         idList.Add(reaction.ID);
     IMolecule[] reactants = reaction.Reactants.Molecules;
     for (int i = 0; i < reactants.Length; i++)
     {
         IMolecule mol = reactants[i];
         idList.AddRange(AtomContainerManipulator.getAllIDs(mol));
     }
     IMolecule[] products = reaction.Products.Molecules;
     for (int i = 0; i < products.Length; i++)
     {
         IMolecule mol = products[i];
         idList.AddRange(AtomContainerManipulator.getAllIDs(mol));
     }
     return idList;
 }
 /// <summary> Returns all the AtomContainer's of a Reaction.</summary>
 public static IAtomContainer[] getAllAtomContainers(IReaction reaction)
 {
     return SetOfMoleculesManipulator.getAllAtomContainers(getAllMolecules(reaction));
 }
Beispiel #54
0
        //protected internal LoggingTool logger;

        /// <summary> Basic contructor</summary>
        public ChemFileCDO(IChemFile file)
        {
            //logger = new LoggingTool(this);
            currentChemFile = file;
            currentChemSequence = file.Builder.newChemSequence();
            currentChemModel = file.Builder.newChemModel();
            currentSetOfMolecules = file.Builder.newSetOfMolecules();
            currentSetOfReactions = null;
            currentReaction = null;
            currentMolecule = file.Builder.newMolecule();
            atomEnumeration = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
        }
Beispiel #55
0
  /* !
    \brief Remove from the specified medium the reaction that has the same characteristics as the one given as parameter
    \param mediumId The Id of the medium to remove from.
    \param reaction The model of reaction to remove.
    \param checkNameAndMedium Whether the name and medium must be taken into account or not.
   */
  public void removeReaction(int mediumId, IReaction reaction, bool checkNameAndMedium = false)
  {
    Medium med = ReactionEngine.getMediumFromId(mediumId, _mediums);

    if (med == null)
    {
      Logger.Log("ReactionEngine::removeReaction could not find medium with id "+mediumId, Logger.Level.WARN);
      return ;
    }

    med.removeReaction(reaction, checkNameAndMedium);
  }
 public static void removeElectronContainer(IReaction reaction, IElectronContainer electrons)
 {
     IMolecule[] reactants = reaction.Reactants.Molecules;
     for (int i = 0; i < reactants.Length; i++)
     {
         IMolecule mol = reactants[i];
         if (mol.contains(electrons))
         {
             mol.removeElectronContainer(electrons);
         }
     }
     IMolecule[] products = reaction.Products.Molecules;
     for (int i = 0; i < products.Length; i++)
     {
         IMolecule mol = products[i];
         if (mol.contains(electrons))
         {
             mol.removeElectronContainer(electrons);
         }
     }
 }
Beispiel #57
0
  /*!
    \brief Add a new reaction to the medium
    \param reaction The reaction to add.
   */
  public void addReaction(IReaction reaction)
  {
    //Logger.Log("Medium::addReaction to medium#"+_numberId+" with "+reaction, Logger.Level.DEBUG);
    if (reaction != null)
    {
      reaction.setMedium(this);
      reaction.enableEnergy = _enableEnergy;
      _reactions.AddLast(reaction);
      //Logger.Log("Medium::addReaction _reactions="+Logger.ToString<IReaction>(_reactions), Logger.Level.DEBUG);
    }
    else
      Logger.Log("Medium::addReaction Cannot add this reaction because null was given", Logger.Level.WARN);

  }
 public static ISetOfMolecules getAllMolecules(IReaction reaction)
 {
     ISetOfMolecules moleculeSet = reaction.Builder.newSetOfMolecules();
     IMolecule[] reactants = reaction.Reactants.Molecules;
     for (int i = 0; i < reactants.Length; i++)
     {
         moleculeSet.addMolecule(reactants[i]);
     }
     IMolecule[] products = reaction.Products.Molecules;
     for (int i = 0; i < products.Length; i++)
     {
         moleculeSet.addMolecule(products[i]);
     }
     return moleculeSet;
 }
Beispiel #59
0
        /// <summary> Labels the reactants and products in the Reaction m1, m2, etc, and the atoms
        /// accordingly, when no ID is given.
        /// </summary>
        public virtual void createIDs(IReaction reaction)
        {
            if (tabuList == null)
                tabuList = ReactionManipulator.getAllIDs(reaction);

            if (reaction.ID == null)
            {
                reactionCount++;
                while (tabuList.Contains("r" + reactionCount))
                    reactionCount++;
                reaction.ID = "r" + reactionCount;
            }

            IAtomContainer[] reactants = reaction.Reactants.AtomContainers;
            for (int i = 0; i < reactants.Length; i++)
            {
                createIDs(reactants[i]);
            }
            IAtomContainer[] products = reaction.Products.AtomContainers;
            for (int i = 0; i < products.Length; i++)
            {
                createIDs(products[i]);
            }
        }
Beispiel #60
0
  /* !
    \brief Remove the reaction that has the same characteristics as the one given as parameter
    \param reaction The model of reaction to remove.
    \param checkNameAndMedium Whether the name  and medium must be taken into account or not.
   */
  public void removeReaction(IReaction reaction, bool checkNameAndMedium)
  {
    LinkedListNode<IReaction> node = _reactions.First;
    bool b = true;

    while (node != null && b)
    {
      if (node.Value.Equals(reaction, checkNameAndMedium))
      {
        _reactions.Remove(node);
        b = false;
      }
      node = node.Next;
    }
    if(b)
      Logger.Log("ReactionEngine::removeReaction failed to find matching reaction", Logger.Level.WARN);
    else
      Logger.Log("ReactionEngine::removeReaction successfully removed matching reaction", Logger.Level.DEBUG);
  }