MoleculeType * NFtest_tlbr::createL(System * s, int count) { vector <string> compName; vector <string> defaultCompState; vector < vector <string> > possibleCompStates; compName.push_back("r0"); defaultCompState.push_back("No State"); vector <string> possibleR0states; possibleCompStates.push_back(possibleR0states); compName.push_back("r1"); defaultCompState.push_back("No State"); vector <string> possibleR1states; possibleCompStates.push_back(possibleR1states); compName.push_back("r2"); defaultCompState.push_back("No State"); vector <string> possibleR2states; possibleCompStates.push_back(possibleR2states); MoleculeType *L = new MoleculeType("L", compName, defaultCompState, possibleCompStates, s); L->populateWithDefaultMolecules(count); return L; }
/*! */ void clearMoleculeComplexIds(System *s) { for(int i=0; i<s->getNumOfMoleculeTypes(); i++) { MoleculeType *mt = s->getMoleculeType(i); for(int j=0; j<mt->getMoleculeCount(); j++) { mt->getMolecule(j)->setComplexID(-1); } } }
std::string formula(const MoleculeType &mol) { // Adapted from chemkit: // A map of atomic symbols to their quantity. std::map<unsigned char, size_t> composition; for (Array<unsigned char>::const_iterator it = mol.atomicNumbers().begin(), itEnd = mol.atomicNumbers().end(); it != itEnd; ++it) { composition[*it]++; } std::stringstream result; std::map<unsigned char, size_t>::iterator iter; // Carbons first iter = composition.find(6); if (iter != composition.end()) { result << "C"; if (iter->second > 1) result << iter->second; composition.erase(iter); // If carbon is present, hydrogens are next. iter = composition.find(1); if (iter != composition.end()) { result << "H"; if (iter->second > 1) result << iter->second; composition.erase(iter); } } // The rest: iter = composition.begin(); while (iter != composition.end()) { result << Avogadro::Core::Elements::symbol(iter->first); if (iter->second > 1) result << iter->second; ++iter; } return result.str(); }
MoleculeType * NFtest_tlbr::createR(System * s, int count) { vector <string> compName; vector <string> defaultCompState; vector < vector <string> > possibleCompStates; compName.push_back("l0"); defaultCompState.push_back("No State"); vector <string> possibleL0states; possibleCompStates.push_back(possibleL0states); compName.push_back("l1"); defaultCompState.push_back("No State"); vector <string> possibleL1states; possibleCompStates.push_back(possibleL1states); MoleculeType *R = new MoleculeType("R", compName, defaultCompState, possibleCompStates, s); R->populateWithDefaultMolecules(count); return R; }
void DumpSystem::dumpHeaderFile(double dumpTime) { string dumpFileName = pathToFolder + s->getName()+"_nf."+Util::toString(dumpTime)+".dump.head"; //cout<<"writing file: "<<dumpFileName<<endl;; ofstream ofs; //ios_base::out -- Set for output only, instead of for input/output //ios_base::trunc -- Truncate the file - that is overwrite anything that was already there ofs.open((dumpFileName).c_str(), ios_base::out | ios_base::trunc); //Make sure we could open the stream (this is really the only thing that can go around) if(!ofs.is_open()) { cout<<"--------"<<endl; cout<<"-Error dumping header file."; cout<<"-Could not open stream to file: '"<<dumpFileName<<"'"<<endl; cout<<"-The path is probably incorrect or does not exist."<<endl; return; } ofs<<"## Automatically generated file from NFsim. Do not edit manually.\n"; ofs<<"## To read this file and the associated information, use the\n"; ofs<<"## included Matlab script readNFdump.m.\n\n"; ofs<<"\n>> Time #######################################\n"; ofs<<dumpTime<<"\n"; ofs<<"\n>> MoleculeTypeDef ############################\n"; ofs<<"##\tindex\tname\tnumOfInstances\tnumOfComponents\n"; for(int i=0; i<s->getNumOfMoleculeTypes(); i++) { MoleculeType *mt = s->getMoleculeType(i); ofs<<"\t"<<i<<"\t"<<mt->getName()<<"\t"<<mt->getMoleculeCount()<<"\t"; ofs<<mt->getNumOfComponents()<<"\t"<<mt->getNumOfTypeIFunctions()<<"\n"; } ofs<<"\n>> MoleculeTypeComponents #####################\n"; ofs<<"##\ttype\tindex\tname\n"; for(int i=0; i<s->getNumOfMoleculeTypes(); i++) { MoleculeType *mt = s->getMoleculeType(i); for(int k=0; k<mt->getNumOfComponents(); k++) { ofs<<"\t"<<i<<"\t"<<k<<"\t"<<mt->getComponentName(k)<<"\n"; } } ofs<<"\n>> MoleculeTypeFunctions ######################\n"; ofs<<"##\ttype\tindex\tname\n"; for(int i=0; i<s->getNumOfMoleculeTypes(); i++) { MoleculeType *mt = s->getMoleculeType(i); for(int k=0; k<mt->getNumOfTypeIFunctions(); k++) { ofs<<"\t"<<i<<"\t"<<k<<"\t"<<mt->getTypeILocalFunction(k)->getName()<<"\n"; } } ofs<<"\n>> EOF ##########################################\n"; ofs.flush(); ofs.close(); }
void DumpSystem::dumpMoleculeTypeFiles(double dumpTime) { double complexCount = 0; for(int i=0; i<s->getNumOfMoleculeTypes(); i++) { MoleculeType *mt = s->getMoleculeType(i); string dumpFileName = pathToFolder+s->getName() + "_nf."+Util::toString(dumpTime)+".dump."+Util::toString(i); ofstream ofs; //ios_base::out -- Set for output only, instead of for input/output //ios_base::binary -- Set output to binary //ios_base::trunc -- Truncate the file - that is overwrite anything that was already there ofs.open((dumpFileName).c_str(), ios_base::out | ios_base::binary | ios_base::trunc); //Make sure we could open the stream (this is really the only thing that can go around) if(!ofs.is_open()) { cout<<"--------"<<endl; cout<<"-Error dumping header file."; cout<<"-Could not open stream to file: '"<<dumpFileName<<"'"<<endl; cout<<"-The path is probably incorrect or does not exist."<<endl; return; } double NOBOND = -1; list <Molecule *> molList; list <Molecule *>::iterator molIter; for(int j=0; j<mt->getMoleculeCount(); j++) { //First, write out this molecules unique ID Molecule *m=mt->getMolecule(j); double uId = (double)m->getUniqueID(); ofs.write((char *)&uId,sizeof(double)); //Second, output the complex number so we can quickly recover //the complexes if(!s->isUsingComplex()) { if(m->getComplexID()==-1) { //if we haven't visited this guy yet... m->traverseBondedNeighborhood(molList,ReactionClass::NO_LIMIT); for(molIter=molList.begin(); molIter!=molList.end(); molIter++) { (*molIter)->setComplexID((int)complexCount); } ofs.write((char *)&complexCount,sizeof(double)); complexCount++; molList.clear(); } else { double thisUid = m->getComplexID(); ofs.write((char *)&thisUid,sizeof(double)); } } else { complexCount = m->getComplexID(); ofs.write((char *)&complexCount,sizeof(double)); } //Now export all the components, marking its state and //binding partner if any for(int k=0; k<mt->getNumOfComponents(); k++) { double stateValue = (double)m->getComponentState(k); ofs.write((char *)&stateValue,sizeof(double)); if(!m->isBindingSiteBonded(k)) { ofs.write((char *)&NOBOND,sizeof(double)); } else { Molecule *m2=m->getBondedMolecule(k); double uId2 = (double)m2->getUniqueID(); ofs.write((char *)&uId2,sizeof(double)); } } for(int k=0; k<mt->getNumOfTypeIFunctions(); k++) { double val = m->getLocalFunctionValue(k); LocalFunction *lf = m->getLocalFunction(k); double localValue = lf->evaluateOn(m,LocalFunction::MOLECULE); ofs.write((char *)&val,sizeof(double)); ofs.write((char *)&localValue,sizeof(double)); // ofs<<"\t"<<i<<"\t"<<k<<"\t"<<mt->getTypeIILocalFunction(k)->getName()<<"\n"; } } ofs.flush(); ofs.close(); } }
void NFtest_transcription::run() { cout<<"Running the transcription system"<<endl; // 1) System *s = new System("Transcription System"); // 2) MoleculeType *molRNA = createRNA(s); // 3) Instantiate the actual molecules (this populate function is the easiest way, but you can do it // manually as well by creating each molecule separately - see the MoleculeType::populate function for // an example on how this can be done). molRNA->populateWithDefaultMolecules(500); // 4) Create the reactions and add them to the system. These are calls to specific functions // below where I set up the details of the reactions. The numbers are the rates and are in // arbitrary units here. In general, the rates should be in units of per second. ReactionClass * rna_degrade = createReactionRNAdegrades(molRNA, 0.5); ReactionClass *rna_transcribe = createReactionRNAtranscribed(molRNA, 100.0); s->addReaction(rna_degrade); s->addReaction(rna_transcribe); // 5) Add the observables that we want to track throughout the simulation. Again, to // see how this is done, see the function below. addObs(s, molRNA); // 6) Prepare the system for simulation (this adds molecules to reactionLists // and counts up the observables) s->prepareForSimulation(); s->printAllReactions(); // 7) Register the output file name (This will put the file in your working directory) // Here, you also want to output the header to the file, which is not done automatically // because you can run a simulation with multiple calls to the sim functions. s->registerOutputFileLocation("transcription_system_output.txt"); s->outputAllObservableNames(); //8) Run the simulation! //You can optionally equilibrate the system for a set amount of time where output is not //recorded (all times are in seconds) using this function where the first parameter is the //length of the equilibration, and the second is the number of times we want to print a //message that says how we are doing. After it equilibrates, the simulation time is reset to zero. //The first parameter is the number of seconds we want to equilibrate. The second (optional) parameter //is the number of times you want to print an 'ok' output message. If the second parameter is not //given, nothing is outputted to the console. s->equilibrate(0,10); //There are two ways to run a simulation. First, you can just call the function sim as in: s->sim(50,50); //Calling this sim function is the easist way to run a simulation. The first parameter is the //number of seconds you want to run for, the second is the number of times you want to output //the results to the outputfile. So in this example, we run for 500 seconds and output 500 times, //so we output once per second. //The second way to run a simulation is to call this stepTo function: cout<<endl<<endl<<"Calling the stepTo function and stepping to the system time t=600 seconds"<<endl; double stoppingTime = s->stepTo(600); cout<<"The last reaction was fired at simulation time: "<<stoppingTime<<endl<<endl; //This function runs the simulation until the given time is reached, and it also returns the //time of the simulation when the last reaction fired (which is now the current time in the //system. This function does not output to a file automatically, so to output using this function, //so to get results, you will have to use a call to this function: s->outputAllObservableCounts(); //The stepTo function will have to be written as part of a loop where you decide when it should //output. This gives you more control, but of course requires more work. //Here we can print out the list of reactions. This is nice because it tells us how many times //a reaction fired, and how many molecules are in each list at the end of the simulation s->printAllReactions(); //Be nice and clean up when we are done. Deleting the system (should) delete everything else //associated with the system, so we don't ever have to remember to delete individual reactions, molecules //moleculeTypes, etc... delete s; }
void NFtest_tlbr::runSystem(int n_L, int n_R, double cTot, double beta, double koff, string outputFileName, double simTime, double dt, bool outputObservables, bool outputAvg, bool outputFinalDist) { double freeBindRate = (cTot*koff)/(3.0*(double)n_L); double crossLinkRate = (beta*koff)/(double)n_R; cout<<"beta: " <<beta<<endl; cout<<"cTot: " <<cTot<<endl; cout<<"kOff: " <<koff<<endl; cout<<"N_l: " <<n_L<<endl; cout<<"N_r: " <<n_R<<endl; //Create the system with ligands, receptors, and reactions System * s = new System("TLBR",true); vector<vector<string> > v; MoleculeType * L = createL(s,n_L); L->addEquivalentComponents(v); MoleculeType * R = createR(s,n_R); R->addEquivalentComponents(v); createUnbindingRxns(s,R,koff); createFreeBindingRxns(s,L,R,freeBindRate); createCrossLinkingRxns(s,L,R,crossLinkRate); //add the observables if we so choose //if(outputObservables) addObservables(s,L,R); //Prepare to run s->printAllMoleculeTypes(); s->prepareForSimulation(); s->registerOutputFileLocation(outputFileName.c_str()); ///////////////// added here for calculating scalling... //s->equilibriate(200,20); s->sim(simTime,3); string x = ""; cout<<"waiting for you to enter something."<<endl; cin>>x; s->printAllReactions(); // NETGEN -- redirected call to the ComplexList object at s->allComplexes cout << "Finished... avg complex size: " << (s->getAllComplexes()).calculateMeanCount(R) << " receptors" << endl; delete s; return; ///////////////////////////////////// if(outputObservables || outputAvg) s->outputAllObservableNames(); double currentTime = 0; double nextStoppingTime = dt; double avg=-1; // NETGEN -- redirected call to the ComplexList object at s->allComplexes if(outputAvg) avg = (s->getAllComplexes()).outputMeanCount(R); if(outputObservables) s->outputAllObservableCounts(); int step=0; while(currentTime<simTime) { currentTime = s->stepTo(nextStoppingTime); if(outputAvg) avg = (s->getAllComplexes()).outputMeanCount(R); if(step%((int)(100/dt))==0)cout<<"at time: "<<currentTime<<" avg: "<<avg<<endl; if(outputObservables) s->outputAllObservableCounts(); nextStoppingTime += dt; step++; } s->printAllReactions(); // NETGEN -- redirected call to the ComplexList object at s->allComplexes avg = (s->getAllComplexes()).calculateMeanCount(R); cout<<"Finished... avg complex size: "<<avg<<" receptors"<<endl; //(s->allComplexes).printAllComplexes(); //If we aren't outputting the trajectory, make sure that we output the //final aggregate size distribution // NETGEN -- redirected call to the ComplexList object at s->allComplexes if(outputFinalDist) (s->getAllComplexes()).outputMoleculeTypeCountPerComplex(R); if(outputFinalDist) (s->getAllComplexes()).outputMoleculeTypeCountPerComplex(R); delete s; }
bool System::saveSpecies(string filename) { bool debugOut = false; //open the output filestream ofstream speciesFile; speciesFile.open(filename.c_str()); if(!speciesFile.is_open()) { cerr<<"Error in System when calling System::saveSpecies(string)! Cannot open output stream to file "<<filename<<". "<<endl; cerr<<"quitting."<<endl; exit(1); } cout<<"\n\nsaving list of final molecular species..."<<endl; // create a couple data structures to store results as we go list <Molecule *> molecules; list <Molecule *>::iterator iter; map <int,bool> reportedMolecules; map <string,int> reportedSpecies; // loop over all the types of molecules that exist for( unsigned int k=0; k<allMoleculeTypes.size(); k++) { // retrieve the MoleculeType MoleculeType *mt = allMoleculeTypes.at(k); // loop over every individual molecule for(int j=0; j<mt->getMoleculeCount(); j++) { // check if we have looked this molecule before, and skip it if we have if(reportedMolecules.find(mt->getMolecule(j)->getUniqueID())!=reportedMolecules.end()) { continue; } //otherwise, we have not visited this particular species before, so loop over the molecules //that make up the species string speciesString = ""; molecules.clear(); mt->getMolecule(j)->traverseBondedNeighborhood(molecules,ReactionClass::NO_LIMIT); // key: partnerID1, bsiteID1, partnerID2, bsiteID2 vector <vector <int> * > bondNumberMap; bool isFirst = true; for( iter = molecules.begin(); iter != molecules.end(); iter++ ) { Molecule *m = (*iter); reportedMolecules.insert(pair <int,bool> (m->getUniqueID(),true)); //Fist, output the molecule name if(isFirst) { speciesString += m->getMoleculeTypeName()+"("; isFirst=false; } else { speciesString += "."+m->getMoleculeTypeName()+"("; } //Go through each component of the molecule for(int s=0; s<m->getMoleculeType()->getNumOfComponents(); s++) { // output the component name string compName = m->getMoleculeType()->getComponentName(s); if(m->getMoleculeType()->isEquivalentComponent(s)) { // symmetric site, so we need to look up its sym name compName = m->getMoleculeType()->getEquivalenceClassComponentNameFromComponentIndex(s); } if(s==0) speciesString += compName; else speciesString += ","+compName; //output the state of the component, if it is set if(m->getComponentState(s)>=0) { speciesString += "~" + m->getMoleculeType()->getComponentStateName(s,m->getComponentState(s)); } // check if the component is bound, if so we have to output a bond // we will label the bond incrementally, but we have to check to make // sure the bond wasn't declared earlier. that's what the vector of int vectors is for. if(m->isBindingSiteBonded(s)) { if(debugOut) cout<<"binding site is bonded"<<endl; int partnerID = m->getBondedMolecule(s)->getUniqueID(); int partnerSite = m->getBondedMoleculeBindingSiteIndex(s); int thisBondNumber = -1; // create the key vector <int> *key = new vector<int>(4); if(partnerID<m->getUniqueID()) { key->at(0) = partnerID; key->at(1) = partnerSite; key->at(2) = m->getUniqueID(); key->at(3)=s; } else { key->at(2) = partnerID; key->at(3) = partnerSite; key->at(0) = m->getUniqueID(); key->at(1)=s; } //search if that key was already inserted bool foundExistingBond = false; for(unsigned int bnmIndex =0; bnmIndex < bondNumberMap.size(); bnmIndex++) { if( key->at(0)==bondNumberMap.at(bnmIndex)->at(0) && key->at(1)==bondNumberMap.at(bnmIndex)->at(1) && key->at(2)==bondNumberMap.at(bnmIndex)->at(2) && key->at(3)==bondNumberMap.at(bnmIndex)->at(3) ) { thisBondNumber = bnmIndex+1; foundExistingBond = true; if(debugOut) cout<<"Found bond number: "<<thisBondNumber<<endl; break; } } //If it was not found, then insert it if(!foundExistingBond) { bondNumberMap.push_back(key); thisBondNumber = bondNumberMap.size(); if(debugOut) cout<<"Creating bond number: "<<bondNumberMap.size()<<endl; } speciesString += "!" + NFutil::toString(thisBondNumber); } } speciesString += ")"; } if(reportedSpecies.find(speciesString) != reportedSpecies.end()) { reportedSpecies[speciesString] = reportedSpecies[speciesString] + mt->getMolecule(j)->getPopulation(); } else { reportedSpecies.insert(pair <string,int> (speciesString, mt->getMolecule(j)->getPopulation())); } //speciesString += " 1"; //cout<<speciesString<<endl; if(debugOut) cout<<endl<<endl; //delete elements of the map while(bondNumberMap.size()>0) { vector <int> *v = bondNumberMap.at(bondNumberMap.size()-1); bondNumberMap.pop_back(); delete v; } if(debugOut) cout<<endl<<endl; } } speciesFile<<"# nfsim generated species list for system: '"<< this->name <<"'\n"; speciesFile<<"# warning! this feature is not yet fully tested! \n"; for ( map<string,int>::iterator it=reportedSpecies.begin() ; it != reportedSpecies.end(); it++ ) speciesFile << (*it).first << " " << (*it).second << "\n"; speciesFile.flush(); speciesFile.close(); return true; }