*** File /home/dnikce/evolve/faster/gene.h: #ifndef _GENE_H_ #define _GENE_H_ // RCSID = $Id: gene.h,v 1.11 2001/11/05 17:33:47 jjb Exp $ #include "protein.h" #include "protopeptide.h" #include class Chromosome; class Gene { friend class Chromosome; friend ostream& operator<<(ostream&, Gene&); int offset; /* offset on chromosome */ int length; char source; /* temporary */ char mutations; /* keep track of the number of mutations accumulated */ char unexpressed; Protein* protein; public: Gene() { length=0; offset= -1; source = 1; mutations = 0; protein = NULL; unexpressed = 0; } 3348 -> Gene(Gene& gr, int newProtein = 0) { offset = gr.offset; length = gr.length; source = 4+newProtein; mutations = gr.mutations; /* One might expect a new protein, but this facilitates matching */ /* inherited proteins in the replication section of Organism::live() */ if(newProtein) { protein = new Protein(*gr.protein); protein->putQty(0); unexpressed = 1; } else { protein = gr.protein; unexpressed = 0; // points to already expressed protein } } Gene(PeptideString*, int, int, int=3, int=0); ~Gene() { // if(unexpressed && protein) // delete protein; } void express() {unexpressed = 0;} int showMutations() { return mutations;} Protein* getProtein() {return protein;} Protein* updateProtein(Protein* pp) { Protein* rp = protein; protein = pp; return rp; } void move(int o) { offset += 0; } }; #endif Top 10 Lines: Line Count 29 3348 Execution Summary: 16 Executable lines in this file 1 Lines executed 6.25 Percent of the file executed 3348 Total number of line executions 209.25 Average executions per line *** File /home/dnikce/evolve/faster/urn.h: #ifndef _URN_H_ #define _URN_H_ #include "random.h" #include /* ** RCSID = $Id: urn.h,v 1.1 2000/04/08 17:29:11 jjb Exp $ */ class Urn { int* contents; int sz; public: Urn(int i=1) { contents = new int[i]; sz = i; reset(); } ~Urn() { if(sz) delete[] contents; } 2666 -> int draw() { int i = int(z1_Rnd::RNG->Gen1() * sz); int a = i; while(!contents[i]) { if(++i == sz) i=0; if(i == a) return -1; } contents[i] = 0; assert(i >= 0 && i < sz); return i; } void reset() { for(int j=0; j #include "protopeptide.h" #include "defs.h" #include "peptidestring.h" extern int OldMatch; char Protopeptide::NoFunctionMsg[] = "No Function"; ##### -> ostream& operator<<(ostream& os, Protopeptide& pr) { return os << pr.pstring << " | " << pr.length; } /* ** lookup() matches the character string in trial against ** each string in the library and returns a list of all ** valid matches. ** ** It assumes that the character string is null-terminated, ** begins with an optional EPI string, followed by a start ** codon, and ends with the stop codon. */ int 2238 -> Protopeptide::lookup(PeptideString* trial, Function_t function[], int mismatch[]) { int err=0; char *c = trial->skipGene( (char*) 0, 0); while(*c != START && *c != '\n') c++; PeptideString* candidate = new PeptideString(c); int findex = 0; for(int i=0; imatch(candidate, maxMismatch); break; case 1: err = lptr->match1(candidate, maxMismatch); break; case 2: err = lptr->mymatch(candidate, maxMismatch); break; default: err = lptr->match(candidate, maxMismatch); break; } if (err < maxMismatch) { function[findex] = i; mismatch[findex++] = err; } /* if(((err=... */ } /* while(! lptr... */ delete candidate; return findex; } Top 10 Lines: Line Count 22 2238 Execution Summary: 22 Executable lines in this file 2 Lines executed 9.09 Percent of the file executed 2238 Total number of line executions 101.73 Average executions per line *** File /home/dnikce/evolve/faster/date.C: static char RCSID[] = "$Id: date.C,v 1.2 2001/04/18 11:25:40 jjb Exp $"; #include "defs.h" #include "date.h" #include "serial.h" int Date::currentTime = 0; int Date::currentDay = 0; int Date::currentYear = 0; 8 -> ostream& operator<<(ostream& os, const Date& dr) { return os << dr.year << ", " << dr.time; } Top 10 Lines: Line Count 10 8 Execution Summary: 2 Executable lines in this file 1 Lines executed 50.00 Percent of the file executed 8 Total number of line executions 4.00 Average executions per line *** File /home/dnikce/evolve/faster/protopeptide.h: // RCSID = $Id: protopeptide.h,v 1.6 2000/12/29 14:42:23 jjb Exp $ #ifndef _PROTOPEPTIDE_H_ #define _PROTOPEPTIDE_H_ #include "peptidestring.h" #include "fptr.h" #include #include #include "env.h" #include "misc.h" #define Motile 0 #define SenseEnv0 1 #define SenseEnv1 2 #define SenseEnv2 3 #define SenseEnv3 4 #define SenseEnv4 5 #define Conjugate 6 #define SecreteSugars 7 #define SecreteA 8 #define SecreteB 9 #define SecreteC 10 #define Protease 11 /* ** Protopeptides are prototype strings that allow us ** to map a peptide string to a function, based on ** its linear arrangement. ** The Efficiency_t structure contains the variables that ** determine a protein's efficiency. Factors may either ** enhance or degrade a protein's efficiency. They are ** both environmental factors such as pH, etc., and materials. ** Lopass and hipass are the points at which f(x) is min and max, ** respectively, with regard to the factor effect. ** VMAX is the maximum rate for an enzyme. The efficiency mechanism is ** attached to the function that a particular to which a protein maps, ** rather than the protein itself. ** At this time, the effect of low substrate concentrations on protein ** efficiency isn't modeled. The efficiency of the protein is taken as ** constant. */ extern PeptideString** prototype; class Protopeptide : public PeptideString { friend ostream& operator<<(ostream&, Protopeptide&); static char NoFunctionMsg[]; public: Protopeptide(){} Protopeptide(Peptide* pep) : PeptideString(pep) {} Protopeptide(Protopeptide& pr) : PeptideString((PeptideString&)pr) {} 9046559 -> static double effect(int which, EnVar& eMillieu, Material& cMillieu){ int ei = efficiency[which].Efactor; int ci = efficiency[which].Mfactor; double ex = eMillieu[ei]; double lp,hp; double retval; // If ei or ci is negative, the corresponding response is unity; // NOTE: the corner points must not be equal or div-by-zero occurs. if(ei >= 0) { hp = efficiency[which].elopass; lp = efficiency[which].ehipass; if(lp < hp) { if(ex < lp) retval = 0; else if(ex > hp) retval = 1; else retval = (ex -lp)/(hp - lp); } else { // ei < 0 if(ex > lp) retval = 0; else if(ex < hp) retval = 1; else retval = 1 - (ex - hp) / (lp - hp); } } else retval = 1.0; if(ci >= 0) { ex = double(cMillieu[ci]); hp = efficiency[which].clopass; lp = efficiency[which].chipass; if(lp < hp) { if(ex < lp) retval *= 0; else if(ex > hp) retval *= 1; else retval *= (ex -lp)/(hp - lp); } else { // lp >= hp if(ex > lp) retval *= 0; else if(ex < hp) retval *= 1; else retval *= 1 - (ex - hp) / (lp - hp); } } else retval *= 1.0; return retval*efficiency[which].Vmax; } static int lookup(PeptideString*, Function_t[], int[]); int isNull() {return !length;} static int getType(int i) {return sfn[i].type;} static int getOperand(int i) {return sfn[i].operand;} static void readTables(char*); }; #endif Top 10 Lines: Line Count 50 9046559 Execution Summary: 34 Executable lines in this file 1 Lines executed 2.94 Percent of the file executed 9046559 Total number of line executions 266075.26 Average executions per line *** File /home/dnikce/evolve/faster/protein.h: #ifndef PROTEIN_H #define PROTEIN_H /* ** RCSID = $Id: protein.h,v 1.6 2001/08/25 21:32:12 jjb Exp $ */ #include "material.h" #include #include /* ** Proteins are macro molecules that (potentially) have ** a functional description as well as a chemical composition. ** ** The Material base class describes the cost to build ** the protein and the list of function pointers identify ** the function(s) that it serves. ** 1/14/98 -- modify Protein to ensure that the primary ** function is always the first in the List<> functions; */ class Organism; class Protein : public Material { friend ostream& operator<<(ostream&, Protein&); friend ostream& operator<<(ostream&, Organism&); friend class Organism; friend class Location; Function_t* function; int* mismatch; int nfunction; float degradation; Material_t quantity; public: Protein() : Material() {degradation=0.0;} Protein(Protein& pr) : Material((Material&)pr) { nfunction = pr.nfunction; quantity = pr.quantity; function = new Function_t[nfunction]; mismatch = new int[nfunction]; degradation = pr.degradation; for(int i=0; i Protein* flake(Material_t q) { if( q >quantity) return (Protein*) 0; else { quantity -= q; Protein* rc = new Protein(*this); rc->quantity = q; return rc; } } Material_t qty() {return quantity;} void putQty(Material_t q) {quantity = q;} void incQty(Material_t q) {quantity += q;} Material degrade(double rate) { float d = rate * quantity; // degrade all instances equally degradation += d; d = min(floor(degradation), quantity); quantity -= (int)d; degradation -= d; return (Material)*this * (Material_t)d; } }; #endif Top 10 Lines: Line Count 57 5176 Execution Summary: 39 Executable lines in this file 1 Lines executed 2.56 Percent of the file executed 5176 Total number of line executions 132.72 Average executions per line *** File /home/dnikce/evolve/faster/peptidestring.h: #ifndef _PEPTIDE_STRING_ #define _PEPTIDE_STRING_ #include "defs.h" #include #include #include #include #include "config.h" #include "random.h" #include "pvector.h" /* ** RCSID = $Id: peptidestring.h,v 1.18 2001/07/30 21:24:34 jjb Exp $ ** ** Peptide strings are represented by character strings ** */ struct mutret_t { int offset; char type; }; class PeptideString { friend ostream& operator<<(ostream&, const PeptideString&); friend class PeptideStringIterator; static char *Alphabet; static int AlphabetLength; protected: int length; Peptide* pstring; public: static PeptideString* NIL; PeptideString() { pstring=0; length = 0; } PeptideString(Peptide* p) { length = strlen(p); pstring = new Peptide[length+1]; strcpy(pstring, p); } PeptideString(PeptideString& pr) { length = pr.length; pstring = new Peptide[length+1]; strcpy(pstring, pr.pstring); } PeptideString(PeptideString* ps) { length = ps->length; pstring = new Peptide[length+1]; strcpy(pstring, ps->pstring); } PeptideString(int); 868 -> ~PeptideString() { if(length) delete[] pstring; } /* Set up the default alphabet, based on the number */ /* of amino acids to be used. */ static void init(int); PeptideString* subString(Peptide*, int=-1) const; PeptideString* subString(int, int=-1) const; /* ** Hamming distance, insDel, alphabet */ void mutateOnce(mutret_t&); void mutate(const int=1, const double = MutationRate, const int = 1); inline int delta(char, char); int match1(PeptideString* const, int); int match(PeptideString* const, int); int mymatch(PeptideString* const, int); int distance(PeptideString*, PeptideString*); void insert(PeptideString*, int=-1); 22 -> void insertChar(int offset, char c) { length++; Peptide* n = new Peptide[length+1]; Peptide* mem = n; Peptide* o = pstring; for(int i=0; i&); */ Peptide& operator[](int i) { if(i < 0) i=0; if(i > length) i=length; return pstring[i]; } void toString(int offset, int len, Peptide retString[]) { int mylen = len; if(offset + len > length) mylen = length - offset; strncpy(retString, pstring+offset, mylen); retString[mylen] = '\0'; return; } char rChar(); }; class PeptideStringIterator { PeptideString* which; char* p; /* pointer into peptideString */ int criticalFlag; public: PeptideStringIterator(){which=NULL;} PeptideStringIterator(PeptideString* const subject) : which(subject){ assert(which != NULL); p = &(which->pstring[0]); } int criticalP() {return isupper(*p);} char getCurrent() {return *p;} /* ** Get the i-th character */ ##### -> char getNext(int i=1) { assert(i>=0); if(*p == '\0') return ('\0'); for(;i>0;i--) { if(*(++p) == '\0') break; } return isupper(*p)?tolower(*p):*p; } ##### -> char getPrev(int i=1) { assert(i>=0); if(*p=='\0') return *p; if(p==which->pstring) return isupper(*p)?tolower(*p):*p; for(;i>0;i--) { if((--p)==which->pstring) return isupper(*p)?tolower(*p):*p; } return isupper(*p)?tolower(*p):*p; } }; #endif Top 10 Lines: Line Count 51 868 71 22 Execution Summary: 58 Executable lines in this file 4 Lines executed 6.90 Percent of the file executed 890 Total number of line executions 15.34 Average executions per line *** File /home/dnikce/evolve/faster/organism.h: /* ** RCSID - $Id: organism.h,v 1.18 2001/11/16 01:30:51 jjb Exp $ ** ** $Log: organism.h,v $ ** Revision 1.18 2001/11/16 01:30:51 jjb ** changed int proDone to char bottom and added ** sinkP() ** ** */ #ifndef ORGANISM_H #define ORGANISM_H #include "defs.h" #include #include #include "material.h" #include "chromosome.h" #include "protein.h" #include "position.h" #include "date.h" #include "env.h" #include "macro.h" #include "vector.h" #include "protopeptide.h" #include #include "config.h" #include "proteintype.h" #include "serial.h" extern ofstream& ofile; class Organism : public Serial, public Position { friend ostream& operator<<(ostream&, Organism&); friend class ORecord; friend class OrganismInfo; enum Direction {east, south, west, north} lastDir; // The next two instances of Material keep track of the // material in partially constructed proteins and chromosome // copy. Material auxMaterial; Material proMaterial; Material cytoplasm; Chromosome* myChromosome; Chromosome* aux; int auxDone; char bottom; char lineage; int np; // Number of proteins I have Protein** protein; int currentAminoAcid; int logDone; int nextPeptide; void acceptFrag(PeptideString*); void conjugate(Organism&); double *efficiency; double *uptakeRates; public: Organism() { lineage = -1; auxMaterial = 0; proMaterial = 0; myChromosome = 0; aux = 0; np = 0; lastDir = east; cytoplasm = Material(Material_t(0)); auxDone = 0; bottom = 0; protein = 0; currentAminoAcid = 0; logDone = 0; nextPeptide = 0; efficiency = new double[NFunction]; uptakeRates = new double[NMat+1]; calculateEfficiencies(); calculateUptakeRates(); } /* In this constructor, the chromosome passed in is incorporated into the */ /* new organism rather than being copied. */ 737 -> Organism(Organism &orgref, Chromosome *cr) : Position(orgref) { lineage = orgref.lineage+1; myChromosome = cr; auxMaterial = 0; proMaterial = 0; aux = new Chromosome(*myChromosome, MutationRate); np = 0; lastDir = east; cytoplasm = Material(Material_t(0)); efficiency = new double[NFunction]; uptakeRates = new double[NMat+1]; auxDone = 0; bottom = 0; protein = 0; currentAminoAcid = myChromosome->nextGeneOffset(-1); logDone = 0; nextPeptide = 0; calculateEfficiencies(); calculateUptakeRates(); } Organism(Chromosome&, Material&, int, int, char); ~Organism(); /* ** return biomass = cytoplasm + proteins + aux + chromosome */ Material biomass() { Material mr; char aa; for(int i=0; iquantity; mr += cytoplasm + myChromosome; mr += auxMaterial + proMaterial; return mr; } Material proteinMaterial() { Material mr; char aa; for(int i=0; iquantity; return mr; } float totalProtein() { float t = 0; for(int i=0; iquantity; return t; } int sinkP() {return (int)bottom;} void copyFunctionality(Function_t*); void die(); void live(); // return the length of the duplicated chromosome int auxlen() { return nextPeptide; } Material cytoMaterial() { return cytoplasm; } double avgProtein() { double avg; for(int i=0; iquantity; avg /= np; return avg; } Serial serial() { return (Serial)*this; } void calculateEfficiencies(); void efficiencies(ostream&); void dltraits(ostream&); void netEfficiencies(ostream&); void proteinqty(ostream&); void calculateUptakeRates(); void getUptakeRates(double* retVal) { for(int i=0; i quantity)?quantity:cytoplasm[ATP]; cytoplasm[ATP] -= avail; cytoplasm[ADP] += avail; cytoplasm[Pi] += avail; return avail; } void datalog(ostream&); }; #endif Top 10 Lines: Line Count 83 737 Execution Summary: 30 Executable lines in this file 1 Lines executed 3.33 Percent of the file executed 737 Total number of line executions 24.57 Average executions per line *** File /home/dnikce/evolve/faster/position.h: #ifndef _POSITION_H_ #define _POSITION_H_ #include #include #include #include "config.h" #include "macro.h" #define NOSPIRAL 1 #define TOP 1 #define BOTTOM 0 /* ** RCSID = $Id: position.h,v 1.10 2001/07/22 19:47:25 jjb Exp $ */ class Position { friend ostream& operator<<(ostream&, const Position&); public: static int indexToX(int i) {return i%X;} static int indexToY(int i) {return i/X;} static void setSize(int x, int y) { X = x; Y = y; } int x, y, z; static int X, Y; Position(){x = y = 0; z = TOP;} Position(int px, int py, int pz = TOP) { assert(px < X && py < Y); x = px; y = py; z = pz; } Position operator=(Position r) { assert(r.x < X && r.y < Y); x = r.x; y = r.y; z = r.z; return *this; } /* ** Assumes shortest distance. I.e., organism ** will never move more than 1/2 the universe ** at a time. */ float distance(Position& P1) { int dx = (P1.x > x)?(P1.x-x):(x-P1.x); int dy = (P1.y > y)?(P1.y-y):(y-P1.y); return sqrt(float(dx*dx + dy*dy)); } 74951 -> Position& moveN(int step=1, int noSpiral = 0) { if(YBar < 0) { /* Can move all the way to Y-1 */ y += step; if(y >= Y) { y %= Y; if(!noSpiral) moveE(1,NOSPIRAL); } } else { /* There's a barrier; can't cross it */ const int offset = YBar+1; if(y <= YBar) { /* South of barrier */ y += step; if(y > YBar) { /* Can't step across */ y %= offset; if(!noSpiral) moveE(1,NOSPIRAL); } } else { /* North of barrier */ y += step; if(y >= Y) { /* Wrap by zero-basing by YBar+1 */ y = offset + ((y - offset) % (Y-offset)); if(!noSpiral) moveE(1,NOSPIRAL); } } } return *this; } Position& 78060 -> moveS(int step=1, int noSpiral=0) { if(YBar < 0) { /* wrap at 0 */ if(step > y) /* will need to wrap */ if(!noSpiral) moveW(1,NOSPIRAL); y = (y + Y - (step % Y)) % Y; } else { /* there's a barrier: wrap up to there */ const int offset = YBar + 1; if(y <= YBar) { /* south of barrier */ if(step > y) { y = (y + offset - (step % offset)) % offset; if(!noSpiral) moveW(1,NOSPIRAL); } else y -= step; } else { /* north of barrier */ if((y - step) <= YBar) { /* wrap at barrier up to top */ const int newY = Y - offset; y = offset +((y-offset) + newY - (step % newY)) % newY; if(!noSpiral) moveW(1,NOSPIRAL); } else y -= step; } } return *this; } 77600 -> Position& moveE(int step=1, int noSpiral=0) { if(XBar < 0) { /* Can move all the way to X-1 */ x += step; if(x >= X) { x %= X; if(!noSpiral) moveN(1,NOSPIRAL); } } else { /* There's a barrier; can't cross it */ const int offset = XBar + 1; if(x <= XBar) { /* West of barrier */ x += step; if(x > XBar) { /* Can't step across */ x %= offset; if(!noSpiral) moveN(1,NOSPIRAL); } } else { /* East of barrier */ x += step; if(x >= X) { /* Wrap by zero-basing by XBar + 1 */ x = offset + ((x - offset) % (X - offset)); if(!noSpiral) moveN(1,NOSPIRAL); } } } return *this; } Position& 77652 -> moveW(int step=1, int noSpiral=0) { if(XBar < 0) { /* wrap at 0 */ if(step > x) /* will need to wrap */ if(!noSpiral) moveS(1,NOSPIRAL); x = (x + X - (step % X)) % X; } else { /* there's a barrier: can't cross it or wrap around */ const int offset = XBar + 1; if(x <= XBar) { /* west of barrier */ if(step > x) { x = (x + offset - (step % offset)) % offset; if(!noSpiral) moveS(1,NOSPIRAL); } else x -= step; } else { /* east of barrier */ if((x - step) <= XBar) { /* wrap at barrier over to right */ const int newX = X - offset; x = offset + ((x - offset) + newX - (step % newX)) % newX; if(!noSpiral) moveS(1,NOSPIRAL); } else x -= step; } } return *this; } void moveU() {z = TOP;} void moveD() {z = BOTTOM;} int upP() {return z==TOP;} int index() {return x + y*X;} static int getIndex(int x, int y) { return x+y*X; } }; #endif Top 10 Lines: Line Count 77 78060 139 77652 108 77600 46 74951 Execution Summary: 83 Executable lines in this file 4 Lines executed 4.82 Percent of the file executed 308263 Total number of line executions 3714.01 Average executions per line *** File /home/dnikce/evolve/faster/mylist.C: static char RCSID[] = "$Id: mylist.C,v 1.2 2000/10/20 16:57:38 jjb Exp $"; #include "mylist.h" #include "random.h" #include "organism.h" void 273467 -> BaseList::prepend(Pix p) { ((BaseNode*)p)->fd = listHead; listHead = (BaseNode*)p; } void ##### -> BaseList::append(Pix p) { if(listHead == 0) { listHead = (BaseNode*)p; return; } BaseNode* ptr = listHead; while(ptr->fd) ptr = ptr->fd; ptr->fd = (BaseNode*)p; ((BaseNode*)p)->fd = 0; // paranoia return; } BaseNode* 272998 -> BaseList::remove(Pix p) { BaseNode* shadow = 0; BaseNode* ptr = listHead; while(ptr && ptr != (BaseNode*)p) { shadow = ptr; ptr = ptr->fd; } if(ptr) { if(shadow) shadow->fd = ptr->fd; else { listHead = ptr->fd; } } return ptr; } Pix ##### -> BaseList::getLast() { Pix ptr=listHead, shadow=listHead; if(!listHead) return listHead; while(((BaseNode*)ptr)->fd) { shadow=ptr; ptr=((BaseNode*)ptr)->fd; } return shadow; } Pix ##### -> BaseList::getNth(int n) { Pix ptr = listHead; for(int i=1; ifd; } else break; } return ptr; } Pix ##### -> BaseList::getSome(){ int i = (int)z1_Rnd::RNG->Gen1()*length(); return getNth(i); } int BaseList::length() { int l=1; BaseNode* ptr = listHead; if(listHead==0) return 0; while(ptr=ptr->fd) l++; return l; } Top 10 Lines: Line Count 7 273467 24 272998 70 72000 Execution Summary: 47 Executable lines in this file 6 Lines executed 12.77 Percent of the file executed 618465 Total number of line executions 13158.83 Average executions per line *** File /home/dnikce/evolve/faster/chromosome.h: #ifndef _CHROMOSOME_H_ #define _CHROMOSOME_H_ /* ** RCSID = $Id: chromosome.h,v 1.7 2001/07/23 16:32:19 jjb Exp $ */ #include "peptidestring.h" #include "material.h" #include #include "gene.h" /* ** Since codons map deterministically to amino acids ** the model reprents the chromosome directly in ** terms of the amino acid string. We may need to ** modify the point mutation routine to capture the ** redundancy of the genetic code. */ /* ** V. 1.2 adds genes to the chromosome. By keeping track ** of individual genes, I can reduce the overhead of interpreting ** genes by roughly 25-fold. That results from only re-interpreting ** the genes that have been mutated. */ class Chromosome : public PeptideString, public Material { friend void parse(); friend ostream& operator<<(ostream&, Chromosome&); Gene** genes; int nGene; /* ** findCodon returns the index of the gene ** containing the codon at offset "c" on the ** the chromosome. It is used by findOffset(), ** findLength() and nextGene(). ** Note that if c points to junk between genes, ** it will return a pointer to the start of the ** previous gene. ** */ 897841 -> int findCodon(int c) { if (c >= length) return 0; if(c < genes[0]->offset) return 0; int g = 0; /* keep going until genes[g]->offset >= c */ while((g < nGene) && (genes[g]->offset <= c)) g++; /* either g == nGene ==> c is in last gene or last intron */ /* or c < genes[g]->offset ==> c is in previous gene or intron */ if(c < (genes[g-1]->offset + genes[g-1]->length)) return g-1; else return -1; } public: static const int RegLen; static const int IntegerLen; static const int DecimalLen; static const char PAD; static void ftos(float, char*, int); static float stof(char*, int); Chromosome(){}; /* ** This is necessary to build the first chromosomes ** from the strings in the config data file */ Chromosome(Peptide*); /* ** copy constructor */ Chromosome(Chromosome& cr) : PeptideString((PeptideString&)cr), Material(cr), nGene(cr.nGene) { genes = new (Gene*)[nGene]; for(int i=0; i= nGene) i = nGene -1; return genes[i]; } Peptide* getGene(Peptide**); /* ** int findOffset(int c) returns the offset of the gene containing ** the codon pointed to by the argument c. ** int findLength(int c) returns the length of the gene in question ** Protein* proteinPointer(int c) returns a pointer to the protein ** for which the gene codes. ** nextGene)Offset(int c) returns the offset of the gene following the one ** containing the codon pointed to by the argument c. It wraps around at ** the end of the chromosome. */ int findOffset(int c) { int g; if((g = findCodon(c)) < 0) return -1; else return genes[g]->offset; } int findLength(int c) { int g; if((g = findCodon(c)) < 0) return -1; else return genes[g]->length; } Protein* proteinPointer(int c) { int g; if((g = findCodon(c)) < 0) return NULL; else return genes[g]->protein; } 19753 -> int nextGeneOffset(int c) { if ((c >= length-1) || (c < 0)) return genes[0]->offset; int g = 0; while((g offset <= c)) g++; if(g == nGene) return genes[0]->offset; else return genes[g]->offset; } void datalogGenes() { for(int i=0; ishowMutations() << ", "; } cerr << genes[nGene-1]->showMutations() << endl; } void datalog(ostream&, Protein*[], int, int); }; #endif Top 10 Lines: Line Count 39 897841 126 19753 Execution Summary: 41 Executable lines in this file 2 Lines executed 4.88 Percent of the file executed 917594 Total number of line executions 22380.34 Average executions per line *** File /home/dnikce/evolve/faster/material.C: static char RCSID[] = "$Id: material.C,v 1.12 2001/10/11 00:20:43 jjb Exp $"; #include "material.h" #include #include "organism.h" #include #include extern ReactionTable RTable; int ##### -> Material::findMin(int f, int l) { Material_t v=MaxMatl; /* Min value */ int rc=f, i; for(i=f; i<=l; i++) if((*this)[i] Material::findMax(int f, int l) { Material_t v=0; int rc, i; for(i=f; i<=l; i++) if((*this)[i]>v){ v=(*this)[i]; rc=i; } return i; } int ##### -> Material::negCheck(Material_t level) { for(int i=0; i Material::Material(const Peptide* p) : Vector(NMat) { int l = strlen(p); for(int i=0; i Material::Material(const PeptideString* psp) : Vector(NMat) { char* ptr = 0; char c; if(!psp) return; while(c = psp->getNext(&ptr)) { ((*this)[(int)(tolower(c) - 'a' + FirstAmino)])++; } // (*this)[NMat] = (Material_t) ProteinAssemblyConstant * psp->plen(); // need another approach // (*this)[024]=0; // Don't charge for the stop codon! // cout<<"Material(PeptideString): " << *this << endl; } ##### -> int Material::threshold(int first, int last, Material_t t) { for(int i=first; i<=last; i++) if((*this)[i] < t) return 1; return 0; } ostream& 7 -> operator<< (ostream& os, const Material& m) { for(int i=0; i Material::datalog(ostream& os) { int i; for(i=0; i operator << (ostream& os, Reaction& r) { os << (Material&) r; return (os << " " << r.KC << endl); } ostream& ##### -> operator<< (ostream& os, ReactionTable& theTable) { for(int i=0; i<=NReactions; i++) os << theTable[i]; return os; } /* ** Returns "at. wt." of a compound */ Material_t ##### -> Material::getMass() { Material_t rc=0; // cout << "getMass: " << *this << endl; for(int i=0; i Material::getMassF() { float rc=0; for(int i=0; i Material::getMassT() { Material_t rc=0; for(int i=0; i Material::totalDecompose() { Material_t coef; Material_t mult; for(int m=NMat-1; m>=NElem; m--) { if((*this)[m] > 0) { for(int r=NReactions-1; r>=0; r--) { if(RTable[r][m] < 0) { Material_t rate = MaxMatl; for(int i=0; i Material::partialDecompose(double fractionToDecompose) { assert(fractionToDecompose < 1.0); Material temp(*this); temp *= fractionToDecompose; *this -= temp; temp.totalDecompose(); *this += temp; } // Vmax is the max rate for the reaction, and is the "efficiency" // for the enzyme modified by environmental effects. Milieu is the // chemical milieu for the reaction, i.e., the cytoplasm. void 7609126 -> Reaction::react(double Vmax, Material& milieu) { // Test to see which way equilibrium lies. int trialDirection; Material temp(milieu); int initialDirection = equilibriumP(temp); if(initialDirection == 0) return; // already at equilibrium double rate = (initialDirection > 0)?Vmax:-Vmax/KC, trialRate; double fraction = 0.0; int trialBit = 1; // Reality check: limit Vmax to the amount of available reagents if(initialDirection > 0) { for(int m=0; m 0 && milieu[m] != 0) { rate = min(floor(rate), milieu[m]/(*this)[m]); } } } else { for(int m=0; m 0)?floor(trialRate):ceil(trialRate)); temp = milieu - (*this) * integerRate; #else temp = milieu - (*this) * trialRate; #endif trialDirection = equilibriumP(temp); if(trialDirection == 0) break; // we've reached equilibrium. can't improve more. if (trialDirection != initialDirection) { // don't set that bit fraction -= 1.0/trialBit; // We'll do all this in case this is the last time through the loop. // Otherwise, the value of fraction will get corrected, but temp will // not reflect the change. trialRate = rate * fraction; #ifdef IntMat int integerRate = (int) ((trialRate > 0)?floor(trialRate):ceil(trialRate)); temp = milieu - (*this) * integerRate; #else temp = milieu - (*this) * trialRate; #endif } } // Here fraction is the best estimate of equilibrium rate // and temp is the result of applying that rate to milieu. // cerr << "fraction = " << fraction << " rate = " << trialRate << endl; assert(temp >= 0); milieu = temp; return; } #define conc(A) ( A * ConcFactor) // ConcFactor is set in the config file // equilibriumP returns a 1 for forward and -1 for reverse. // If the reaction is at equilibrium, or within e of it, // equilibriumP returns 0 20561465 -> int Reaction::equilibriumP(Material& milieu) { double epsilon = .01; double fwd = 1.0, rev = 1.0; for(int m=0; m 0.0) fwd *= pow(conc(milieu[m]), ((*this)[m])); else if((*this)[m] < 0.0) rev *= pow(conc(milieu[m]), (-(*this)[m])); } if(fwd > (rev / KC) * (1 + epsilon)) return 1; if(rev / KC > fwd * (1 + epsilon)) return -1; return 0; } Top 10 Lines: Line Count 236 20561465 165 7609126 131 36670 52 3191 80 2048 43 1583 74 7 152 1 Execution Summary: 90 Executable lines in this file 17 Lines executed 18.89 Percent of the file executed 28214091 Total number of line executions 313489.90 Average executions per line *** File /home/dnikce/evolve/faster/gene.C: static char RCSID[] = "$Id: gene.C,v 1.10 2001/08/24 04:17:12 jjb Exp $"; #include "gene.h" ##### -> ostream& operator<<(ostream& os, Gene& gr) { return os << gr.offset << "|" << gr.length; } 2239 -> Gene::Gene(PeptideString *pptr, int start, int len, int src, int nMutation) { offset = 0; length = 0; source = src; mutations = nMutation+1; int nfunction = 0; int i; char gFlag = 0; for(i=0; isubString(offset, length-1); Function_t tempFunction[NFunction]; int tempMismatch[NFunction]; nfunction = Protopeptide::lookup(geneString, tempFunction, tempMismatch); protein = new Protein(geneString, tempFunction, tempMismatch, nfunction); unexpressed = 1; delete geneString; } else { protein = NULL; unexpressed = 0; } } Top 10 Lines: Line Count 7 2239 Execution Summary: 27 Executable lines in this file 2 Lines executed 7.41 Percent of the file executed 2239 Total number of line executions 82.93 Average executions per line *** File /home/dnikce/evolve/faster/main.C: static char RCSID[] = "$Id: main.C,v 1.52 2002/01/17 12:24:49 jjb Exp $"; // $Log: main.C,v $ // Revision 1.52 2002/01/17 12:24:49 jjb // Added explicit timeString in epilogue // // Revision 1.51 2001/11/11 01:30:15 jjb // error on l. 143 ni was i // // Revision 1.50 2001/11/11 01:24:40 jjb // Moved updateShare() again. // // Revision 1.49 2001/11/10 22:48:10 jjb // ? // // Revision 1.48 2001/11/10 22:33:04 jjb // Added cost printout for each chromosome. // // Revision 1.47 2001/11/10 22:24:59 jjb // merged with 1.44.1.2 // // Revision 1.46 2001/11/05 17:26:16 jjb // Changed LOG to Log // #define NULL 0 #include "defs.h" #include "env.h" #include "material.h" #include "organism.h" #include "position.h" #include "protopeptide.h" #include "random.h" #include "date.h" #include "macro.h" #include #include #include #include #include #include #include #include #include // for msgctl #include #include #include #include #include #include #include #include #include #include "global.h" #include "envars.h" #define DEFAULTPORT 3141 int ST = 0; static int REREAD = 0; int maxPop = 0; ReactionTable RTable(0); extern char* optarg; int* Material::atwt = 0; extern int optind, opterr, optopt; PeptideString** prototype; char sampleP = 1; // sample Predicate int msgqid; char ConfigFileName[MAXPATHLEN+1]; char logFileName[MAXPATHLEN+1]; extern FILE* yyin; Date now = *new Date; 1 -> void epilogue(char * msg = 0) { int grossPop = Location::WorldPop(); char timeString[100]; ofstream logFile(logFileName, ios::app); time_t ltime; time(<ime); strcpy(timeString, ctime(<ime)); logFile << "EvolveIV: "; if(msg) logFile << "caught " << msg << ": "; logFile << timeString << endl; logFile << "Finished at " << now << " with population " << grossPop << endl; logFile << "Peak population was " << maxPop << endl; logFile << "Resources: "; logFile << Location::resourceSummary(1) << endl; logFile << "Biomass: "; logFile << Location::biomassSummary() << endl; logFile << endl; } extern "C" { int yyparse(); } void parse(char* ConfigFileName, ostream& logFile) 1 -> { Chromosome **cptr; Material *cost; PeptideString* ps; float *proteinSetpt, tempProtein; int i, j, k, NotDone = 1; fclose (stdin); yyin = fopen(ConfigFileName, "r"); if(yyin == NULL) { cerr << "Error opening config file " << ConfigFileName << endl; perror("Parse"); exit(1); } GX = GY = 0; PASS = 0; yyparse(); bioact = new struct bioact_t[NBioAct]; PeptideString::init(NAmino); // set up the amino acid alphabet RTable.resize(NReactions); int cbufLen = MAXCHROMOLEN * NSpecies; cbuf = new char[cbufLen]; pbuf = new char[MAXGENELEN*NFunction]; reactions = new Material_t[NMat * NReactions]; equilibriumConstants = new double[NReactions]; cptr = new Chromosome*[NSpecies]; cost = new Material[NSpecies]; override = new int[NMat]; cytoInit = new int[NMat]; for(int h=0; hplen() << " norg " << norg[ni]<< endl; cost[ni] = ((Material&) *(cptr[ni])); cost[ni].totalDecompose(); logFile << "Chromosome cost: " << cost[ni] << endl; cost[ni] = ((Material&) *(cptr[ni])) * CytoMultiplier; cost[ni].partialDecompose(0.167); for(int h=0; h -1)?cytoInit[h]:cost[ni][h]; logFile << "Cost[" < -1) envMatl[h] = override[h]; logFile << "envMatl after override: " << envMatl << endl; for(j = 0; j < XDim; j++) { GX = j; for(k=0; k< YDim; k++) { GY = k; int lindex = Position::getIndex(j,k); rewind(yyin); EnVar::setDefaults(envec); for(int ix=0; ix". // The change to MySQL also changed the format of the files, // in that the first line of the data files no longer contains // the column labels. Instead, an additional file named ddl-pid // contains the DDL. The database itself is named Ev4_pid. // static char firstTime = 1; void 7 -> datalog(int pid) { char filename[MAXPATHLEN]; ostrstream fdstream(filename, sizeof(filename)); fdstream.seekp(0); fdstream << "location-" << pid << ends; ofstream ls(filename, ios::app); fdstream.seekp(0); fdstream << "organism-" << pid << ends; ofstream os(filename, ios::app); fdstream.seekp(0); fdstream << "time-" << pid << ends; ofstream ts(filename, ios::app); const int nLoc = XDim * YDim; int lindex; if(firstTime) { fdstream.seekp(0); fdstream << "ddl-" << pid << ends; ofstream ds(filename, ios::app); // Write ddl file ds << "CREATE DATABASE Ev4_" << pid << ";" << endl; ds << "USE Ev4_" << pid << ";" << endl; ds << "CREATE TABLE Time" <getNext(); while(op) { os << "0, " << op->sn(); os << FS << lindex << FS << TimeID << FS; // log Lineage, Chromosome_Length, Efficiencies, Cytoplasm // Total_Protein, nProtein, AuxLen and nGene op->datalog(os); os << endl; op = bip->getNext(); } delete bip; } TimeID++; } // Organism* findOrganism(long sn) { // const int nLoc = XDim * YDim; // Organism* op; // Pix ptr; // int lindex; // for(lindex=0; lindex < nLoc; lindex++) { // BiotaIterator* bip = new BiotaIterator(&Location::theWorld[lindex]); // op = bip->getNext(); // while(op) { // if(op->sn() == sn) // return op; // else // op = bip->getNext(); // } // delete bip; // } // // are you *still* here? // return (Organism*)0; // } // Organism* firstOrganism() { // const int nLoc = XDim * YDim; // Organism* op; // int lindex; // for(lindex=0; lindex < nLoc; lindex++) { // if(Location::theWorld[lindex].locationPop()) { // BiotaIterator* bip = new BiotaIterator(&Location::theWorld[lindex]); // op = bip->getNext(); // delete bip; // return op; // } // } // return (Organism*)0; // } // void // sample() { // int grossPop = Location::WorldPop(); // Material biomass(Material_t(0)); // Material resources(Material_t(0)); // char sampleDone = 1, resp = 0; // int sli = 0; // SampleLocationIndex // Organism* sampleOrgPtr = firstOrganism(); // struct data_t response; // ostrstream responseStream((char*)response.text, DATALEN); // struct qry_t query; // int mrc = 0; // do { // // Check for messages // mrc = msgrcv(msgqid, &query, QRYSIZE, QUERY, IPC_NOWAIT); // if(mrc > 0) { // responseStream.seekp(0); // resp = 0; // switch(query.text) { // case BEGIN_MULTI: // sampleDone = 0; // break; // case END_MULTI: // sampleDone = 1; // break; // case FIRSTORGANISM: // sampleOrgPtr = firstOrganism(); // break; // case RANDOMORGANISM: // while(! (sampleOrgPtr = Location::theWorld[sli].randOrg())) { // sli = Location::randLoc(); // } // break; // case SPECIFICORGANISM: // sampleOrgPtr = findOrganism(query.value); // if(sampleOrgPtr == 0) { // responseStream << "Warning: couldn't get organism " << query.value << ends; // resp = 1; // } // break; // case FIRSTLOC: // sli = 0; // break; // case RANDOMLOC: // sli = Location::randLoc(); // break; // case SPECIFICLOC: // sli = query.value; // break; // case O_LOCATION: // if(sampleOrgPtr) // sli = sampleOrgPtr->index(); // else // sli = 0; // break; // case AUXLEN: // if(sampleOrgPtr) // responseStream << sampleOrgPtr->auxlen() << ends; // else { // responseStream << "Zero population here: " << Location::theWorld[sli] << endl; // } // resp = 1; // break; // case CYTOPLASM: // if(sampleOrgPtr) { // resp = 1; // responseStream << sampleOrgPtr->cytoMaterial() << ends; // } // break; // case TOTALOPROTEIN: // resp =1; // responseStream << Location::orgProteinSummary() << ends; // break; // case TOTALEPROTEIN: // resp = 1; // responseStream << Location::proteinSummary() << ends; // break; // case AVGPROTEIN: // if(sampleOrgPtr) { // resp = 1; // responseStream << sampleOrgPtr->avgProtein() << ends; // } // break; // case EFFICIENCIES: // if(sampleOrgPtr) { // resp = 1; // sampleOrgPtr->efficiencies(responseStream); // responseStream << ends; // } // break; // case PROTEINQTY: // if(sampleOrgPtr) { // resp = 1; // sampleOrgPtr->proteinqty(responseStream); // responseStream << ends; // } // break; // case ORGANISMID: // if(sampleOrgPtr) { // resp = 1; // responseStream << sampleOrgPtr->serial() << ends; // } // break; // case O_ENVIRONMENT: // if(sampleOrgPtr) { // resp = 1; // sampleOrgPtr->myEnv(responseStream); // responseStream << ends; // } // break; // case NET_EFFECT: // if(sampleOrgPtr) { // resp = 1; // sampleOrgPtr->netEfficiencies(responseStream); // responseStream << ends; // } // break; // case BIOMASS: // resp = 1; // responseStream << Location::biomassSummary() << ends; // break; // case REDBIO: // resp = 1; // responseStream << Location::biomassSummary(1) << ends; // break; // case POPULATION: // resp = 1; // responseStream << grossPop << ends; // break; // case SERIAL: // if(sampleOrgPtr) { // resp = 1; // responseStream << sampleOrgPtr->sn() << ends; // } // break; // case TIME: // resp = 1; // responseStream << now << endl << ends; // break; // case MASSTOTAL: // resp = 1; // biomass = Location::biomassSummary(1); // resources = Location::resourceSummary(1); // responseStream << biomass + resources << ends; // break; // case RESRCSUMMARY: // resp = 1; // resources = Location::resourceSummary(0); // responseStream << resources << ends; // break; // case LOCATION: // responseStream << sli << " " << "X: " << Position::indexToX(sli); // responseStream << " Y: " << Position::indexToY(sli) << " pop: "; // responseStream << Location::theWorld[sli].locationPop(); // responseStream << " protein: " << Location::theWorld[sli].proteinCount() << "\n"; // responseStream << (Material&) Location::theWorld[sli] << ends; // break; // default: // resp = 1; // responseStream << "Query " << query.text << " not implemented." << ends; // break; // } // response.type = TEXTRESPONSE; // // cerr << "Sending msg type " << response.type << " >>" << response.text << "<<" << endl; // if(resp) { // if(msgsnd(msgqid, &response, DATALEN, 0)) // perror("MSGSND"); // resp = 0; // } // } // end of query processing // } while((! sampleDone ) || (mrc > -1)); // } extern "C" void ##### -> HandleUSR1(int sig) { ofstream logFile(logFileName, ios::app); time_t ltime; time(<ime); logFile << "Caught SIGUSR1 at " << ctime(<ime) << " " << now << endl; // logFile << "Setting sampleP to TRUE" << endl; // sampleP = 1; signal(SIGUSR1, HandleUSR1); } extern "C" void ##### -> HandleUSR2(int sig) { ofstream logFile(logFileName, ios::app); time_t ltime; time(<ime); logFile << "Caught SIGUSR2 at " << ctime(<ime) << " " << now << endl; logFile << "Total population = " << Location::WorldPop() << endl; signal(sig, HandleUSR2); } extern "C" void ##### -> HandleHUP(int sig) { REREAD = 1; // defer reread until end of jiffy signal(sig, HandleHUP); } /* ** Cleanup for SIGTERM ** ** fclose logFile; ** remove pid file ** fclose history file ** */ extern "C" void ##### -> HandleTERM(int sig) { msgctl(msgqid, IPC_RMID, (struct msqid_ds*) 0); epilogue("SIGTERM"); exit(2); } extern "C" void ##### -> HandleINT(int sig) { msgctl(msgqid, IPC_RMID, (struct msqid_ds*) 0); epilogue("SIGINT"); exit(2); } /* ** The output data file format is: ** "Addr: " Offset ** Run Description ** Command line text ** [INPUT] ** Input data ** [DATA] ** Binary data */ ##### -> main(int argc, char** argv, char** argve) { Date end; int samplePeriod = 0; int runTime = 0; int i; int c, pid = getpid(); // int key = DEFAULTKEY; // int port = DEFAULTPORT; Organism* op = 0; float totalMass; // Set up default config file name. strcpy(ConfigFileName, "config"); //make sure that unmentioned variables are defined for(int i=0; i 0) { switch (c) { /* ** allocation styles ** a - proportionate to ability ** b - bids ** c - per capita */ case 'c': strncpy(ConfigFileName, optarg, MAXPATHLEN); break; case 'k': // key = atoi(optarg); cerr << "IPC no longer supported. Option -k ignored." << endl; break; case 'p': // port = atoi(optarg); cerr << "IPC no longer supported. Option -p ignored." << endl; break; /* ** runTime is in years. */ case 't': samplePeriod = atoi(optarg); break; case 'y': runTime++; end = Date(atof(optarg)); break; default: cerr << "Unknown option: -" << char(c) << " ignored" << endl; break; } } /* ** set up queue for data requests */ // msgqid = msgget(key, IPC_CREAT | 0600); // if(msgqid < 0) { // perror("Evolve: msgget()"); // exit(1); // } // The default log file is the concatenation of // the config file name, the string '-'PID and // the file extension "log". char *lfp = ConfigFileName+strlen(ConfigFileName); while(*lfp != '/' && lfp != ConfigFileName) lfp--; if(*lfp == '/') lfp++; strncpy(logFileName, lfp, MAXPATHLEN-11); int tmplen = strlen(logFileName); sprintf(logFileName+tmplen, "-%d.log", pid); struct stat statbuf; // If the config file can't be found there's no point in continuing if(lstat(ConfigFileName, &statbuf)) { cerr << "Can't stat " << ConfigFileName << endl; perror("Stat"); exit(1); } // Open the log file and record some information about // the run that's about to start ofstream logFile(logFileName); struct utsname myhost; if(uname(&myhost) < 0) { cerr << "Can't get host info!" << endl; } logFile << "Running on " << myhost.nodename << " (" << myhost.machine << ") "; logFile << "\nOS: " << myhost.sysname << " " << myhost.release << "."; logFile << myhost.version << endl; logFile << " with command: "; for(int ii=0; ii< argc; ii++) { logFile << argv[ii] << " "; } logFile << "PID: " << pid << endl; logFile << "Config file: " << ConfigFileName << " " << ctime(&statbuf.st_mtime) << endl; char cwdir[MAXPATHLEN+1]; if(! getcwd(cwdir, MAXPATHLEN)) { cerr << "Error getting current directory: "; perror(argv[0]); exit(1); } logFile << "Working directory " << cwdir << endl; /* ** Initialization */ // RTable.readIn(); // Protopeptide::readIn(StdGenePath); // Protopeptide::readFunctions(); XBar = YBar = -1; parse(ConfigFileName, logFile); logFile << "Total Material: " << Location::resourceSummary(1) + Location::biomassSummary(1) << endl; logFile << "Initialized " << XDim << " by " << YDim << " locations with "; long int grossPop=Location::WorldPop(); logFile << grossPop << " organisms." << endl; time_t ltime; time(<ime); logFile << "Starting run at " << ctime(<ime); Date sampleNow; signal(SIGHUP, HandleHUP); signal(SIGINT, HandleINT); signal(SIGUSR1, HandleUSR1); signal(SIGUSR2, HandleUSR2); signal(SIGTERM, HandleTERM); BiotaIterator* bip; Literator lit; sampleP = 0; while(grossPop){ if(samplePeriod) sampleP = now.afterp(sampleNow); Location::updateShare(); lit.reset(); /* ** For each location */ // if(sampleP) // logFile << now << endl; while((i = lit.getOne()) >= 0) { bip = new BiotaIterator(&Location::theWorld[i]); // for each organism within the location while(op = bip->getNext()) { op->live(); } delete(bip); // done with one location } // sample(); // See if any sample requests have come in if(sampleP) { datalog(pid); sampleNow.incrementDate(samplePeriod); sampleP = 0; } Date::advanceDate(ClockTick); now.refresh(); grossPop = Location::WorldPop(); maxPop = max(grossPop, maxPop); if(runTime && now.afterp(end)) break; if(REREAD) { // if(yyin) { yyin = fopen(ConfigFileName, "r"); PASS = 2; for(int j = 0; j < XDim; j++) { GX = j; for(int k=0; k< YDim; k++) { GY = k; int lindex = Position::getIndex(j,k); rewind(yyin); EnVar::setDefaults(envec); yyparse(); Location::theWorld[lindex].setBaseline(envec); // sets baseline } } // } logFile << "Caught SIGHUP at " << ctime(<ime) << " / " << now << " Rereading config file" << endl; REREAD = 0; fclose(yyin); } Location::decompose(); // background decomposition } epilogue(); } Top 10 Lines: Line Count 260 7 72 1 95 1 Execution Summary: 244 Executable lines in this file 9 Lines executed 3.69 Percent of the file executed 9 Total number of line executions 0.04 Average executions per line *** File /home/dnikce/evolve/faster/mylist.h: #ifndef _MYLIST_H_ #define _MYLIST_H_ /* ** RCSID = $Id: mylist.h,v 1.4 2001/06/29 18:06:00 jjb Exp $ */ #include "defs.h" #include "Pix.h" #include #include //extern ofstream& cerr; class BaseNode { public: BaseNode* fd; BaseNode() {fd = 0;} Pix getNext() {return fd;} }; class BaseList { public: // friend template class List; BaseNode* listHead; BaseList() {listHead = (BaseNode*)0;} ##### -> virtual ~BaseList() { } void clear() { BaseNode* q,*p = listHead; while(p) { q=(BaseNode*)getNext(p); delete p; p=q; } listHead=0; } void prepend(Pix); void append(Pix); BaseNode* remove(Pix); Pix getLast(); Pix removeLast(){return remove(getLast());} Pix getFirst() {return (Pix)listHead;} Pix removeFirst() {return remove(getFirst());} Pix getNth(int); Pix getSome(); Pix removeSome() {return remove(getSome());} Pix getNext(Pix p){return ((BaseNode*)p)->fd;} int length(); int empty(){return listHead==0;} }; template class Node : public BaseNode { public: T datum; Node() {}; Node(T d, Node* n = 0) : datum(d) {fd = n;} T operator()() {return datum;} Node(Node& nr) { datum = nr.datum; fd = 0; } }; template class List : public BaseList { // friend ostream& operator<<(ostream&, List&); public: Pix find(T t) { Node* ptr = (Node*)listHead; while(ptr && (ptr->datum != t)) { ptr = (Node*)ptr->fd; } if(!ptr) cerr<<"Find failed to find " <"; clear(); } void prepend(T d) { BaseList::prepend((Pix)new Node(d)); } void append(T d) { BaseList::append((Pix) new Node(d)); } BaseNode* remove(T t) { return BaseList::remove(find(t)); } T operator()(Pix p) { if(p) return ((Node*)p)->datum; else { cerr << "List::operator() Null Pix" << endl; exit(1); } } T getFrst() { Pix p = getFirst(); return (*this)(p); } T getRand() { Pix p = getSome(); return (*this)(p); } T takeFirst() { Pix p = getFirst(); T rv; if(p) { rv = ((Node*)p)->datum; delete remove(((Node*)p)->datum); } else rv = 0; return rv; } void concat(List&); void merge(List& lr) { BaseList::append(lr.listHead); lr.listHead = 0; } }; /* template */ /* ostream& operator<<(ostream& os, List& lr) { */ /* Node* ptr; */ /* ptr = (Node*)lr.getFirst(); */ /* while(ptr) { */ /* cerr << ptr->datum << " "; */ /* ptr = (Node*)ptr->fd; */ /* } */ /* return cerr << endl; */ /* }/**/ template List::List(List& lr) { if(lr.listHead == 0) { listHead = 0; return; } Node* ptr = (Node*)lr.getFirst(); Node* n = new Node (ptr->datum); listHead = (BaseNode*)n; ptr = (Node*)(ptr->fd); while(ptr) { n->fd = new Node(ptr->datum); n = (Node*) n->fd; ptr = (Node*)(ptr->fd); } } template void List::concat(List& lr) { if (lr.listHead == 0) return; Pix ptr = lr.getFirst(); while(ptr) { append(lr.ptr); ptr = lr.getNext(ptr); } } #endif Top 10 Lines: Line Count 92 528774 63 8611 Execution Summary: 34 Executable lines in this file 1 Lines executed 2.94 Percent of the file executed 537385 Total number of line executions 15805.44 Average executions per line *** File /home/dnikce/evolve/faster/env.h: #ifndef _ENV_H_ #define _ENV_H_ #include #include "mylist.h" #include "myset.h" #include "position.h" #include "material.h" #include "envars.h" #include "config.h" #include "protein.h" #include "defs.h" #define defaultX 10 #define defaultY 10 #define MeanMass 176468 /* RCSID = $Id: env.h,v 1.32 2001/11/14 16:48:47 jjb Exp jjb $ * * $Log: env.h,v $ * Revision 1.32 2001/11/14 16:48:47 jjb * Removed tempMem * * Revision 1.31 2001/11/12 08:43:07 jjb * Added tempMem for debugging purposes * * Revision 1.30 2001/11/05 17:40:19 jjb * Possibly incomplete mod to allow genetic control of mutation rate and * criticalWeight * * * The environment comprises a series of locations, * each of which has a set of biota that currently occupy * that position, a set of materials that exist at that * position and a vector of environmental variables that * describe the environment at that particular location. */ typedef double EnVar_t; class Location; class Organism; class EnVar { friend ostream& operator<<(ostream&, const Location&); friend ostream& operator<<(ostream&, const EnVar&); friend class Location; private: static EnVar_t defaults[ENVSIZE]; /* Baseline is set only from config file. Modified is changed */ /* at every time step. */ EnVar_t baseline[ENVSIZE]; EnVar_t modified[ENVSIZE]; public: EnVar() { setDefaults(baseline); for(int i=0; i biota; List proteins; friend void parse(); public: static Material resourceSummary(int=0); static Material biomassSummary(int=0); Material locationResourceSummary(int=0); Material locationBiomassSummary(int=0); static void updateShare(); static void decompose(); static int randLoc(); int getShare(Material& mr, double *rates){ for(int i=0; i0?(rates[i] * ((Material&)(*this))[i] / rateTotals[i]):0); } return (int)(rateTotals[NMat]>0?(proteinCount() * rates[NMat]/rateTotals[NMat]):0); } double envFactor(int, int); static void materialReport(ofstream&); static void envReport(ofstream&); void biotaReport(ofstream&); static Material_t proteinSummary(); static long int orgProteinSummary(); static long int WorldPop(); int locationPop() {return biota.length();} int floaterPop(); void resources(ostream& os) { os << *this; } Material_t proteinCount() { Material_t rc = 0; Pix p = proteins.getFirst(); while(p) { rc += proteins(p)->qty(); p = proteins.getNext(p); } return rc; } static void setNLoc(int n) {NLoc = n;} static Location* theWorld; Location(){ rateTotals =new double[NMat+1]; } Location(int X, int Y, EnVar_t* er, const Material& mr) : Position(X,Y), EnVar(er), Material(mr){ rateTotals =new double[NMat+1]; } void insertBiota(Organism* op){biota.prepend(op);} void removeBiota(Organism*); ~Location() { biota.~List(); delete rateTotals; } static void printWorld(ostream&); void addProtein(Protein* psr[], int np) { for(int i=0; iqty()) { proteins.prepend(psr[i]); } else delete psr[i]; } } Protein* takeProtein(int amt=1) { Pix p = proteins.getFirst(); if(p == NULL) return NULL; Protein* ptr = proteins(p); float q = ptr->qty(); if(q <= amt) return proteins.takeFirst(); if(q > amt) return ptr->flake(amt); } Organism* firstOrg() { if(biota.length()) return biota.getFrst(); else return (Organism*) 0; } /* e is expressed as a percentage, not decimal */ Organism* encounter(const double e) { if(chance(e)) { return randOrg(); } else { return (Organism*)0; } } Organism* randOrg(){ if(biota.length()) return biota.getRand(); else return (Organism*) 0; } int blen() {return biota.length();} //log EnVars, Resources and Protein_Count void datalog(ostream& os) { ((EnVar*)this)->datalog(os); os << FS; ((Material*)this)->datalog(os); os << FS << proteinCount(); } void updateEnv(); double calculateModifier(int); }; class Literator { int* used; public: Literator(); ~Literator() {delete[] used;} int getOne(); void reset(); }; class BiotaIterator { Location* here; Pix nextOne; public: BiotaIterator(){} BiotaIterator(Location* h) {here = h; nextOne=h->biota.getFirst();} Organism* getNext(); Organism* getFirst(){ reset(); return getNext(); } void reset(){nextOne=here->biota.getFirst();} }; #endif Top 10 Lines: Line Count 65 36 70 36 Execution Summary: 57 Executable lines in this file 0 Lines executed 0.00 Percent of the file executed 72 Total number of line executions 1.26 Average executions per line *** File /home/dnikce/evolve/faster/material.h: /* ** RCSID = $Id: material.h,v 1.15 2001/11/14 16:47:47 jjb Exp $ ** $Log: material.h,v $ ** Revision 1.15 2001/11/14 16:47:47 jjb ** Removed assertion in exchangeMaterial() ** ** Revision 1.14 2001/11/12 10:23:55 jjb ** Added assertion at l. 55 ** */ #ifndef MATERIAL_H #define MATERIAL_H #include "defs.h" #include "config.h" #include "vector.h" #include #include #include #include #include #include "macro.h" class EnVar; //class Organism; class PeptideString; using namespace std; const int INT_SIGN = 1 << 31; #define SignBit(A) ((A) & INT_SIGN) class Material : public Vector { friend ostream& operator<< (ostream&, const Material&); public: static int *atwt; Material(Material_t x=0): Vector(NMat) { for(int i=0; i((Vector&) mr){ // ofile << "Material (copy): " << *this << endl; } Material(Material_t amt[]):Vector(NMat, amt) { // ofile << "Material (Vector): " << amt << endl; } Material(const Peptide*); Material(const PeptideString*); Material(const Vector& mr) : Vector(mr) { // cout << "Material constructor--Vector class" << endl; assert(mr.getSize() == NMat); } ~Material(){} // Here endeth the constructors /* ** Take and put material from (this). ** (this) is assumed to be entirely positive. ** If mr[i] < 0, take material from (this). ** If mr[i] > 0, put material into (this). ** Limit taken material to the amount available. ** Return the result. */ 939701 -> Material exchangeMaterial(const Material mr) { Material rc(Material_t(0)); for(int i=0; i= 0) { #ifdef IntMat rc[i] = mr[i]; #else rc[i] = floor(mr[i]); } #endif else { #ifdef IntMat rc[i] = max(mr[i], -(*this)[i]); // here's the assumption #else rc[i] = max(ceil(mr[i]), -(*this)[i]); #endif } (*this)[i] += rc[i]; } return rc; } void setMin(Material&mr) { for(int i=0; i Material operator+(const Material& mr) const { Material retval; int s1, s2, s3; for(int i=0; i<(NMat); i++) { retval[i] = (*(this))[i] + mr[i]; #ifdef IntMat s1 = (*(this))[i] & INT_SIGN; s2 = mr[i] & INT_SIGN; s3 = retval[i] & INT_SIGN; if(s1 == s2) assert(s3 == s1); #endif } return retval; } /* ** If the operands are of opposite signs, overflow may occur. ** In that case, I want to ensure that the sign of the result ** is the same as that of the subtrahend. */ Material operator-() const { Material rv; for(int i=0; i Material operator*(const Material_t factor) const { Material retval; for(int i=0; i< (NMat); i++) retval[i] = (*this)[i] * factor; return retval; } /* Material operator*(const double factor) const { Material retval; for(int i=0; i< (NMat); i++) retval[i] = (Material_t)((*this)[i] * factor); return retval; }*/ Material operator/(const Material_t divisor) const { assert(divisor != 0); Material retval; for(int i=0; i< (NMat); i++) retval[i] = (*this)[i] / divisor; return retval; } Material& operator+=(const Material& vr) { for(int i=0; i<(NMat); i++) (*this)[i] += vr[i]; return *this; } Material& operator-=(const Material& vr) { for(int i=0; i<(NMat); i++) (*this)[i] -= vr[i]; return *this; } Material& operator*=(const Material& vr) { for(int i=0; i= vr[i]) return 0; return 1; } int operator>(const Material& vr) const { for(int i=0; i<(NMat); i++) if((*this)[i] <= vr[i]) { return 0; } return 1; } int operator<=(const Material& vr) const { for(int i=0; i<(NMat); i++) if((*this)[i] > vr[i]) return 0; return 1; } int operator>=(const Material& vr) const { for(int i=0; i<(NMat); i++) if((*this)[i] < vr[i]) return 0; return 1; } // Returns true if any element is unequal int operator!=(const Material& vr) const { for(int i=0; i<(NMat); i++) if((*this)[i] != vr[i]) return 1; return 0; } /* ** All of the above are furnished by class Vector */ int operator==(const Material_t val) const { for(int i=0; i<(NMat); i++) if((*this)[i] != val) return 0; return 1; } int operator<(const Material_t val) const { for(int i=0; i<(NMat); i++) if((*this)[i] >= val) return 0; return 1; } int operator>(const Material_t val) const { for(int i=0; i<(NMat); i++) if((*this)[i] <= val) return 0; return 1; } int operator<=(const Material_t val) const { for(int i=0; i<(NMat); i++) if((*this)[i] > val) return 0; return 1; } int operator>=(const Material_t val) const { for(int i=0; i<(NMat); i++) if((*this)[i] < val) return 0; return 1; } int operator!=(const Material_t val) const { for(int i=0; i<(NMat); i++) if((*this)[i] != val) return 1; return 0; } /* ** End of operators */ int threshold(int=0, int=NMat-1, Material_t=0); //smallest amino acid ratio // suspect -- depends on knowing which are amino acids // float minRat(Material&); // //find product: negative is substrate for decomposition // int findProduct(); //returns index of smallest item int findMin(int=FirstElem, int=NMat-1); //returns index of largest item int findMax(int=FirstElem, int=NMat-1); /* ** Reduce this to a maximum of limit */ // void ceil(Material&); // /* // ** Limit this to a mimimum of limit // */ // void floor(Material&); static int getwt(int i) {return atwt[i];} static void setwt(int i, int v) {atwt[i] = v;} Material_t getMass(); Material_t getMassT(); float getMassF(); Material_t set(int i, Material_t v) {return ((*this)[i] = v);} Material_t get(int i) {return ((*this)[i]);} Material_t incr(int i, Material_t n = 1) {return (*this)[i] += n;} void excess(Material*, Material*); int negCheck(Material_t = 0); void totalDecompose(); void partialDecompose(double); void clear(Material_t x = 0) {for(int i=0; i<(NMat); i++) (*this)[i] = x;} void datalog(ostream&); }; // Reactants in a reaction are positive, and products are negative. // There may be more than one reactant and more than one product. class Reaction : public Material { friend ostream& operator <<(ostream&, Reaction&); friend class ReactionTable; double KC; public: Reaction(){KC = 0;} Reaction(Material_t r[], double ec) : Material(r){ KC = ec; } Reaction(const Reaction& rr) : Material(rr) { KC = rr.KC; } void react(double, Material&); int equilibriumP(Material&); double getKC() { return (KC); } }; class ReactionTable { friend ostream& operator<<(ostream&, ReactionTable&); int size; Reaction* table; public: 1 -> ReactionTable(int rs=0): size(rs) { if(rs) table = new Reaction[rs]; else table = 0; } ~ReactionTable() { if(size) delete[] table; } void initialize(Material_t* mp, double* ecp) { for(int i=0; i= size) { cerr<<"ReactionTable index "<< indx <<" out of bounds." << endl; abort(); } return table[indx]; } ReactionTable& resize(int s) { if(size != 0) { delete[] table; } size = s; table = new Reaction[size]; } }; #endif /*MATERIAL*/ Top 10 Lines: Line Count 59 939701 153 60631 158 17411 112 1038 33 71 36 1 353 1 Execution Summary: 72 Executable lines in this file 4 Lines executed 5.56 Percent of the file executed 1018854 Total number of line executions 14150.75 Average executions per line *** File /home/dnikce/evolve/faster/vector.h: #ifndef _VECTOR_H_ #define _VECTOR_H_ #include #include /* RCSID = $Id: vector.h,v 1.3 2001/06/29 18:08:08 jjb Exp $ ** ** This is the simple case. The index is 0-based. ** No provision is made for expansion. */ template class Vector { /* friend istream& operator>>(istream&, Vector); */ /* friend ostream& operator<<(ostream&, Vector&); */ int size; T* data; /* int rangecheck(int x) const*//* {return (x >= 0) && (x < size);}*/ public: Vector() { size = 0; data = 0; } 40775834 -> Vector(int sz, T val=0) { size = sz; if(size) { data = new T[size]; for(int i=0; i Vector(const Vector& vr) { size = vr.size; if(size) { data = new T[size]; for(int i=0; i& subVec(int start, int length) { assert(size >= length+start); Vector* rv = new Vector(length); for(int i=0; idata[i] = data[i+start]; return *rv; }*/ /* ** This is for the memory mapped instances that never get ** constructed. */ int getSize() const {return size;} const T& operator[] (int i) const { /*assert(rangecheck(i));*/ return *(data + i); } T& operator[] (int i) { return *(data + i); } /* ** This looks ambiguous ** T operator[](int i) const { ** assert(rangecheck(i)); ** return data[i]; ** } */ T readOnly(int i) const { /* assert(rangecheck(i));*/ return data[i]; } /* ** Binary operations on vectors of inequal size ** are not supported. ** ** Functions that return Vector cannot be made ** virtual. */ Vector operator+(const Vector& vr) const { Vector retval(size); for(i=0; i operator-(const Vector& vr) const { Vector retval(size); for(int i=0; i operator*(const T factor) const { Vector retval (size); for(int i=0; i< size; i++) retval.data[i] = data[i] * factor; return retval; } Vector operator/(const T divisor) const { assert(divisor != 0); Vector retval (size); for(int i=0; i< size; i++) retval.data[i] = data[i] / divisor; return retval; } ##### -> virtual Vector& operator+=(const Vector& vr) { for(int i=0; i& operator-=(const Vector& vr) { for(int i=0; i& operator*=(const T mult) { for(int i=0; i< size; i++) data[i] = (T)(data[i] * mult); return *this; } Vector& operator/=(const T divisor) { for(int i=0; i< size; i++) data[i] = (T)(data[i] / divisor); return *this; } ##### -> virtual int operator==(const Vector& vr) const { for(int i=0; i virtual int operator<(const Vector& vr) const { for(int i=0; i= vr.data[i]) return 0; return 1; } ##### -> virtual int operator>(const Vector& vr) const { for(int i=0; i virtual int operator<=(const Vector& vr) const { for(int i=0; i vr.data[i]) return 0; return 1; } ##### -> virtual int operator>=(const Vector& vr) const { for(int i=0; i virtual int operator!=(const Vector& vr) const { for(int i=0; i virtual Vector& operator=(const Vector& vr) { assert(size == vr.size); for(int i=0; i #include "protopeptide.h" #include #include #include extern int Organism_ID; extern int Gene_ID; const int Chromosome::RegLen=RSL; const int Chromosome::IntegerLen = 6; const int Chromosome::DecimalLen = 2; const char Chromosome::PAD='0'; ##### -> void Chromosome::ftos(float in, char* workspace, int len) { if(in>9999999 || (in<.01 && in!=0)) cerr << "ftos(): representational bounds exceeded: " << in << endl; char integer[Chromosome::RegLen+2], decimal[Chromosome::RegLen+2]; for(int i=0; i float Chromosome::stof(char* in, int len) { if(len>Chromosome::RegLen) cerr << "stof(): input string too long. Truncating" << endl; char temp[Chromosome::RegLen+2]; for(int i=0; i Chromosome::Chromosome(Peptide* pp) : PeptideString(pp), Material(pp) { int np = nGene = geneCount(); Peptide* ptr = 0; Peptide* a; Peptide* b; genes = new (Gene*)[nGene]; b = pstring; for(int i=0; i Chromosome::Chromosome(Chromosome& cr, double rate) : PeptideString((PeptideString&)cr), nGene(cr.nGene) { Peptide* pptr=0, *tmpptr; Peptide* begin; int len, g, t; char* b; PeptideString* newGene; Gene** newGenes; genes = new (Gene*)[nGene]; for(int i=0; i z1_Rnd::RNG->Gen1()) { int target = int(nGene * z1_Rnd::RNG->Gen1()); PeptideString* newGene = subString(genes[target]->offset, genes[target]->length); prependGene(newGene); for(int t=0; toffset += genes[target]->length; newGenes = new Gene*[++nGene]; newGenes[0] = new Gene(*(genes[target]), 1); // request new protein newGenes[0]->offset = 0; for(int i=nGene-1; i>0; i--) newGenes[i] = genes[i-1]; delete newGene; delete[] genes; genes = newGenes; } // end of gene doubling if(GeneDeletionRate > z1_Rnd::RNG->Gen1()) { /* ** delete a gene */ int target = int(nGene * z1_Rnd::RNG->Gen1()); int len = genes[target]->length; replaceGene(genes[target]->offset, genes[target]->length, PeptideString::NIL); delete genes[target]; nGene--; for(int i=target; ioffset -=len; } genes[nGene]=0; } // end of gene doubling and deletion // dist is the Hamming distance, or number of // mutations, to make and is rate X chromosome length double dist = rate * length; int idist = int(floor(dist)); if((dist-double(idist)) > z1_Rnd::RNG->Gen1()) idist++; struct mutret_t rc; for(int i=0; ioffset > rc.offset) genes[g]->offset += shiftVal; else gindex = g; } // genes have now been shifted as needed // gene g's offset is <= rc.offset, so // it either contains the mutation or // the intron following it does. // There are five possibilities: // genes[g]->offset > rc.offset && g == 0 // Mutation before 1st gene // genes[g]->offset == rc.offset < genes[g]->offset + genes[g]->length-1 // Mutation of START codon for gene g // genes[g]->offset < rc.offset < genes[g]->offset + genes[g]->length-1 // Mutation lies between START and STOP of gene g // genes[g]->offset < rc.offset == genes[g]->offset + genes[g]->length-1 // Mutation of the STOP codon of gene g // genes[g]->offset < rc.offset > genes[g]->offset + genes[g]->length-1 // Mutation lies beyond STOP codon of gene g // Cases one and five require no modification to the gene set Gene* tmpGene; if(gindex == -1) break; g = gindex; if(genes[g]->offset == rc.offset) { // case 2 // The start codon of gene g was affected by the mutation switch(rc.type) { case 'i': // if the new codon is a START, it makes the gene longer by 1 // else, just change the offset of gene g. if(pstring[rc.offset] == 's') { tmpGene = new Gene(this, rc.offset, genes[g]->length+1, 11, genes[g]->showMutations()); delete genes[g]; genes[g] = tmpGene; } else genes[g]->offset++; break; case 'd': // the start codon has been deleted // need to look up the new gene. genes[g]->length--; tmpGene = new Gene(this, rc.offset, genes[g]->length, 12, genes[g]->showMutations()); if(tmpGene->length) { delete genes[g]; genes[g] = tmpGene; } else { // there's no gene at all anymore nGene--; for(int t=g; toffset, genes[g]->length, 13, genes[g]->showMutations()); if(tmpGene->length == 0) { delete genes[g]; delete tmpGene; nGene--; for(int t=g; tprotein == NULL) cerr << "Oops1 Just added a gene with a null protein ptr" << endl; } break; } // end of switch continue; } // end of case 2 -- mutated START codon section // Case 3 -- mutation lies between gene g's START and STOP codons if((genes[g]->offset < rc.offset) && (rc.offset < (genes[g]->offset + genes[g]->length - 1))) { // The mutation lies somewhere in this gene, but start and // stop codons are not affected switch(rc.type) { case 'i': // a new amino acid has been inserted into gene genes[g]->length++; tmpGene = new Gene(this, genes[g]->offset, genes[g]->length, 14, genes[g]->showMutations()); if(tmpGene->length < genes[g]->length) { if(tmpGene->protein == NULL) cerr << "Oops2 Just added a gene with a null protein ptr" << endl; // a STOP was inserted // there may be a new shorter gene followed by junk // or two shorter genes. // the first begins at genes[g]->offset and is at tmpGene delete genes[g]; genes[g] = tmpGene; // see if there is a second one tmpGene = new Gene(this, genes[g]->offset + genes[g]->length, genes[g+1]->offset - (genes[g]->offset + genes[g]->length), 15, genes[g]->showMutations()); if(tmpGene->length) { // make room for the second gene after g nGene++; newGenes = new Gene*[nGene]; for(int t=0; t<=g; t++) newGenes[t] = genes[t]; newGenes[g+1] = tmpGene; if(genes[g+1]->protein == NULL) cerr << "Oops3 Just added a gene with a null protein ptr" << endl; for(int t=g+2; tlength++; delete genes[g]; genes[g] = tmpGene; } break; case 'd': // an amino acid has been deleted // no gene fragmentation possible genes[g]->length--; tmpGene = new Gene(this, genes[g]->offset, genes[g]->length, 16, genes[g]->showMutations()); delete genes[g]; genes[g] = tmpGene; if(tmpGene->protein == NULL) cerr << "Oops4 Just added a gene with a null protein ptr" << endl; break; case 's': // an amino acid was substituted // it might be a STOP tmpGene = new Gene(this, genes[g]->offset, genes[g]->length, 17, genes[g]->showMutations()); if(tmpGene->length < genes[g]->length) { // a STOP was substituted // there may be a new shorter gene followed by junk // or two shorter genes. // the first begins at genes[g]->offset and is at tmpGene if(tmpGene->protein == NULL) cerr << "Oops5 Just added a gene with a null protein ptr" << endl; delete genes[g]; genes[g] = tmpGene; // see if there is a second one tmpGene = new Gene(this, genes[g]->offset + genes[g]->length, genes[g+1]->offset - (genes[g]->offset + genes[g]->length), 18, genes[g]->showMutations()); if(tmpGene->length) { // make room for the second gene after g if(tmpGene->protein == NULL) cerr << "Oops6 Just added a gene with a null protein ptr" << endl; nGene++; newGenes = new Gene*[nGene]; for(int t=0; t<=g; t++) newGenes[t] = genes[t]; newGenes[g+1] = tmpGene; for(int t=g+2; tprotein != tmpGene->protein); delete genes[g]; genes[g] = tmpGene; } break; } //end of switch(rc.type) continue; } // end of case 3 // Case 4 -- mutation of the STOP codon if(rc.offset == (genes[g]->offset + genes[g]->length - 1)) { // The mutation affected the stop codon // if rc.type == 'i', just increment the length and look up the gene. // if rc.type == 'd' or rc.type == 's', the stop codon // is gone, and unless there's another stop codon between // rc.offset and the start of the next gene, the current gene // and the next have merged together. // Find the next stop codon. If it is after the start of the next gene, // then delete the next gene , decrement nGene // and shift the remaining genes down by one. Look up the current gene. // Else, there was another stop codon in an intron between this gene and // the next, so just look up the current gene and replace it. switch(rc.type) { case 'i': // a new amino acid has been inserted into the gene // replace gene with a new one tmpGene = new Gene(this, genes[g]->offset, genes[g]->length+1, 19, genes[g]->showMutations()); delete genes[g]; genes[g] = tmpGene; if(tmpGene->protein == NULL) cerr << "Oops7 Just added a gene with a null protein ptr" << endl; break; case 'd': // the stop codon has been deleted genes[g]->length--; // note that this is supposed to fall through to the next case case 's': // the stop codon has been replaced // If g isn't the last gene, the comment above is valid. // If g == nGene-1, the last gene is really spliced on to the first // one due to the circular form of the chromosome. // Replace the first and delete the last... if(g < nGene - 1) { // not the last gene // verify that the deletion really formed one gene len = genes[g+1]->offset + genes[g+1]->length - genes[g]->offset; tmpGene = new Gene(this, genes[g]->offset, len, 20, genes[g]->showMutations()); if(tmpGene->length == len) { // there is one supergene delete genes[g]; genes[g] = tmpGene; if(tmpGene->protein == NULL) cerr << "Oops8 Just added a gene with a null protein ptr" << endl; nGene--; for(int t=g+1; toffset, length - genes[g]->offset, 21, genes[g]->showMutations()); if(tmpGene->protein) genes[g] = tmpGene; else { // need to move end of string to head. // split removes the tail of this and returns a // pointer to it. newGene = split(genes[g]->offset); insert(newGene,0); // update offsets len = newGene->plen(); for(t=0; toffset += len; // string is modified, and gene offsets // have been compensated delete tmpGene; tmpGene = new Gene(this, 0, genes[0]->offset + genes[0]->length, 22, genes[0]->showMutations()); if(tmpGene->length == genes[0]->length + genes[0]->offset) { // There is one supergene, so just replace genes[0] with it delete genes[0]; genes[0] = tmpGene; // There is one less gene now. nGene--; genes[nGene] = (Gene*)5; } else { // There are two genes. This can result when there // is a solitary STOP codon in the initial intron. // The second gene is the one in genes[0]. // Move all gene pointers to the right by one for(int t=nGene-1; t>0; t--) genes[t] = genes[t-1]; // The new gene is gene 0 and the old gene 0 is gene 1. genes[0] = tmpGene; } } // done with mutation } // end of stop-codon-of-last-gene-is-gone break; } // end of switch } // end of case 4 }//end of one mutation cycle pstring[length] = '\0'; // insurance (Material&)(*this) = Material(pstring); } /* ** It is essential that the number of returns from ** getGene() agree with the value returned by ** PeptideString::geneCount(). Otherwise, the ** vector, Organism.protein, won't have the right ** length. geneCount() returns the number of ** of START codons that follow a STOP codon, plus ** the initial START codon. That is the same as the ** number of genes bounded by both START and STOP ** codons plus, potentially, the string bounded by ** a START codon and the string's terminating null. ** ** PeptideString::nextGene() just advances the ** pointer to the first character in the next ** gene, or to the terminating null character. ** getGene()'s algorithm needs to check for a ** START codon in nextGene()'s return and prune ** the head of the string back to RegLen chars before ** the START codon. If there is no START, we skip ** to the next return from nextGene(). ** */ // This may no longer be correct. It is no longer used. Peptide* ##### -> Chromosome::getGene(Peptide** mem) { if(! *mem) /* Starting with a NULL pointer begins at start */ *mem = pstring; Peptide* startPtr = *mem; Peptide* endPtr; Peptide* EPIStart = startPtr; int geneLength; Peptide* geneBuffer; /* ** keep at this until we find either a START codon ** (and nextGene() has found the STOP) or the terminating NULL. */ do { nextGene(mem); /* advance past STOP or to NULL */ endPtr = *mem; /* ** search current gene from start to new end ** startPtr will either point to a START codon, or to ** the thing pointed at by endPtr: the first codon of ** the next gene or to a NULL. */ while((*startPtr != START) && (startPtr < endPtr)) startPtr++; switch(*startPtr) { case START: EPIStart = ((startPtr-EPIStart) > RegLen)? (startPtr-RegLen): EPIStart; geneLength = endPtr - EPIStart; geneBuffer = new Peptide[geneLength + 1]; strncpy(geneBuffer, EPIStart, geneLength); geneBuffer[geneLength] = '\0'; return geneBuffer; break; case STOP: /* double (or more) STOP. Keep trying */ break; case (char)NULL: /* no START before end of peptide string */ return NULL; break; default: /* no START; try next gene */ /* what do you call a gene with no START */ break; } /* end of switch */ } while(1); } ##### -> ostream& operator<<(ostream& os, Chromosome& cr) { os << "Chromosome: " << (PeptideString&)cr << endl; os << cr.nGene << " genes: " << endl; for(int i=0; i #include #include #include #include #include PeptideString* PeptideString::NIL = new PeptideString(""); char *PeptideString::Alphabet; int PeptideString::AlphabetLength; extern ofstream& ofile; ##### -> PeptideString::PeptideString(int len) { pstring = new Peptide[len + 1]; length = len; for (int i=0; i PeptideString::init(int netamino) { // If net amino acids are < than 19 ('s') // add STOP if(netamino < 19) { NAmino = netamino + 1; Alphabet = new char[NAmino+1]; //leave room for start Alphabet[NAmino-1] = START; Alphabet[NAmino] = '\0'; } else { NAmino = netamino; Alphabet = new char[NAmino+1]; //leave room for start and stop Alphabet[NAmino] = '\0'; } for(int i=0; i PeptideString::upCase(int i, int len) { if(i >= length) return; if(i+len > length) len = length - i; for(int j=i; jpeptidestring ** at the location indicated by "where". Where points to ** the location of the first amino acid of the inserted ** material, so where==0 indicates that the new peptidestring ** will begin with p. If where<0, the insertion is made ** randomly. If where==strlen(polypeptide), the new peptidestring ** ends with p. */ void 1 -> PeptideString::insert(PeptideString* ps, int where) { int i; const int buflen = length + ps->length + 1; char* buf = new char[buflen]; if(where<0) where = int(z1_Rnd::RNG->Gen1() * length); for(i=0; ipstring); strcat(buf, pstring+i); delete[] pstring; pstring = buf; length += ps->length; } // Mutate this by one mutation, either substitution or // insertion/deletion. void 2666 -> PeptideString::mutateOnce(mutret_t& rs) { Urn* u1 = new Urn(length); if(u1== 0) { cerr << "Can't allocate urn" << endl; exit(1); } int j, ins; char c; j = u1->draw(); rs.offset = j; if (z1_Rnd::RNG->Gen1()>(INSProb + DELProb)) { // replacement while((c=rChar())==pstring[j]); pstring[j]=c; rs.type = 's'; } else { // insertion or deletion if(z1_Rnd::RNG->Gen1() > INSProb/(INSProb+DELProb)) { char ichar = rChar(); insertChar(j, ichar); rs.type = 'i'; } else { char* p = pstring+j, *q = pstring+j+1; while(*(p++) = *(q++)); length--; rs.type = 'd'; } } delete u1; } /* ** Mutate this to Hamming distance away by point mutations ** If insDel, allow insertions and deletions ** Otherwise, only replacement */ void PeptideString::mutate(const int insDel, const double distance, ##### -> const int allowCritical) { Urn* u1 = new Urn(length); int mutCrit = allowCritical; int j, ins; int count = int(distance); if(double(distance - count) > z1_Rnd::RNG->Gen1()) count++; assert(u1 > 0); assert(length>distance); // Don't intend any double mutations while(count) { char c; j = u1->draw(); if(count < criticalWeight) mutCrit = 0; if(! mutCrit) { while(isupper(pstring[j])) if((j = u1->draw()) < 0) { cerr << "PeptideString::mutate() ran out of choices" << endl; return; } } count -= (isupper(pstring[j]))?criticalWeight:1; assert(jGen1()>(INSProb + DELProb)) || (insDel == 0)) { // replacement while((c=rChar())==pstring[j]); pstring[j]=c; } else { // insertion or deletion if(z1_Rnd::RNG->Gen1() > INSProb/(INSProb+DELProb)) { char ichar = rChar(); length++; assert(j < length); char* newstr = new Peptide[length+1]; strncpy(newstr, pstring, j); newstr[j]=ichar; newstr[j+1] = '\0'; strcat(newstr, pstring+j); delete[] pstring; pstring = newstr; } else { char* p = pstring+j, *q = pstring+j+1; while(*(p++) = *(q++)); length--; } delete u1; u1 = new Urn(length); } // end else } /* end for(int i=0... */ delete u1; } Peptide* 2238 -> PeptideString::skipGene(Peptide* a, int cnt) { Peptide* p; if(a==0) p = pstring; else p = a; if(cnt <= 0) return p; int i = 0; while(*p) { if((*p++) == STOP) { if(++i == cnt) return p; } } return p; } void ##### -> PeptideString::replaceGene(Peptide* start, Peptide* next, PeptideString* raw) { int l1 = int(start-pstring); int l2 = int(next-start); length = length - l2 + raw->length; Peptide* newstr = new Peptide[length+1]; strncpy(newstr, pstring, l1); newstr[l1] = '\0'; if(raw->plen()) strcat(newstr, raw->pstring); strcat(newstr, next); delete[] pstring; pstring = newstr; } void 8 -> PeptideString::replaceGene(int offset, int len, PeptideString* raw) { int l1 = offset; length = length - len + raw->length; Peptide* newstr = new Peptide[length+1]; strncpy(newstr, pstring, l1); newstr[l1] = '\0'; if(raw->plen()) strcat(newstr, raw->pstring); strcat(newstr, pstring+len+offset); delete[] pstring; pstring = newstr; } void 20 -> PeptideString::prependGene(PeptideString* raw) { length = raw->length + length; Peptide* tempstr = new Peptide[length+1]; strcpy(tempstr, raw->pstring); strcat(tempstr, pstring); delete[] pstring; pstring = tempstr; } int 1 -> PeptideString::geneCount() const { Peptide* p = pstring; Peptide* q; int gs = 0; // "Gene State" int nProt = 0; while(*p) { switch(*p) { case START: if(!gs) { nProt++; } gs=1; break; case STOP: gs=0; break; default: break; } p++; } return nProt; } /* ** Modify the contents of p, so that it contains a ** pointer to the first codon following a valid gene. */ void 31 -> PeptideString::nextGene(Peptide** p) { Peptide* q = *p; Peptide* indx = *p; char state = 0; assert(q >= pstring); // cout << "q: " << (void*)q << "length: " << length << (void*) &(pstring[length]) << endl; assert(q <= &(pstring[length])); // first find a START -- state 1 while(*indx) { if(*indx==START) break; indx++; } if(*indx) { // found START -- state 2 while(*indx) { if(*indx++==STOP) { // -- state 3 *p = indx; return; } } // -- state 4 } *p = indx; // return NULL return; } PeptideString* 2258 -> PeptideString::subString(int start, int len) const { assert(start >= 0); PeptideString* rs = new PeptideString; if(len==-1) { // either tail or copy rs->length = length - start; } else rs->length = len; rs->pstring = new Peptide[rs->length+1]; if(rs->length) strncpy(rs->pstring, pstring+start, rs->length); rs->pstring[rs->length] = '\0'; return rs; } PeptideString* ##### -> PeptideString::subString(Peptide* pstart, int len) const { int start = pstart - pstring; assert(start >= 0); PeptideString* rs = new PeptideString; if(len==-1) { // either tail or copy rs->length = length-start; } else rs->length = len; rs->pstring = new Peptide[rs->length+1]; if(rs->length) strncpy(rs->pstring, pstring+start, rs->length); rs->pstring[rs->length] = '\0'; return rs; } // Split returns a new string that begins at *this[c] // and this becomes a string of length c PeptideString* 1 -> PeptideString::split(int c) { if(c==0) c=(int)(z1_Rnd::RNG->Gen1()*(strlen(pstring)-1)); PeptideString* rp = new PeptideString(pstring+c); Peptide* n = new Peptide[c+1]; strncpy(n, pstring, c); n[c] = '\0'; delete[] pstring; pstring=n; length=c; return rp; } char PeptideString::rChar() { return Alphabet[int(RANDOM * AlphabetLength)]; } ##### -> ostream& operator<<(ostream& os, const PeptideString& psr) { return os << psr.pstring; } /* ** This algorithm is from ** _Calculating_the_Secrets_of_Life_, ** (1995) National Academy Press ** E. S. Lander and M. S. Waterman, eds ** Since we have a maxMismatch, we can ** prune the search space. */ inline int PeptideString::delta(char a, char b) { // args are (library, unknown) // range of a, b is a through t and - (gap) /* ** The delta value is normally taken from a table that ** is based on the frequence with which one amino acid ** mutates into another. (See Dayhoff et al. Methods in ** Enzymology 91:524-45.) ** However, our concern is only whether there is a match ** or not. (If we had a table, it would be based on how ** the specific mismatches affect the function of the protein. */ if(a==b) return(0); else { // if(a=='-' || b=='-') // return(-1); if(isupper(a)) return(-criticalWeight); else return(-1); } } int ##### -> PeptideString::match1(PeptideString* const candidate, int maxmismatch) { int mismatch, i, j, N = candidate->plen(), M = this->plen(); int *thisCol=new int[N]; // corresponds to i-th column int *lastCol=new int[N]; // corresponds to i-1-th column int *temp; int m1, m2, m3; /* ** this points to the library string, and corresponds to A ** candidate points to the unknown, and corresponds to B ** calls to delta are delta(a, b) */ lastCol[0] = 0; // S[0,0] <- 0 for(j=1; jpstring[j])?0:-1; if(isupper(pstring[i])) del *= criticalWeight; /* thisCol[j] = max3((lastCol[j-1] + delta((*this)[i], (*candidate)[j])), (lastCol[j] + delta((*this)[i], '-')), (thisCol[j-1] + delta('-', (*candidate)[j]))); /**/ thisCol[j] = max3(lastCol[j-1] + del, lastCol[j] - 1, thisCol[j-1] - 1); /**/ rc = max(rc, thisCol[j]); } temp = thisCol; thisCol = lastCol; lastCol = temp; if(-rc > maxmismatch) { delete[] thisCol; delete[] lastCol; return maxmismatch; //break; } } if( -rc > maxmismatch) rc = maxmismatch; else rc = -thisCol[N-1]; delete[] thisCol; delete[] lastCol; return rc; } int 147708 -> PeptideString::match(PeptideString* const candidate, int maxmismatch) { int rc=abs(length - candidate->length); int len = min(length, candidate->length); for(int i=0; ipstring)[i]) rc += (isupper(pstring[i]))?criticalWeight:1; if(rc>maxmismatch) break; } return min(rc, maxmismatch); } int ##### -> PeptideString::mymatch(PeptideString* const candidate, int maxmismatch) { int error=0; char a,b; int i=0,j; PeptideStringIterator* li = new PeptideStringIterator(this); PeptideStringIterator* lj = new PeptideStringIterator(candidate); a=li->getNext(0); b=lj->getNext(0); while(error<=maxmismatch) { a=li->getNext(); b=lj->getNext(); while(a == b){ a=li->getNext(); b=lj->getNext(); if(a=='\0' && b=='\0') { delete(li); delete(lj); return error; } } // ofile << "Mismatch: " << a << " vs " << b << " E = " << error << endl; /* * Try to get past small errors by looking ahead for j characters. * Small means anything that would not indicate a complete mismatch. */ for(j=1,error+=(li->criticalP())?criticalWeight:1; error<=maxMismatch; j++,error+=(li->criticalP())?criticalWeight:1) { if(a == (b=lj->getNext(j))){ /*insertion*/ // ofile << "Insertion: " << error << endl; break; } if((a=li->getNext(j)) == (b=lj->getPrev(j))){ /*deletion*/ // ofile << "Deletion: " << error << endl; break; } if(a == (b=lj->getNext(j))){ /*substitution*/ break; } li->getPrev(j); lj->getPrev(j); } } delete(li); delete(lj); return error; } // int // PeptideString::countLines(char* inputFile) { // char buf[GLEN+GTOL+3]; // int lineCount = 0; // ifstream& is = *new ifstream(inputFile); // while(!is.eof()) { // is>>buf; // lineCount++; // } // return lineCount-1; // } // void // PeptideString::readIn(char* inputFile, PVector& list) { // char buf[GLEN+GTOL+3]; // int lineCount = list.getSize(); // ifstream& is = *new ifstream(inputFile); // for(int lp=0; lp>buf; // if(! is.eof() ) // list[lp]=new PeptideString(buf); // else // break; // } // } Top 10 Lines: Line Count 424 147708 82 2666 286 2258 175 2238 258 31 220 20 207 8 26 1 63 1 230 1 Execution Summary: 260 Executable lines in this file 19 Lines executed 7.31 Percent of the file executed 154933 Total number of line executions 595.90 Average executions per line *** File /home/dnikce/evolve/faster/env.C: static char RCSID[] = "$Id: env.C,v 1.47 2001/11/16 01:59:51 jjb Exp $"; // $Log: env.C,v $ // Revision 1.47 2001/11/16 01:59:51 jjb // syntax error fixup. // // Revision 1.46 2001/11/16 01:56:48 jjb // Added code for floaterPop() // // Revision 1.45 2001/11/16 01:48:16 jjb // changed LocationPop to floaterPop at l. 407 // // Revision 1.44 2001/11/14 16:49:54 jjb // Removed tempMem and its assertions. // // Revision 1.43 2001/11/12 08:51:54 jjb // qualified tempMem // // Revision 1.42 2001/11/12 08:49:40 jjb // 1. Added defDecomp to defaults. Just in case it's ever left undefined // in the config file. // 2. Added debugging assertions in decompose(). // // Revision 1.41 2001/11/12 00:27:09 jjb // Fixed syntax errors ll. 377,378 // // Revision 1.40 2001/11/12 00:05:41 jjb // Added calculations for halflife ll. 373-379 // #include #include #include "env.h" #include "organism.h" #include "random.h" #include #include "bioact.h" extern char AllocationStrategy; int Location::NLoc = 100; int ##### -> Location::randLoc() { return (int)floor(RANDOM * NLoc); } Material 2 -> Location::resourceSummary(int reduce) { Material rval(Material_t(0)); Protein* pp; Pix ap; for(int l=0; lqty(); ap = theWorld[l].proteins.getNext(ap); } } if(reduce) rval.totalDecompose(); return rval; } Material ##### -> Location::locationResourceSummary(int reduce) { Material rval(Material_t(0)); Protein* pp; Pix ap; rval += (Material) (*this); ap = proteins.getFirst(); while(ap) { pp = proteins(ap); rval += (Material)*pp * pp->qty(); ap = proteins.getNext(ap); } if(reduce) rval.totalDecompose(); return rval; } Material_t ##### -> Location::proteinSummary() { Material_t rval = 0; Protein* pp; Pix ap; for(int l=0; lqty(); ap = theWorld[l].proteins.getNext(ap); } } return rval; } Material 2 -> Location::biomassSummary(int reduce) { Material rval(Material_t(0)); Pix ptr; for(int l=0; lbiomass(); ptr = theWorld[l].biota.getNext(ptr); } } if(reduce) rval.totalDecompose(); return rval; } int ##### -> Location::floaterPop() { int count = 0; Pix ptr = biota.getFirst(); while(ptr) { if(biota(ptr)->sinkP() == 0) count++; } return count; } Material ##### -> Location::locationBiomassSummary(int reduce) { Material rval(Material_t(0)); Pix ptr; ptr = biota.getFirst(); while(ptr) { rval += biota(ptr)->biomass(); ptr = biota.getNext(ptr); } if(reduce) rval.totalDecompose(); return rval; } long int ##### -> Location::orgProteinSummary() { long int rval = 0; Pix ptr; for(int l=0; ltotalProtein(); ptr = theWorld[l].biota.getNext(ptr); } } return rval; } void ##### -> Location::materialReport(ofstream& lfile) { for(int i=0; i Location::envReport(ofstream& lfile) { for(int i=0; i Location::biotaReport(ofstream& lfile) { Pix ptr = biota.getFirst(); lfile << (Location&) *this < long int Location::WorldPop() { long int total = 0; for(int i=0; i EnVar::getDefaults(double p[]) { for(int i=0; i EnVar::datalog(ostream& os) { int i; for(i=0; i Location::removeBiota(Organism* op){ if(biota.find(op)==0) { cerr<<"Can't find "< Location::decompose() { Literator lit; int a; while((a=lit.getOne()) >= 0) { Location& here = theWorld[a]; Material& resources = (Material&)here; EnVar_t decompRate = ((EnVar)here)[EVdecomp]; Material decomp; Pix p = here.proteins.getFirst(); Protein* pp; while(p) { pp = here.proteins(p); decomp += pp->degrade(decompRate); p = here.proteins.getNext(p); if(pp->qty() == 0) { delete pp; delete (Node*) here.proteins.remove(pp); } } resources += decomp; decomp = 0; for(int i=0; i< NMat; i++) decomp[i] = int(resources[i] * decompRate); assert(((Material&) here) >= decomp); resources -= decomp; decomp.totalDecompose(); resources += decomp; } } // total uptake rates over all biota in // each location void 999 -> Location::updateShare() { Literator lit; int a; Organism* op; int pop; while((a=lit.getOne()) >= 0) { // set up the EnVar modifiers theWorld[a].updateEnv(); if(pop = theWorld[a].locationPop()) { for(int i=0; igetNext(); while(op) { op->calculateUptakeRates(); op->getUptakeRates((theWorld[a].rateTotals)); op = bip->getNext(); } delete bip; } } } // EnVar // EnVar::operator+(EnVar er) { // EnVar p; // for(int i=0; i Literator::reset() { for(int i=0; i Literator::Literator() { used = new int[Location::NLoc]; reset(); } int Literator::getOne() { int j; int i = j = int(z1_Rnd::RNG->Gen1() * Location::NLoc); while(used[i] !=0) { if(++i >= Location::NLoc) i = 0; if(i==j) return -1; } used[i]++; return i; } Organism* BiotaIterator::getNext() { Pix tmp=nextOne; if(tmp) { nextOne=here->biota.getNext(nextOne); return (*(Node*)tmp)(); } return (Organism*)0; } ostream& operator<<(ostream& os, Location& lr) { Pix ptr = lr.biota.getFirst(); os << "Location at: " << (Position&) lr << (EnVar&) lr; os << " population: " << lr.locationPop() << " Proteins: " << lr.proteins.length() << endl; os << "Biota: "; while(ptr) { os << lr.biota(ptr) << endl; ptr = lr.biota.getNext(ptr); } return os << (Material&) lr; } void ##### -> Location::printWorld(ostream& os) { for(int i=0; i void Location::updateEnv() { // Begin with the baseline value for each variable for(int i = 0; i< ENVSIZE; i++) { modified[i] = baseline[i]; } // Apply all modifiers in turn for(int i=0; i double Location::calculateModifier(int bioactIndex) { double A = bioact[bioactIndex].A, B = bioact[bioactIndex].B, M; // Initialize M depending on the agent specified. int agnt = bioact[bioactIndex].agent; if(agnt < NMat) { if(bioact[bioactIndex].halfLife) { Material degrade(Material_t(0)); degrade[agnt] = bioact[bioactIndex].halfLife * ((Material&)(*this))[agnt]; ((Material&)(*this))[agnt] -= degrade[agnt]; degrade.totalDecompose(); ((Material&)(*this)) += degrade; } M = double(((Material&)(*this))[agnt]); } else { // It would be nice to use a switch here, but the constant // NMat is defined at run time. if(agnt < NMat + ENVSIZE) M = double(modified[agnt]); else { // ad hoc stuff -- code each one as it comes up if(agnt == (NMat + ENVSIZE)) M = double(floaterPop()); else { cerr << "Unknown agent: " << agnt << " in calculateModifier" << endl; abort(); } } } // Calculate modifier according to the function specified switch(bioact[bioactIndex].function) { case POLY: return A * M; break; case LOG: return A * log(1 + B * M); break; case POW: return pow(A, M / B); break; case MODPOW: return pow(A, (int)M / (int)B); break; case INVPOW: return pow(A, B / M); break; default: cerr << "Location::updateEnv() unknown function: "; cerr << bioact[bioactIndex].function << " for entry " << bioactIndex << endl; abort(); break; } } Top 10 Lines: Line Count 353 400457 207 264387 405 71928 340 36963 380 35964 173 1001 250 999 331 999 218 998 200 252 Execution Summary: 150 Executable lines in this file 22 Lines executed 14.67 Percent of the file executed 813953 Total number of line executions 5426.35 Average executions per line *** File /home/dnikce/evolve/faster/random.C: #include "defs.h" #include #include #include #include #include "random.h" static char RCSID[] = "$Id: random.C,v 1.2 2000/07/03 18:35:04 jjb Exp $"; // With thanks to Klaus-Peter Zauner //-------------------%<------------------------%<------------------------- z1_Rnd* z1_Rnd::RNG = new z1_Rnd((long)-time((time_t*)0)); // The following function was implemented following // W.H. Press et al. "Numerical Recipes in C",2nd ed., 1992 // z1_Rnd::z1_Rnd( long s ){ seed = -20010; //originally was s dn ia = 16607; im = 2147483647; am = 1.0 / im; iq = 127773; ir = 2836; ntab = 32; ndiv = 1 + (im - 1) / ntab; eps = 1.2e-7; rnmax = 1.0 - eps; iy = 0L; iv = new long[ntab]; } ##### -> z1_Rnd::~z1_Rnd(){ delete iv; } 1301093 -> float z1_Rnd::Gen1(){ int j; long k; float temp; if( seed <= 0 || !iy ) { if( -(seed) < 1) seed = 1; else seed = -(seed); for( j = ntab + 7; j >= 0; j-- ){ k = (seed)/iq; seed = ia * (seed - k * iq) - ir * k; if( seed < 0 ) seed += im; if( j < ntab ) iv[j] = seed; } iy = iv[0]; } k = (seed) / iq; seed = ia * (seed - k * iq) - ir * k; if( seed < 0 ) seed += im; j = (int) (iy / ndiv); iy = iv[j]; iv[j] = seed; if( (temp = am * iy) > rnmax ) return( rnmax ); else return( temp ); } Top 10 Lines: Line Count 41 1301093 Execution Summary: 40 Executable lines in this file 2 Lines executed 5.00 Percent of the file executed 1301093 Total number of line executions 32527.33 Average executions per line *** File /home/dnikce/evolve/faster/organism.C: static char RCSID[] = "$Id: organism.C,v 1.68 2001/11/16 01:45:31 jjb Exp $"; //$Log: organism.C,v $ //Revision 1.68 2001/11/16 01:45:31 jjb //Added sinkP code to function switch and changed proDone to bottom. // //Revision 1.67 2001/11/14 16:55:59 jjb //Removed the changes added by rev. 1.65 // //Revision 1.66 2001/11/13 20:20:47 jjb //Added limit to amino acid imports so that it doesn't swamp out //other import channels. // //Revision 1.65 2001/11/13 12:20:50 jjb //Switched to fixed organism size. //1. Setup at l. 191 //2. Test at l. 341 //3. Test at l. 468 // //Revision 1.64 2001/11/13 11:18:18 jjb //Removed commented out code above import // //Revision 1.63 2001/11/12 16:20:43 jjb //modified calculateUptakeRates so that effect() is calculated from //cytoplasm calculations, not environmental ones. // //Revision 1.62 2001/11/12 10:33:53 jjb //changed += to *= @ l. 316 // //Revision 1.61 2001/11/12 08:55:55 jjb //Added assertion at l. 454 // //Revision 1.60 2001/11/11 02:37:36 jjb //Check for emax = 0 two places. // //Revision 1.59 2001/11/11 02:33:07 jjb //Roll back modifier changes // #include "organism.h" #include "random.h" #include "env.h" #include #include "defs.h" #include #include "protopeptide.h" #include //#define conc(A) ((double)A * ConcFactor) Organism* TargetOrganism = (Organism*) -1; extern int NoMutate; extern ReactionTable RTable; extern Date now; extern int ST; #define report(A, B) if(ST) \ cerr << A << " " << sn() << " in " << lindex << endl << \ Here.locationResourceSummary(B) << endl << \ Here.locationBiomassSummary(B) << endl ##### -> ostream& operator<<(ostream& os, Organism& orgref) { os << "Organism " << (Serial&)orgref << " at " << (Position&) orgref << " born " << (Date&)orgref << " lineage " << orgref.lineage << endl; os << "\tCytoplasmic materials: " << orgref.cytoplasm << endl; os << " lastDir: " << orgref.lastDir ; os << " \tmyChromosome " << orgref.myChromosome << endl; os << "aux " << orgref.aux << endl; os << "Aggregate efficiencies:" << endl; double efficiency[NFunction]; // Setup of efficiency[] for(int i=0; i< NFunction; i++) efficiency[i] = 0; Protein* pp; for(int i=0; infunction; j++) { float err = float(maxMismatch - pp->mismatch[j])/maxMismatch; efficiency[pp->function[j]] += (Function_t)(pp->quantity * err); } } for(int i=0; i Organism::Organism(Chromosome& cr, Material& mr, int x, int y, char l) : Position(x, y), lineage(l), // No parent to inherit cytoplasm from... cytoplasm (mr) { /* ** Initialize some things. */ myChromosome = new Chromosome(cr); efficiency = new double[NFunction]; uptakeRates = new double[NMat+1]; currentAminoAcid = myChromosome->nextGeneOffset(-1); logDone = 0; nextPeptide = 0; auxDone = 0; bottom = 0; auxMaterial = 0; proMaterial = 0; // Material pcost; np = myChromosome->numGenes(); protein = new Protein*[np]; for(int i=0; igene(i)->getProtein(); protein[i]->quantity = initialProteinQuantity; } aux = new Chromosome(*myChromosome, MutationRate); lastDir = east; calculateEfficiencies(); calculateUptakeRates(); } 434 -> Organism::~Organism(){ // Delete all of the dynamically allocated storage. // The method, die(), takes care of removing the // organism from its environment and moving its // material to its environment. // The default constructor does not create a chromosome, // aux chromosome or vector of protein pointers, so // their destructors must be conditional if(myChromosome) { delete myChromosome; } if(aux) { delete aux; } if(protein) delete[] protein; delete[] efficiency; delete[] uptakeRates; } void 434 -> Organism::die() { Location& here = Location::theWorld[this->index()]; // All of the material that is summed up as biomass() should // be moved to the environment. // biomass = cytoplasm // + chromosome // + aux chromosome (auxMaterial) // + unfinished proteins (proMaterial) // + proteins // Proteins are assumed to remain intact and so are handed to // Location:: addProtein() rather than being dumped as gross // material. // Include a death notice for the deceased Material_t totalProtein = 0; Protein* pp; for(int i=0; iquantity; } cerr << sn() << " age " << age() << " wt " << totalProtein; cerr << ". MPF = " << cytoplasm[MPF] << " and ATP = " << cytoplasm[ATP]; cerr << ". Auxlen = " << nextPeptide << " and next peptide is "; cerr << tolower((*(PeptideString*)aux)[nextPeptide]) << endl; cytoplasm += myChromosome; cytoplasm += auxMaterial; cytoplasm += proMaterial; assert(cytoplasm >= 0); here.exchangeMaterial(cytoplasm); here.addProtein(protein, np); here.removeBiota(this); delete(this); } void 362445 -> Organism::live() { int lindex = ((Position*)this)->index(); Location& Here = Location::theWorld[lindex]; int expressProgress; Material fragment; int remainingLength, cglength, cgstart; Position nextPos; int notDone; double energeticCost; Protein* currentProtein; int expressMem; // Weed out obviously dead organisms: // Without any proteins, uptake of anything but elementals is // impossible, photosynthesis is impossible, and gene expression // is impossible. Material_t totalProtein = 0; Protein* pp; for(int i=0; iquantity; } if(totalProtein == 0) { die(); return; } // Here is a good place to add some sort of somatic limitation // // calculateEfficiencies() was already run in calculateUptake // Every organism is able to take up elemental material via passive // diffusion. It is an equilibrium reaction. Material share; int proteinShare = Here.getShare(share, uptakeRates); Material eshare(Material_t(0)); //effective share Material tempMaterial(cytoplasm); int integerRate; double remainder, tmp; double fwd, rev, rate; enum Direction moveDir; int d; double rollMag = -0.0, motileMag = 0.0; int reaction; int moveNow, tmpPtr; int operand; Peptide aa; // do import // the base rate for transfer of elements is reversible // but the import due to material-specific ports is not // reversible. // First calculate the rate of transfer based on concentration difference // across the cell wall = tmpMat but not to exceed share. // Rate is positive _into_ the cell for(int i=0; i= 0); for(int i=0; i= 0); if(efficiency[i]){ operand = Protopeptide::getOperand(i); switch (Protopeptide::getType(i)) { case SINK_P: rate = efficiency[i]; if(rate == 0.0) continue; else { rate *= Protopeptide::effect(i, Here, cytoplasm); if(rate > 0) bottom = (char)1; } break; case ENZYME_P: targetReaction = RTable[operand]; assert(cytoplasm >= 0); rate = efficiency[i]; // effectiveness of enzyme configuration if(rate == 0) continue; rate *= Protopeptide::effect(i, Here, cytoplasm); // rate, env factors targetReaction.react(rate, cytoplasm); assert(cytoplasm >= 0); break; case SECRETE_P: // or EXPORT // Rate is the fraction of total substance that will be exported. // Basic rate is protein effect, modified by environmental factors // The value of rate must never exceed 1.0. eshare = 0; rate = Protopeptide::effect(i, Here, cytoplasm) * efficiency[i]; rate = min(rate, 1.0); if(operand == -1) { for(int ai=NElem; ai<(NAmino+NElem); ai++) eshare[ai] = cytoplasm[ai]; } else eshare[operand] = cytoplasm[operand]; eshare *= rate; // If exportEnergy isn't 0, there will be an energetic cost // for every molecule exported. Can export only as much as // there is energy to export. if(exportEnergy != 0) { emax = 0.0; for(int ei=0; ei= 0); break; case UPTAKE_P: // or IMPORT // Imports are calculated in a similar fashion, except that the // import rate is the quantity that can be imported, rather than // a fraction of it. eshare = 0; rate = Protopeptide::effect(i, Here, cytoplasm)* efficiency[i]; // It is important to apportion uptake fairly because the all-amino-acids // operand is a total rate of 20K and can swamp out everything else. if(operand == -1) { // import all amino acids for(int j=NElem; j= 0); break; case ROLL_P: double electors, party; electors = efficiency[i]; party = (Protopeptide::effect(i, Here, cytoplasm) > 0.5)? 1: -1; rollMag += electors * party; break; case MOTILE_P: motileMag += Protopeptide::effect(i, Here, cytoplasm)* efficiency[i]; break; case PROTEASE_P: rate = Protopeptide::effect(i, Here, cytoplasm) * efficiency[i]; integerRate = (int)stoch(rate); assert(proteinShare >= 0); integerRate = min(integerRate, proteinShare); while(integerRate) { Protein* importProtein = Here.takeProtein(integerRate); if(importProtein) { integerRate -= (int)importProtein->quantity; Material aminos = Material(*importProtein) * importProtein->quantity; cytoplasm += aminos; delete importProtein; } else // getting here means there's no available protein break; } break; case MALE_P: rate = Protopeptide::effect(i, Here, share)* efficiency[i]; if(RANDOM < rate) { } break; case REPLICATE_P: // Reproduction section. If the new chromosome has been // completed, mitosis is the next step, provided there is sufficient // capital. rate = Protopeptide::effect(i, Here, cytoplasm)* efficiency[i]; auxDone = 0; tmpPtr = nextPeptide; rate = min(rate, floor(double(cytoplasm[ATP])/ReplicationEnergy)); // rate is limit, either from time or energy for(int j=0; j= 1) { cytoplasm[aa]--; auxMaterial[aa]++; nextPeptide++; } else { // replication is stalled here break; } } } // end for-loop energeticCost = (nextPeptide - tmpPtr) * ReplicationEnergy; energy(Material_t(energeticCost)); if(auxDone) { int ng = aux->numGenes(); int inheritIndex; Protein* inherit[np]; Protein* temp[np+ng]; nextPeptide = 0; int nextAA = 0; int orphan = 0; int novo = 0; for(int i=0; igene(i)->getProtein(); // for each protein in inherit for(inheritIndex=0; inheritIndexgene(i)->updateProtein(offspringProt); // receive inherited qty offspringProt->quantity = int(cur->quantity * mitosisRatio); // decrement parent accordingly cur->quantity -= offspringProt->quantity; } else { // assert(++novo < 10); // this protein corresponds to a mutated gene // it is a new one, so just add it to temp // it should have a quantity of 0 temp[nextAA++] = cur; aux->gene(i)->express(); //mark it as expressed } } // end of i-loop // Temp now contains a list of all proteins for which the offspring has a // gene, and those proteins have appropriate quantitites. // Inherit may still contain proteins for which the new organism // does not have a gene. Move a portion of // those to temp, but do not update the (non-existent) gene. for(int i=0; iquantity * mitosisRatio) >= 1) { // assert(++orphan < 10); Protein* offspringProt = new Protein(*(inherit[i])); Protein* cur = inherit[i]; inherit[i] = (Protein*)1; offspringProt->quantity = int(cur->quantity * mitosisRatio); cur->quantity -= offspringProt->quantity; temp[nextAA++] = offspringProt; } } } Organism* offspring = new Organism(*this, aux); // Reset MPF eshare = 0; eshare[MPF] = cytoplasm[MPF]; cytoplasm[MPF] = 0; eshare.totalDecompose(); assert(eshare >= 0); cytoplasm += eshare; offspring->cytoplasm = cytoplasm * mitosisRatio; cytoplasm -= offspring->cytoplasm; offspring->np = nextAA; offspring->protein = new Protein*[nextAA]; for(int i=0; iprotein[i] = temp[i]; refresh(); // reset parent age to 0, so two offspring. Here.insertBiota(offspring); offspring->myChromosome->datalogGenes(); // Clean up parent auxMaterial = 0; auxDone = 0; bottom = 0; nextPeptide = 0; aux = new Chromosome(*myChromosome, MutationRate); } // end of if(auxDone) assert(cytoplasm >= 0); break; // End of replication finish case EXPRESS_P: // The rate for this function is the number of amino acids added // per time-step. // This routine always starts with currentAminoAcid // pointing to a codon that is within a valid gene. // Initially, it is set by the contructor calling // nextGeneOffset(-1). After, it is set in this routine // either as an increment or a call to nextGeneOffset. // From that value, we can set the other variables needed: // cgstart, currentProtein, cglength, and remainingLength // Material bookkeeping requires that we update energeticCost, // cytoplasm, and proMaterial whenever an amino acid is added to the // protein. When the protein is completed, increment // protein quantity by 1 and reset proMaterial back to 0. rate = floor(Protopeptide::effect(i, Here, cytoplasm) * efficiency[i]); rate = min(rate, floor(double(cytoplasm[ATP])/ExpressionEnergy)); expressProgress = 0; // get offset of current gene cgstart = myChromosome->findOffset(currentAminoAcid); // get pointer to corresponding protein currentProtein = myChromosome->proteinPointer(currentAminoAcid); // get length of current gene cglength = myChromosome->findLength(currentAminoAcid); // how much of current gene remains to be constructed? remainingLength = cglength - (currentAminoAcid - cgstart); notDone = 1; // First assemble proteins or chunks of proteins while(notDone) { // how much of current gene remains? fragment = (Material)(*currentProtein) - proMaterial; if((rate >= fragment.alength()) && (cytoplasm >= fragment)) { //construct the fragment assert(fragment <= cytoplasm); // update bookkeeping cytoplasm -= fragment; // already have deducted proMaterial proMaterial = 0; currentProtein->incQty(1); expressProgress += fragment.alength(); rate -= fragment.alength(); assert(cytoplasm >= 0); // move to next gene/protein currentAminoAcid = myChromosome->nextGeneOffset(currentAminoAcid); cgstart = currentAminoAcid; cglength = myChromosome->findLength(currentAminoAcid); currentProtein = myChromosome->proteinPointer(currentAminoAcid); } // built a fragment -- or a protein else notDone = 0; } assert(cytoplasm >= 0); // add one amino acid at a time -- either rate or material // will run out while(rate > 0) { aa = (*(PeptideString*)myChromosome)[currentAminoAcid]; int naa = tolower(aa) - 'a' + NElem; if(cytoplasm[naa] >= Material_t(1)) { currentAminoAcid++; cytoplasm[naa]--; proMaterial[naa]++; expressProgress++; rate--; } else rate = 0.0; // force an exit } energeticCost = expressProgress * ExpressionEnergy; energy(Material_t(energeticCost)); assert(cytoplasm >= 0); break; default: break; } // end of switch } // if(efficiency[i]) } // for(int i=0; i 0) moveDir = lastDir; else { // tumble switch(int(ceil(RANDOM*4))) { case 1: moveDir = east; break; case 2: moveDir = south; break; case 3: moveDir = west; break; case 4: moveDir = north; break; default: cerr << "Enumerated direction of range" << endl; moveDir = east; break; } // end switch } // end tumble // remember starting position lindex = ((Position*)this)->index(); switch(moveDir) { case east: nextPos = moveE(); break; case south: nextPos = moveS(); break; case west: nextPos = moveW(); break; case north: nextPos = moveN(); break; } int toIndex = nextPos.index(); Location::theWorld[lindex].removeBiota(this); Location::theWorld[toIndex].insertBiota(this); } break; // End of motion finish default: break; } //end of switch } //if efficiency } // for(int i=0; i chaos(Lifetime, 40)) { die(); return; } } void ##### -> Organism::efficiencies(ostream& os) { double efficiency[NFunction]; for(int i=0; i< NFunction; i++) efficiency[i] = 0; for(int i=0; i< NFunction; i++) efficiency[i] = 0; Protein* pp; for(int i=0; infunction; j++) { double err = double(maxMismatch - pp->mismatch[j])/maxMismatch; efficiency[pp->function[j]] += (pp->quantity * err); } } for(int i=0; i< NFunction; i++) os << efficiency[i] << " "; return; } // for CSV records // record total genetic trait values // independent of environmental factors // and protein quantities void 1796 -> Organism::dltraits(ostream& os) { double trait[NFunction], err; for(int i=0; i< NFunction; i++) trait[i] = 0; Protein* pp; for(int i=0; infunction; j++) { err = double(maxMismatch - pp->mismatch[j])/maxMismatch; trait[pp->function[j]] += err; } } for(int i=0; i< NFunction-1; i++) os << trait[i] << FS; os << trait[NFunction-1]; return; } void ##### -> Organism::netEfficiencies(ostream& os) { int lindex = ((Position*)this)->index(); Location& Here = Location::theWorld[lindex]; double efficiency[NFunction]; for(int i=0; i< NFunction; i++) efficiency[i] = 0; Protein* pp; for(int i=0; infunction; j++) { double err = double(maxMismatch - pp->mismatch[j])/maxMismatch; efficiency[pp->function[j]] += (pp->quantity * err) * Protopeptide::effect( pp->function[j], Here, cytoplasm); } } for(int i=0; i< NFunction; i++) os << efficiency[i] << " "; return; } void ##### -> Organism::proteinqty(ostream& os) { Protein* pp; for(int i=0; iquantity << " "; } return; } void ##### -> Organism::myEnv(ostream& os) { int lindex = ((Position*)this)->index(); Location& Here = Location::theWorld[lindex]; for(int i=0; i Organism::whichProtein(int aa) { Protein* pp = myChromosome->proteinPointer(aa); for(int i=0; i Organism::datalog(ostream& os) { // Record Lineage, Chromosome_Length, Traits, // Cytoplasm, Total_Protein, NProtein, AuxLen and nGene os << (int)lineage << FS << myChromosome->plen(); os << FS; dltraits(os); os << FS; cytoplasm.datalog(os); Material_t totalProtein = 0; for(int i=0; iquantity; } os << FS << totalProtein << FS << np << FS << nextPeptide << FS; os << myChromosome->numGenes(); } void 277573 -> Organism::calculateUptakeRates() { int lindex = ((Position*)this)->index(); Location& Here = Location::theWorld[lindex]; calculateEfficiencies(); for(int i=0; i<=NMat; i++) uptakeRates[i] = 0.0; // calculate uptake rate for Material[i] for(int i=0; i= 0) { uptakeRates[operand] += efficiency[i] * Protopeptide::effect(i, Here, cytoplasm); } if(operand == -1) {// all amino acids for(int j=NElem; j Organism::calculateEfficiencies() { // Setup of efficiency[] for(int i=0; i< NFunction; i++) efficiency[i] = 0; Protein* pp; for(int i=0; idegrade(proteinDecayRate); for(int j=0; jnfunction; j++) { // double effect = double(maxMismatch - pp->mismatch[j])/maxMismatch; double effect = sqrt(double(maxMismatch - pp->mismatch[j])/maxMismatch); efficiency[pp->function[j]] += (pp->quantity * effect); } } } Top 10 Lines: Line Count 181 362445 796 278418 763 277573 677 1796 747 1796 124 434 145 434 93 108 Execution Summary: 285 Executable lines in this file 14 Lines executed 4.91 Percent of the file executed 923004 Total number of line executions 3238.61 Average executions per line *** File /usr/include/g++-v31/streambuf: // Stream buffer classes -*- C++ -*- // Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002 // Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 2, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // the GNU General Public License. This exception does not however // invalidate any other reasons why the executable file might be covered by // the GNU General Public License. // // ISO C++ 14882: 27.5 Stream buffers // /** @file streambuf * This is a Standard C++ Library header. You should @c #include this header * in your programs, rather than any of the "st[dl]_*.h" implementation files. */ #ifndef _CPP_STREAMBUF #define _CPP_STREAMBUF 1 #pragma GCC system_header #include #include #include // For SEEK_SET, SEEK_CUR, SEEK_END #include #include namespace std { template streamsize __copy_streambufs(basic_ios<_CharT, _Traits>& _ios, basic_streambuf<_CharT, _Traits>* __sbin, basic_streambuf<_CharT, _Traits>* __sbout); // 27.5.2 Template class basic_streambuf<_CharT, _Traits> template class basic_streambuf { public: // Types: typedef _CharT char_type; typedef _Traits traits_type; typedef typename traits_type::int_type int_type; typedef typename traits_type::pos_type pos_type; typedef typename traits_type::off_type off_type; // Non-standard Types: typedef ctype __ctype_type; typedef basic_streambuf __streambuf_type; friend class basic_ios; friend class basic_istream; friend class basic_ostream; friend class istreambuf_iterator; friend class ostreambuf_iterator; friend streamsize __copy_streambufs<>(basic_ios& __ios, __streambuf_type* __sbin,__streambuf_type* __sbout); protected: // Pointer to the beginning of internally-allocated // space. Filebuf manually allocates/deallocates this, whereas // stringstreams attempt to use the built-in intelligence of the // string class. If you are managing memory, set this. If not, // leave it NULL. char_type* _M_buf; // Actual size of allocated internal buffer, in bytes. int_type _M_buf_size; // Optimal or preferred size of internal buffer, in bytes. int_type _M_buf_size_opt; // True iff _M_in_* and _M_out_* buffers should always point to // the same place. True for fstreams, false for sstreams. bool _M_buf_unified; // This is based on _IO_FILE, just reordered to be more // consistent, and is intended to be the most minimal abstraction // for an internal buffer. // get == input == read // put == output == write char_type* _M_in_beg; // Start of get area. char_type* _M_in_cur; // Current read area. char_type* _M_in_end; // End of get area. char_type* _M_out_beg; // Start of put area. char_type* _M_out_cur; // Current put area. char_type* _M_out_end; // End of put area. // Place to stash in || out || in | out settings for current streambuf. ios_base::openmode _M_mode; // Current locale setting. locale _M_buf_locale; // True iff locale is initialized. bool _M_buf_locale_init; // Necessary bits for putback buffer management. Only used in // the basic_filebuf class, as necessary for the standard // requirements. The only basic_streambuf member function that // needs access to these data members is in_avail... // NB: pbacks of over one character are not currently supported. static const int_type _S_pback_size = 1; 4 -> char_type _M_pback[_S_pback_size]; char_type* _M_pback_cur_save; char_type* _M_pback_end_save; bool _M_pback_init; // Initializes pback buffers, and moves normal buffers to safety. // Assumptions: // _M_in_cur has already been moved back void _M_pback_create() { if (!_M_pback_init) { int_type __dist = _M_in_end - _M_in_cur; int_type __len = min(_S_pback_size, __dist); traits_type::copy(_M_pback, _M_in_cur, __len); _M_pback_cur_save = _M_in_cur; _M_pback_end_save = _M_in_end; this->setg(_M_pback, _M_pback, _M_pback + __len); _M_pback_init = true; } } // Deactivates pback buffer contents, and restores normal buffer. // Assumptions: // The pback buffer has only moved forward. void _M_pback_destroy() { if (_M_pback_init) { // Length _M_in_cur moved in the pback buffer. int_type __off_cur = _M_in_cur - _M_pback; // For in | out buffers, the end can be pushed back... int_type __off_end = 0; int_type __pback_len = _M_in_end - _M_pback; int_type __save_len = _M_pback_end_save - _M_buf; if (__pback_len > __save_len) __off_end = __pback_len - __save_len; this->setg(_M_buf, _M_pback_cur_save + __off_cur, _M_pback_end_save + __off_end); _M_pback_cur_save = NULL; _M_pback_end_save = NULL; _M_pback_init = false; } } // Correctly sets the _M_in_cur pointer, and bumps the // _M_out_cur pointer as well if necessary. void _M_in_cur_move(off_type __n) // argument needs to be +- { bool __testout = _M_out_cur; _M_in_cur += __n; if (__testout && _M_buf_unified) _M_out_cur += __n; } // Correctly sets the _M_out_cur pointer, and bumps the // appropriate _M_*_end pointers as well. Necessary for the // un-tied stringbufs, in in|out mode. // Invariant: // __n + _M_out_[cur, end] <= _M_buf + _M_buf_size // Assuming all _M_*_[beg, cur, end] pointers are operating on // the same range: // _M_buf <= _M_*_ <= _M_buf + _M_buf_size void _M_out_cur_move(off_type __n) // argument needs to be +- { bool __testin = _M_in_cur; _M_out_cur += __n; if (__testin && _M_buf_unified) _M_in_cur += __n; if (_M_out_cur > _M_out_end) { _M_out_end = _M_out_cur; // NB: in | out buffers drag the _M_in_end pointer along... if (__testin) _M_in_end += __n; } } // Return the size of the output buffer. This depends on the // buffer in use: allocated buffers have a stored size in // _M_buf_size and setbuf() buffers don't. off_type _M_out_buf_size() { off_type __ret = 0; if (_M_out_cur) { // Using allocated buffer. if (_M_out_beg == _M_buf) __ret = _M_out_beg + _M_buf_size - _M_out_cur; // Using non-allocated buffer. else __ret = _M_out_end - _M_out_cur; } return __ret; } public: virtual ~basic_streambuf() { _M_buf_unified = false; _M_buf_size = 0; _M_buf_size_opt = 0; _M_mode = ios_base::openmode(0); _M_buf_locale_init = false; } // Locales: locale pubimbue(const locale &__loc) { locale __tmp(this->getloc()); this->imbue(__loc); return __tmp; } locale getloc() const { if (_M_buf_locale_init) return _M_buf_locale; else return locale(); } // Buffer and positioning: __streambuf_type* pubsetbuf(char_type* __s, streamsize __n) { return this->setbuf(__s, __n); } pos_type pubseekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode __mode = ios_base::in | ios_base::out) { return this->seekoff(__off, __way, __mode); } pos_type pubseekpos(pos_type __sp, ios_base::openmode __mode = ios_base::in | ios_base::out) { return this->seekpos(__sp, __mode); } int pubsync() { return this->sync(); } // Get and put areas: // Get area: streamsize in_avail() { streamsize __ret; if (_M_in_cur && _M_in_cur < _M_in_end) { if (_M_pback_init) { int_type __save_len = _M_pback_end_save - _M_pback_cur_save; int_type __pback_len = _M_in_cur - _M_pback; __ret = __save_len - __pback_len; } else __ret = this->egptr() - this->gptr(); } else __ret = this->showmanyc(); return __ret; } int_type snextc() { int_type __eof = traits_type::eof(); return (this->sbumpc() == __eof ? __eof : this->sgetc()); } int_type sbumpc(); int_type sgetc() { int_type __ret; if (_M_in_cur && _M_in_cur < _M_in_end) __ret = traits_type::to_int_type(*(this->gptr())); else __ret = this->underflow(); return __ret; } streamsize sgetn(char_type* __s, streamsize __n) { return this->xsgetn(__s, __n); } // Putback: int_type sputbackc(char_type __c); int_type sungetc(); // Put area: int_type sputc(char_type __c); streamsize sputn(const char_type* __s, streamsize __n) { return this->xsputn(__s, __n); } protected: basic_streambuf() : _M_buf(NULL), _M_buf_size(0), _M_buf_size_opt(static_cast(BUFSIZ)), _M_buf_unified(false), _M_in_beg(0), _M_in_cur(0), _M_in_end(0), _M_out_beg(0), _M_out_cur(0), _M_out_end(0), _M_mode(ios_base::openmode(0)), _M_buf_locale(locale()), _M_buf_locale_init(false), _M_pback_cur_save(0), _M_pback_end_save(0), _M_pback_init(false) { } // Get area: char_type* eback() const { return _M_in_beg; } char_type* gptr() const { return _M_in_cur; } char_type* egptr() const { return _M_in_end; } void gbump(int __n) { _M_in_cur += __n; } void setg(char_type* __gbeg, char_type* __gnext, char_type* __gend) { _M_in_beg = __gbeg; _M_in_cur = __gnext; _M_in_end = __gend; if (!(_M_mode & ios_base::in) && __gbeg && __gnext && __gend) _M_mode = _M_mode | ios_base::in; } // Put area: char_type* pbase() const { return _M_out_beg; } char_type* pptr() const { return _M_out_cur; } char_type* epptr() const { return _M_out_end; } void pbump(int __n) { _M_out_cur += __n; } void setp(char_type* __pbeg, char_type* __pend) { _M_out_beg = _M_out_cur = __pbeg; _M_out_end = __pend; if (!(_M_mode & ios_base::out) && __pbeg && __pend) _M_mode = _M_mode | ios_base::out; } // Virtual functions: // Locales: virtual void imbue(const locale& __loc) { _M_buf_locale_init = true; if (_M_buf_locale != __loc) _M_buf_locale = __loc; } // Buffer management and positioning: virtual basic_streambuf* setbuf(char_type*, streamsize) { return this; } virtual pos_type seekoff(off_type, ios_base::seekdir, ios_base::openmode /*__mode*/ = ios_base::in | ios_base::out) { return pos_type(off_type(-1)); } virtual pos_type seekpos(pos_type, ios_base::openmode /*__mode*/ = ios_base::in | ios_base::out) { return pos_type(off_type(-1)); } virtual int sync() { return 0; } // Get area: virtual streamsize showmanyc() { return 0; } virtual streamsize xsgetn(char_type* __s, streamsize __n); virtual int_type underflow() { return traits_type::eof(); } virtual int_type uflow() { int_type __ret = traits_type::eof(); bool __testeof = this->underflow() == __ret; bool __testpending = _M_in_cur && _M_in_cur < _M_in_end; if (!__testeof && __testpending) { __ret = traits_type::to_int_type(*_M_in_cur); ++_M_in_cur; if (_M_buf_unified && _M_mode & ios_base::out) ++_M_out_cur; } return __ret; } // Putback: virtual int_type pbackfail(int_type /* __c */ = traits_type::eof()) { return traits_type::eof(); } // Put area: virtual streamsize xsputn(const char_type* __s, streamsize __n); virtual int_type overflow(int_type /* __c */ = traits_type::eof()) { return traits_type::eof(); } #ifdef _GLIBCPP_DEPRECATED public: void stossc() { if (_M_in_cur < _M_in_end) ++_M_in_cur; else this->uflow(); } #endif #ifdef _GLIBCPP_RESOLVE_LIB_DEFECTS // Side effect of DR 50. private: basic_streambuf(const __streambuf_type&) { }; __streambuf_type& operator=(const __streambuf_type&) { return *this; }; #endif }; } // namespace std #ifdef _GLIBCPP_NO_TEMPLATE_EXPORT # define export #endif #ifdef _GLIBCPP_FULLY_COMPLIANT_HEADERS #include #endif #endif Top 10 Lines: Line Count 130 4 Execution Summary: 1 Executable lines in this file 1 Lines executed 100.00 Percent of the file executed 4 Total number of line executions 4.00 Average executions per line *** File /usr/include/g++-v31/bits/codecvt.h: // Locale support (codecvt) -*- C++ -*- // Copyright (C) 2000, 2001 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 2, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // the GNU General Public License. This exception does not however // invalidate any other reasons why the executable file might be covered by // the GNU General Public License. // // ISO C++ 14882: 22.2.1.5 Template class codecvt // // Written by Benjamin Kosnik /** @file codecvt.h * This is an internal header file, included by other library headers. * You should not attempt to use it directly. */ #ifndef _CPP_BITS_CODECVT_H #define _CPP_BITS_CODECVT_H 1 #pragma GCC system_header // 22.2.1.5 Template class codecvt class codecvt_base { public: enum result { ok, partial, error, noconv }; }; // Template class __codecvt_abstract_base // NB: An abstract base class that fills in the public inlines, so // that the specializations don't have to re-copy the public // interface. template class __codecvt_abstract_base : public locale::facet, public codecvt_base { public: // Types: typedef codecvt_base::result result; typedef _InternT intern_type; typedef _ExternT extern_type; typedef _StateT state_type; // 22.2.1.5.1 codecvt members result out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { 4 -> return this->do_out(__state, __from, __from_end, __from_next, __to, __to_end, __to_next); } result unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { return this->do_unshift(__state, __to,__to_end,__to_next); } result in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { return this->do_in(__state, __from, __from_end, __from_next, __to, __to_end, __to_next); } int encoding() const throw() { return this->do_encoding(); } bool always_noconv() const throw() { return this->do_always_noconv(); } int length(const state_type& __state, const extern_type* __from, const extern_type* __end, size_t __max) const { return this->do_length(__state, __from, __end, __max); } int max_length() const throw() { return this->do_max_length(); } protected: explicit __codecvt_abstract_base(size_t __refs = 0) : locale::facet(__refs) { } virtual ~__codecvt_abstract_base() { } virtual result do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const = 0; virtual result do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const = 0; virtual result do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const = 0; virtual int do_encoding() const throw() = 0; virtual bool do_always_noconv() const throw() = 0; virtual int do_length(const state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const = 0; virtual int do_max_length() const throw() = 0; }; // 22.2.1.5 Template class codecvt // NB: Generic, mostly useless implementation. template class codecvt : public __codecvt_abstract_base<_InternT, _ExternT, _StateT> { public: // Types: typedef codecvt_base::result result; typedef _InternT intern_type; typedef _ExternT extern_type; typedef _StateT state_type; // Data Members: static locale::id id; explicit codecvt(size_t __refs = 0) : __codecvt_abstract_base<_InternT,_ExternT,_StateT> (__refs) { } protected: virtual ~codecvt() { } virtual result do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const; virtual int do_encoding() const throw(); virtual bool do_always_noconv() const throw(); virtual int do_length(const state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const; virtual int do_max_length() const throw(); }; template locale::id codecvt<_InternT, _ExternT, _StateT>::id; // codecvt required specialization template<> class codecvt : public __codecvt_abstract_base { public: // Types: typedef char intern_type; typedef char extern_type; typedef mbstate_t state_type; // Data Members: static locale::id id; explicit codecvt(size_t __refs = 0); protected: virtual ~codecvt(); virtual result do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const; virtual int do_encoding() const throw(); virtual bool do_always_noconv() const throw(); virtual int do_length(const state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const; virtual int do_max_length() const throw(); }; #ifdef _GLIBCPP_USE_WCHAR_T // codecvt required specialization template<> class codecvt : public __codecvt_abstract_base { public: // Types: typedef wchar_t intern_type; typedef char extern_type; typedef mbstate_t state_type; // Data Members: static locale::id id; explicit codecvt(size_t __refs = 0); protected: virtual ~codecvt(); virtual result do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const; virtual int do_encoding() const throw(); virtual bool do_always_noconv() const throw(); virtual int do_length(const state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const; virtual int do_max_length() const throw(); }; #endif //_GLIBCPP_USE_WCHAR_T // 22.2.1.6 Template class codecvt_byname template class codecvt_byname : public codecvt<_InternT, _ExternT, _StateT> { public: explicit codecvt_byname(const char*, size_t __refs = 0) : codecvt<_InternT, _ExternT, _StateT>(__refs) { } protected: virtual ~codecvt_byname() { } }; // Include host and configuration specific partial specializations // with additional functionality, if possible. #ifdef _GLIBCPP_USE_WCHAR_T #include #endif #endif // _CPP_BITS_CODECVT_H Top 10 Lines: Line Count 81 4 Execution Summary: 1 Executable lines in this file 1 Lines executed 100.00 Percent of the file executed 4 Total number of line executions 4.00 Average executions per line *** File /usr/include/g++-v31/bits/locale_facets.h: // Locale support -*- C++ -*- // Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002 // Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 2, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, // USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // the GNU General Public License. This exception does not however // invalidate any other reasons why the executable file might be covered by // the GNU General Public License. // // ISO C++ 14882: 22.1 Locales // /** @file locale_facets.h * This is an internal header file, included by other library headers. * You should not attempt to use it directly. */ #ifndef _CPP_BITS_LOCFACETS_H #define _CPP_BITS_LOCFACETS_H 1 #pragma GCC system_header #include // For struct tm #include // For wctype_t #include // For ios_base namespace std { // NB: Don't instantiate required wchar_t facets if no wchar_t support. #ifdef _GLIBCPP_USE_WCHAR_T # define _GLIBCPP_NUM_FACETS 28 #else # define _GLIBCPP_NUM_FACETS 14 #endif // 22.2.1.1 Template class ctype // Include host and configuration specific ctype enums for ctype_base. #include // Common base for ctype<_CharT>. template class __ctype_abstract_base : public locale::facet, public ctype_base { public: // Types: typedef _CharT char_type; bool is(mask __m, char_type __c) const { return this->do_is(__m, __c); } const char_type* is(const char_type *__lo, const char_type *__hi, mask *__vec) const { return this->do_is(__lo, __hi, __vec); } const char_type* scan_is(mask __m, const char_type* __lo, const char_type* __hi) const { return this->do_scan_is(__m, __lo, __hi); } const char_type* scan_not(mask __m, const char_type* __lo, const char_type* __hi) const { return this->do_scan_not(__m, __lo, __hi); } char_type toupper(char_type __c) const { return this->do_toupper(__c); } const char_type* toupper(char_type *__lo, const char_type* __hi) const { return this->do_toupper(__lo, __hi); } char_type tolower(char_type __c) const { return this->do_tolower(__c); } const char_type* tolower(char_type* __lo, const char_type* __hi) const { return this->do_tolower(__lo, __hi); } char_type widen(char __c) const 4 -> { return this->do_widen(__c); } const char* widen(const char* __lo, const char* __hi, char_type* __to) const 44 -> { return this->do_widen(__lo, __hi, __to); } char narrow(char_type __c, char __dfault) const { return this->do_narrow(__c, __dfault); } const char_type* narrow(const char_type* __lo, const char_type* __hi, char __dfault, char *__to) const { return this->do_narrow(__lo, __hi, __dfault, __to); } protected: explicit __ctype_abstract_base(size_t __refs = 0): locale::facet(__refs) { } virtual ~__ctype_abstract_base() { } virtual bool do_is(mask __m, char_type __c) const = 0; virtual const char_type* do_is(const char_type* __lo, const char_type* __hi, mask* __vec) const = 0; virtual const char_type* do_scan_is(mask __m, const char_type* __lo, const char_type* __hi) const = 0; virtual const char_type* do_scan_not(mask __m, const char_type* __lo, const char_type* __hi) const = 0; virtual char_type do_toupper(char_type) const = 0; virtual const char_type* do_toupper(char_type* __lo, const char_type* __hi) const = 0; virtual char_type do_tolower(char_type) const = 0; virtual const char_type* do_tolower(char_type* __lo, const char_type* __hi) const = 0; virtual char_type do_widen(char) const = 0; virtual const char* do_widen(const char* __lo, const char* __hi, char_type* __dest) const = 0; virtual char do_narrow(char_type, char __dfault) const = 0; virtual const char_type* do_narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __dest) const = 0; }; // NB: Generic, mostly useless implementation. template class ctype : public __ctype_abstract_base<_CharT> { public: // Types: typedef _CharT char_type; typedef typename ctype::mask mask; static locale::id id; explicit ctype(size_t __refs = 0) : __ctype_abstract_base<_CharT>(__refs) { } protected: virtual ~ctype(); virtual bool do_is(mask __m, char_type __c) const; virtual const char_type* do_is(const char_type* __lo, const char_type* __hi, mask* __vec) const; virtual const char_type* do_scan_is(mask __m, const char_type* __lo, const char_type* __hi) const; virtual const char_type* do_scan_not(mask __m, const char_type* __lo, const char_type* __hi) const; virtual char_type do_toupper(char_type __c) const; virtual const char_type* do_toupper(char_type* __lo, const char_type* __hi) const; virtual char_type do_tolower(char_type __c) const; virtual const char_type* do_tolower(char_type* __lo, const char_type* __hi) const; virtual char_type do_widen(char __c) const; virtual const char* do_widen(const char* __lo, const char* __hi, char_type* __dest) const; virtual char do_narrow(char_type, char __dfault) const; virtual const char_type* do_narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __dest) const; }; template locale::id ctype<_CharT>::id; // 22.2.1.3 ctype specialization. template<> class ctype : public __ctype_abstract_base { public: // Types: typedef char char_type; protected: // Data Members: __c_locale _M_c_locale_ctype; bool _M_del; __to_type _M_toupper; __to_type _M_tolower; const mask* _M_table; public: static locale::id id; static const size_t table_size = 1 + static_cast(-1); explicit ctype(const mask* __table = 0, bool __del = false, size_t __refs = 0); explicit ctype(__c_locale __cloc, const mask* __table = 0, bool __del = false, size_t __refs = 0); inline bool is(mask __m, char __c) const; inline const char* is(const char* __lo, const char* __hi, mask* __vec) const; inline const char* scan_is(mask __m, const char* __lo, const char* __hi) const; inline const char* scan_not(mask __m, const char* __lo, const char* __hi) const; protected: const mask* table() const throw() { return _M_table; } static const mask* classic_table() throw(); virtual ~ctype(); virtual bool do_is(mask __m, char_type __c) const; virtual const char_type* do_is(const char_type* __lo, const char_type* __hi, mask* __vec) const; virtual const char_type* do_scan_is(mask __m, const char_type* __lo, const char_type* __hi) const; virtual const char_type* do_scan_not(mask __m, const char_type* __lo, const char_type* __hi) const; virtual char_type do_toupper(char_type) const; virtual const char_type* do_toupper(char_type* __lo, const char_type* __hi) const; virtual char_type do_tolower(char_type) const; virtual const char_type* do_tolower(char_type* __lo, const char_type* __hi) const; virtual char_type do_widen(char) const; virtual const char* do_widen(const char* __lo, const char* __hi, char_type* __dest) const; virtual char do_narrow(char_type, char __dfault) const; virtual const char_type* do_narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __dest) const; }; template<> const ctype& use_facet >(const locale& __loc); #ifdef _GLIBCPP_USE_WCHAR_T // 22.2.1.3 ctype specialization template<> class ctype : public __ctype_abstract_base { public: // Types: typedef wchar_t char_type; typedef wctype_t __wmask_type; protected: __c_locale _M_c_locale_ctype; public: // Data Members: static locale::id id; explicit ctype(size_t __refs = 0); explicit ctype(__c_locale __cloc, size_t __refs = 0); protected: __wmask_type _M_convert_to_wmask(const mask __m) const; virtual ~ctype(); virtual bool do_is(mask __m, char_type __c) const; virtual const char_type* do_is(const char_type* __lo, const char_type* __hi, mask* __vec) const; virtual const char_type* do_scan_is(mask __m, const char_type* __lo, const char_type* __hi) const; virtual const char_type* do_scan_not(mask __m, const char_type* __lo, const char_type* __hi) const; virtual char_type do_toupper(char_type) const; virtual const char_type* do_toupper(char_type* __lo, const char_type* __hi) const; virtual char_type do_tolower(char_type) const; virtual const char_type* do_tolower(char_type* __lo, const char_type* __hi) const; virtual char_type do_widen(char) const; virtual const char* do_widen(const char* __lo, const char* __hi, char_type* __dest) const; virtual char do_narrow(char_type, char __dfault) const; virtual const char_type* do_narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __dest) const; }; template<> const ctype& use_facet >(const locale& __loc); #endif //_GLIBCPP_USE_WCHAR_T // Include host and configuration specific ctype inlines. #include // 22.2.1.2 Template class ctype_byname template class ctype_byname : public ctype<_CharT> { public: typedef _CharT char_type; explicit ctype_byname(const char* __s, size_t __refs = 0); protected: virtual ~ctype_byname() { }; }; // 22.2.1.4 Class ctype_byname specializations. template<> ctype_byname::ctype_byname(const char*, size_t refs); template<> ctype_byname::ctype_byname(const char*, size_t refs); // 22.2.1.5 Template class codecvt #include // 22.2.2 The numeric category. class __num_base { protected: // String literal of acceptable (narrow) input, for num_get. // "0123456789eEabcdfABCDF" static const char _S_atoms[]; enum { _M_zero, _M_e = _M_zero + 10, _M_E = _M_zero + 11, _M_size = 21 + 1 }; // num_put // Construct and return valid scanf format for floating point types. static bool _S_format_float(const ios_base& __io, char* __fptr, char __mod, streamsize __prec); // Construct and return valid scanf format for integer types. static void _S_format_int(const ios_base& __io, char* __fptr, char __mod, char __modl); }; template class numpunct : public locale::facet { public: // Types: typedef _CharT char_type; typedef basic_string<_CharT> string_type; static locale::id id; private: char_type _M_decimal_point; char_type _M_thousands_sep; const char* _M_grouping; const char_type* _M_truename; const char_type* _M_falsename; public: explicit numpunct(size_t __refs = 0) : locale::facet(__refs) { _M_initialize_numpunct(); } explicit numpunct(__c_locale __cloc, size_t __refs = 0) : locale::facet(__refs) { _M_initialize_numpunct(__cloc); } char_type decimal_point() const { return this->do_decimal_point(); } char_type thousands_sep() const { return this->do_thousands_sep(); } string grouping() const { return this->do_grouping(); } string_type truename() const { return this->do_truename(); } string_type falsename() const { return this->do_falsename(); } protected: virtual ~numpunct(); virtual char_type do_decimal_point() const { return _M_decimal_point; } virtual char_type do_thousands_sep() const { return _M_thousands_sep; } virtual string do_grouping() const { return _M_grouping; } virtual string_type do_truename() const { return _M_truename; } virtual string_type do_falsename() const { return _M_falsename; } // For use at construction time only. void _M_initialize_numpunct(__c_locale __cloc = _S_c_locale); }; template locale::id numpunct<_CharT>::id; template<> numpunct::~numpunct(); template<> void numpunct::_M_initialize_numpunct(__c_locale __cloc); #ifdef _GLIBCPP_USE_WCHAR_T template<> numpunct::~numpunct(); template<> void numpunct::_M_initialize_numpunct(__c_locale __cloc); #endif template class numpunct_byname : public numpunct<_CharT> { // Data Member. __c_locale _M_c_locale_numpunct; public: typedef _CharT char_type; typedef basic_string<_CharT> string_type; explicit numpunct_byname(const char* __s, size_t __refs = 0) : numpunct<_CharT>(__refs) { _S_create_c_locale(_M_c_locale_numpunct, __s); _M_initialize_numpunct(_M_c_locale_numpunct); } protected: virtual ~numpunct_byname() { _S_destroy_c_locale(_M_c_locale_numpunct); } }; template class num_get : public locale::facet, public __num_base { public: // Types: typedef _CharT char_type; typedef _InIter iter_type; static locale::id id; explicit num_get(size_t __refs = 0) : locale::facet(__refs) { } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, bool& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, long& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned short& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned int& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned long& __v) const { return this->do_get(__in, __end, __io, __err, __v); } #ifdef _GLIBCPP_USE_LONG_LONG iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, long long& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned long long& __v) const { return this->do_get(__in, __end, __io, __err, __v); } #endif iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, float& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, double& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, long double& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, void*& __v) const { return this->do_get(__in, __end, __io, __err, __v); } protected: virtual ~num_get() { } iter_type _M_extract_float(iter_type, iter_type, ios_base&, ios_base::iostate&, string& __xtrc) const; iter_type _M_extract_int(iter_type, iter_type, ios_base&, ios_base::iostate&, string& __xtrc, int& __base) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, bool&) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, long&) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& __err, unsigned short&) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& __err, unsigned int&) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& __err, unsigned long&) const; #ifdef _GLIBCPP_USE_LONG_LONG virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& __err, long long&) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& __err, unsigned long long&) const; #endif virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& __err, float&) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& __err, double&) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& __err, long double&) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& __err, void*&) const; }; template locale::id num_get<_CharT, _InIter>::id; template class num_put : public locale::facet, public __num_base { public: // Types: typedef _CharT char_type; typedef _OutIter iter_type; static locale::id id; explicit num_put(size_t __refs = 0) : locale::facet(__refs) { } iter_type put(iter_type __s, ios_base& __f, char_type __fill, bool __v) const { return this->do_put(__s, __f, __fill, __v); } iter_type put(iter_type __s, ios_base& __f, char_type __fill, long __v) const { return this->do_put(__s, __f, __fill, __v); } iter_type put(iter_type __s, ios_base& __f, char_type __fill, unsigned long __v) const { return this->do_put(__s, __f, __fill, __v); } #ifdef _GLIBCPP_USE_LONG_LONG iter_type put(iter_type __s, ios_base& __f, char_type __fill, long long __v) const { return this->do_put(__s, __f, __fill, __v); } iter_type put(iter_type __s, ios_base& __f, char_type __fill, unsigned long long __v) const { return this->do_put(__s, __f, __fill, __v); } #endif iter_type put(iter_type __s, ios_base& __f, char_type __fill, double __v) const { return this->do_put(__s, __f, __fill, __v); } iter_type put(iter_type __s, ios_base& __f, char_type __fill, long double __v) const { return this->do_put(__s, __f, __fill, __v); } iter_type put(iter_type __s, ios_base& __f, char_type __fill, const void* __v) const { return this->do_put(__s, __f, __fill, __v); } protected: template iter_type _M_convert_float(iter_type, ios_base& __io, char_type __fill, char __mod, _ValueT __v) const; template iter_type _M_convert_int(iter_type, ios_base& __io, char_type __fill, char __mod, char __modl, _ValueT __v) const; iter_type _M_widen_float(iter_type, ios_base& __io, char_type __fill, char* __cs, int __len) const; iter_type _M_widen_int(iter_type, ios_base& __io, char_type __fill, char* __cs, int __len) const; iter_type _M_insert(iter_type, ios_base& __io, char_type __fill, const char_type* __ws, int __len) const; virtual ~num_put() { }; virtual iter_type do_put(iter_type, ios_base&, char_type __fill, bool __v) const; virtual iter_type do_put(iter_type, ios_base&, char_type __fill, long __v) const; virtual iter_type do_put(iter_type, ios_base&, char_type __fill, unsigned long) const; #ifdef _GLIBCPP_USE_LONG_LONG virtual iter_type do_put(iter_type, ios_base&, char_type __fill, long long __v) const; virtual iter_type do_put(iter_type, ios_base&, char_type __fill, unsigned long long) const; #endif virtual iter_type do_put(iter_type, ios_base&, char_type __fill, double __v) const; virtual iter_type do_put(iter_type, ios_base&, char_type __fill, long double __v) const; virtual iter_type do_put(iter_type, ios_base&, char_type __fill, const void* __v) const; }; template locale::id num_put<_CharT, _OutIter>::id; template class collate : public locale::facet { public: // Types: typedef _CharT char_type; typedef basic_string<_CharT> string_type; protected: // Underlying "C" library locale information saved from // initialization, needed by collate_byname as well. __c_locale _M_c_locale_collate; public: static locale::id id; explicit collate(size_t __refs = 0) : locale::facet(__refs) { _M_c_locale_collate = _S_c_locale; } // Non-standard. explicit collate(__c_locale __cloc, size_t __refs = 0) : locale::facet(__refs) { _M_c_locale_collate = _S_clone_c_locale(__cloc); } int compare(const _CharT* __lo1, const _CharT* __hi1, const _CharT* __lo2, const _CharT* __hi2) const { return this->do_compare(__lo1, __hi1, __lo2, __hi2); } string_type transform(const _CharT* __lo, const _CharT* __hi) const { return this->do_transform(__lo, __hi); } long hash(const _CharT* __lo, const _CharT* __hi) const { return this->do_hash(__lo, __hi); } // Used to abstract out _CharT bits in virtual member functions, below. int _M_compare(const _CharT*, const _CharT*) const; size_t _M_transform(_CharT*, const _CharT*, size_t) const; protected: virtual ~collate() { if (_M_c_locale_collate != _S_c_locale) _S_destroy_c_locale(_M_c_locale_collate); } virtual int do_compare(const _CharT* __lo1, const _CharT* __hi1, const _CharT* __lo2, const _CharT* __hi2) const; virtual string_type do_transform(const _CharT* __lo, const _CharT* __hi) const; virtual long do_hash(const _CharT* __lo, const _CharT* __hi) const; }; template locale::id collate<_CharT>::id; // Specializations. template<> int collate::_M_compare(const char*, const char*) const; template<> size_t collate::_M_transform(char*, const char*, size_t) const; #ifdef _GLIBCPP_USE_WCHAR_T template<> int collate::_M_compare(const wchar_t*, const wchar_t*) const; template<> size_t collate::_M_transform(wchar_t*, const wchar_t*, size_t) const; #endif template class collate_byname : public collate<_CharT> { public: typedef _CharT char_type; typedef basic_string<_CharT> string_type; explicit collate_byname(const char* __s, size_t __refs = 0) : collate<_CharT>(__refs) { if (_M_c_locale_collate != _S_c_locale) _S_destroy_c_locale(_M_c_locale_collate); _S_create_c_locale(_M_c_locale_collate, __s); } protected: virtual ~collate_byname() { } }; class time_base { public: enum dateorder { no_order, dmy, mdy, ymd, ydm }; }; template class __timepunct : public locale::facet { public: // Types: typedef _CharT __char_type; typedef basic_string<_CharT> __string_type; static locale::id id; // List of all known timezones, with GMT first. static const _CharT* _S_timezones[14]; protected: __c_locale _M_c_locale_timepunct; const char* _M_name_timepunct; const _CharT* _M_date_format; const _CharT* _M_date_era_format; const _CharT* _M_time_format; const _CharT* _M_time_era_format; const _CharT* _M_date_time_format; const _CharT* _M_date_time_era_format; const _CharT* _M_am; const _CharT* _M_pm; const _CharT* _M_am_pm_format; // Day names, starting with "C"'s Sunday. const _CharT* _M_day1; const _CharT* _M_day2; const _CharT* _M_day3; const _CharT* _M_day4; const _CharT* _M_day5; const _CharT* _M_day6; const _CharT* _M_day7; // Abbreviated day names, starting with "C"'s Sun. const _CharT* _M_day_a1; const _CharT* _M_day_a2; const _CharT* _M_day_a3; const _CharT* _M_day_a4; const _CharT* _M_day_a5; const _CharT* _M_day_a6; const _CharT* _M_day_a7; // Month names, starting with "C"'s January. const _CharT* _M_month01; const _CharT* _M_month02; const _CharT* _M_month03; const _CharT* _M_month04; const _CharT* _M_month05; const _CharT* _M_month06; const _CharT* _M_month07; const _CharT* _M_month08; const _CharT* _M_month09; const _CharT* _M_month10; const _CharT* _M_month11; const _CharT* _M_month12; // Abbreviated month names, starting with "C"'s Jan. const _CharT* _M_month_a01; const _CharT* _M_month_a02; const _CharT* _M_month_a03; const _CharT* _M_month_a04; const _CharT* _M_month_a05; const _CharT* _M_month_a06; const _CharT* _M_month_a07; const _CharT* _M_month_a08; const _CharT* _M_month_a09; const _CharT* _M_month_a10; const _CharT* _M_month_a11; const _CharT* _M_month_a12; public: explicit __timepunct(size_t __refs = 0) : locale::facet(__refs), _M_name_timepunct("C") { _M_initialize_timepunct(); } explicit __timepunct(__c_locale __cloc, const char* __s, size_t __refs = 0) : locale::facet(__refs), _M_name_timepunct(__s) { _M_initialize_timepunct(__cloc); } void _M_put(_CharT* __s, size_t __maxlen, const _CharT* __format, const tm* __tm) const; void _M_date_formats(const _CharT** __date) const { // Always have default first. __date[0] = _M_date_format; __date[1] = _M_date_era_format; } void _M_time_formats(const _CharT** __time) const { // Always have default first. __time[0] = _M_time_format; __time[1] = _M_time_era_format; } void _M_ampm(const _CharT** __ampm) const { __ampm[0] = _M_am; __ampm[1] = _M_pm; } void _M_date_time_formats(const _CharT** __dt) const { // Always have default first. __dt[0] = _M_date_time_format; __dt[1] = _M_date_time_era_format; } void _M_days(const _CharT** __days) const { __days[0] = _M_day1; __days[1] = _M_day2; __days[2] = _M_day3; __days[3] = _M_day4; __days[4] = _M_day5; __days[5] = _M_day6; __days[6] = _M_day7; } void _M_days_abbreviated(const _CharT** __days) const { __days[0] = _M_day_a1; __days[1] = _M_day_a2; __days[2] = _M_day_a3; __days[3] = _M_day_a4; __days[4] = _M_day_a5; __days[5] = _M_day_a6; __days[6] = _M_day_a7; } void _M_months(const _CharT** __months) const { __months[0] = _M_month01; __months[1] = _M_month02; __months[2] = _M_month03; __months[3] = _M_month04; __months[4] = _M_month05; __months[5] = _M_month06; __months[6] = _M_month07; __months[7] = _M_month08; __months[8] = _M_month09; __months[9] = _M_month10; __months[10] = _M_month11; __months[11] = _M_month12; } void _M_months_abbreviated(const _CharT** __months) const { __months[0] = _M_month_a01; __months[1] = _M_month_a02; __months[2] = _M_month_a03; __months[3] = _M_month_a04; __months[4] = _M_month_a05; __months[5] = _M_month_a06; __months[6] = _M_month_a07; __months[7] = _M_month_a08; __months[8] = _M_month_a09; __months[9] = _M_month_a10; __months[10] = _M_month_a11; __months[11] = _M_month_a12; } protected: virtual ~__timepunct(); // For use at construction time only. void _M_initialize_timepunct(__c_locale __cloc = _S_c_locale); }; template locale::id __timepunct<_CharT>::id; // Specializations. template<> __timepunct::~__timepunct(); template<> const char* __timepunct::_S_timezones[14]; template<> void __timepunct::_M_initialize_timepunct(__c_locale __cloc); template<> void __timepunct::_M_put(char*, size_t, const char*, const tm*) const; #ifdef _GLIBCPP_USE_WCHAR_T template<> __timepunct::~__timepunct(); template<> const wchar_t* __timepunct::_S_timezones[14]; template<> void __timepunct::_M_initialize_timepunct(__c_locale __cloc); template<> void __timepunct::_M_put(wchar_t*, size_t, const wchar_t*, const tm*) const; #endif // Generic. template const _CharT* __timepunct<_CharT>::_S_timezones[14]; template class time_get : public locale::facet, public time_base { public: // Types: typedef _CharT char_type; typedef _InIter iter_type; typedef basic_string<_CharT> __string_type; static locale::id id; explicit time_get(size_t __refs = 0) : locale::facet (__refs) { } dateorder date_order() const { return this->do_date_order(); } iter_type get_time(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { return this->do_get_time(__beg, __end, __io, __err, __tm); } iter_type get_date(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { return this->do_get_date(__beg, __end, __io, __err, __tm); } iter_type get_weekday(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { return this->do_get_weekday(__beg, __end, __io, __err, __tm); } iter_type get_monthname(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { return this->do_get_monthname(__beg, __end, __io, __err, __tm); } iter_type get_year(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { return this->do_get_year(__beg, __end, __io, __err, __tm); } protected: virtual ~time_get() { } virtual dateorder do_date_order() const; virtual iter_type do_get_time(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const; virtual iter_type do_get_date(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const; virtual iter_type do_get_weekday(iter_type __beg, iter_type __end, ios_base&, ios_base::iostate& __err, tm* __tm) const; virtual iter_type do_get_monthname(iter_type __beg, iter_type __end, ios_base&, ios_base::iostate& __err, tm* __tm) const; virtual iter_type do_get_year(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const; // Extract numeric component of length __len. void _M_extract_num(iter_type& __beg, iter_type& __end, int& __member, int __min, int __max, size_t __len, const ctype<_CharT>& __ctype, ios_base::iostate& __err) const; // Extract day or month name, or any unique array of string // literals in a const _CharT* array. void _M_extract_name(iter_type& __beg, iter_type& __end, int& __member, const _CharT** __names, size_t __indexlen, ios_base::iostate& __err) const; // Extract on a component-by-component basis, via __format argument. void _M_extract_via_format(iter_type& __beg, iter_type& __end, ios_base& __io, ios_base::iostate& __err, tm* __tm, const _CharT* __format) const; }; template locale::id time_get<_CharT, _InIter>::id; template class time_get_byname : public time_get<_CharT, _InIter> { public: // Types: typedef _CharT char_type; typedef _InIter iter_type; explicit time_get_byname(const char*, size_t __refs = 0) : time_get<_CharT, _InIter>(__refs) { } protected: virtual ~time_get_byname() { } }; template class time_put : public locale::facet, public time_base { public: // Types: typedef _CharT char_type; typedef _OutIter iter_type; static locale::id id; explicit time_put(size_t __refs = 0) : locale::facet(__refs) { } iter_type put(iter_type __s, ios_base& __io, char_type __fill, const tm* __tm, const _CharT* __beg, const _CharT* __end) const; iter_type put(iter_type __s, ios_base& __io, char_type __fill, const tm* __tm, char __format, char __mod = 0) const { return this->do_put(__s, __io, __fill, __tm, __format, __mod); } protected: virtual ~time_put() { } virtual iter_type do_put(iter_type __s, ios_base& __io, char_type __fill, const tm* __tm, char __format, char __mod) const; }; template locale::id time_put<_CharT, _OutIter>::id; template class time_put_byname : public time_put<_CharT, _OutIter> { public: // Types: typedef _CharT char_type; typedef _OutIter iter_type; explicit time_put_byname(const char* /*__s*/, size_t __refs = 0) : time_put<_CharT, _OutIter>(__refs) { }; protected: virtual ~time_put_byname() { } }; class money_base { public: enum part { none, space, symbol, sign, value }; struct pattern { char field[4]; }; static const pattern _S_default_pattern; // Construct and return valid pattern consisting of some combination of: // space none symbol sign value static pattern _S_construct_pattern(char __precedes, char __space, char __posn); }; template class moneypunct : public locale::facet, public money_base { public: // Types: typedef _CharT char_type; typedef basic_string<_CharT> string_type; static const bool intl = _Intl; static locale::id id; private: const char* _M_grouping; char_type _M_decimal_point; char_type _M_thousands_sep; const char_type* _M_curr_symbol; const char_type* _M_positive_sign; const char_type* _M_negative_sign; int _M_frac_digits; pattern _M_pos_format; pattern _M_neg_format; public: explicit moneypunct(size_t __refs = 0) : locale::facet(__refs) { _M_initialize_moneypunct(); } explicit moneypunct(__c_locale __cloc, size_t __refs = 0) : locale::facet(__refs) { _M_initialize_moneypunct(__cloc); } char_type decimal_point() const { return this->do_decimal_point(); } char_type thousands_sep() const { return this->do_thousands_sep(); } string grouping() const { return this->do_grouping(); } string_type curr_symbol() const { return this->do_curr_symbol(); } string_type positive_sign() const { return this->do_positive_sign(); } string_type negative_sign() const { return this->do_negative_sign(); } int frac_digits() const { return this->do_frac_digits(); } pattern pos_format() const { return this->do_pos_format(); } pattern neg_format() const { return this->do_neg_format(); } protected: virtual ~moneypunct(); virtual char_type do_decimal_point() const { return _M_decimal_point; } virtual char_type do_thousands_sep() const { return _M_thousands_sep; } virtual string do_grouping() const { return _M_grouping; } virtual string_type do_curr_symbol() const { return _M_curr_symbol; } virtual string_type do_positive_sign() const { return _M_positive_sign; } virtual string_type do_negative_sign() const { return _M_negative_sign; } virtual int do_frac_digits() const { return _M_frac_digits; } virtual pattern do_pos_format() const { return _M_pos_format; } virtual pattern do_neg_format() const { return _M_neg_format; } // For use at construction time only. void _M_initialize_moneypunct(__c_locale __cloc = _S_c_locale); }; template locale::id moneypunct<_CharT, _Intl>::id; template const bool moneypunct<_CharT, _Intl>::intl; template<> moneypunct::~moneypunct(); template<> moneypunct::~moneypunct(); template<> void moneypunct::_M_initialize_moneypunct(__c_locale __cloc); template<> void moneypunct::_M_initialize_moneypunct(__c_locale __cloc); #ifdef _GLIBCPP_USE_WCHAR_T template<> moneypunct::~moneypunct(); template<> moneypunct::~moneypunct(); template<> void moneypunct::_M_initialize_moneypunct(__c_locale __cloc); template<> void moneypunct::_M_initialize_moneypunct(__c_locale __cloc); #endif template class moneypunct_byname : public moneypunct<_CharT, _Intl> { __c_locale _M_c_locale_moneypunct; public: typedef _CharT char_type; typedef basic_string<_CharT> string_type; static const bool intl = _Intl; explicit moneypunct_byname(const char* __s, size_t __refs = 0) : moneypunct<_CharT, _Intl>(__refs) { _S_create_c_locale(_M_c_locale_moneypunct, __s); _M_initialize_moneypunct(_M_c_locale_moneypunct); } protected: virtual ~moneypunct_byname() { _S_destroy_c_locale(_M_c_locale_moneypunct); } }; template const bool moneypunct_byname<_CharT, _Intl>::intl; template class money_get : public locale::facet { public: // Types: typedef _CharT char_type; typedef _InIter iter_type; typedef basic_string<_CharT> string_type; static locale::id id; explicit money_get(size_t __refs = 0) : locale::facet(__refs) { } iter_type get(iter_type __s, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, long double& __units) const { return this->do_get(__s, __end, __intl, __io, __err, __units); } iter_type get(iter_type __s, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, string_type& __digits) const { return this->do_get(__s, __end, __intl, __io, __err, __digits); } protected: virtual ~money_get() { } virtual iter_type do_get(iter_type __s, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, long double& __units) const; virtual iter_type do_get(iter_type __s, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, string_type& __digits) const; }; template locale::id money_get<_CharT, _InIter>::id; template class money_put : public locale::facet { public: typedef _CharT char_type; typedef _OutIter iter_type; typedef basic_string<_CharT> string_type; static locale::id id; explicit money_put(size_t __refs = 0) : locale::facet(__refs) { } iter_type put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, long double __units) const { return this->do_put(__s, __intl, __io, __fill, __units); } iter_type put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, const string_type& __digits) const { return this->do_put(__s, __intl, __io, __fill, __digits); } protected: virtual ~money_put() { } virtual iter_type do_put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, long double __units) const; virtual iter_type do_put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, const string_type& __digits) const; }; template locale::id money_put<_CharT, _OutIter>::id; struct messages_base { typedef int catalog; }; template class messages : public locale::facet, public messages_base { public: // Types: typedef _CharT char_type; typedef basic_string<_CharT> string_type; protected: // Underlying "C" library locale information saved from // initialization, needed by messages_byname as well. __c_locale _M_c_locale_messages; #if 1 // Only needed if glibc < 2.3 const char* _M_name_messages; #endif public: static locale::id id; explicit messages(size_t __refs = 0) : locale::facet(__refs), _M_name_messages("C") { _M_c_locale_messages = _S_c_locale; } // Non-standard. explicit messages(__c_locale __cloc, const char* __name, size_t __refs = 0) : locale::facet(__refs) { _M_name_messages = __name; _M_c_locale_messages = _S_clone_c_locale(__cloc); } catalog open(const basic_string& __s, const locale& __loc) const { return this->do_open(__s, __loc); } // Non-standard and unorthodox, yet effective. catalog open(const basic_string&, const locale&, const char*) const; string_type get(catalog __c, int __set, int __msgid, const string_type& __s) const { return this->do_get(__c, __set, __msgid, __s); } void close(catalog __c) const { return this->do_close(__c); } protected: virtual ~messages() { if (_M_c_locale_messages != _S_c_locale) _S_destroy_c_locale(_M_c_locale_messages); } virtual catalog do_open(const basic_string&, const locale&) const; virtual string_type do_get(catalog, int, int, const string_type& __dfault) const; virtual void do_close(catalog) const; // Returns a locale and codeset-converted string, given a char* message. char* _M_convert_to_char(const string_type& __msg) const { // XXX return reinterpret_cast(const_cast<_CharT*>(__msg.c_str())); } // Returns a locale and codeset-converted string, given a char* message. string_type _M_convert_from_char(char* __msg) const { // Length of message string without terminating null. size_t __len = char_traits::length(__msg) - 1; // "everybody can easily convert the string using // mbsrtowcs/wcsrtombs or with iconv()" #if 0 // Convert char* to _CharT in locale used to open catalog. // XXX need additional template parameter on messages class for this.. // typedef typename codecvt __codecvt_type; typedef typename codecvt __codecvt_type; __codecvt_type::state_type __state; // XXX may need to initialize state. //initialize_state(__state._M_init()); char* __from_next; // XXX what size for this string? _CharT* __to = static_cast<_CharT*>(__builtin_alloca(__len + 1)); const __codecvt_type& __cvt = use_facet<__codecvt_type>(_M_locale_conv); __cvt.out(__state, __msg, __msg + __len, __from_next, __to, __to + __len + 1, __to_next); return string_type(__to); #endif #if 0 typedef ctype<_CharT> __ctype_type; // const __ctype_type& __cvt = use_facet<__ctype_type>(_M_locale_msg); const __ctype_type& __cvt = use_facet<__ctype_type>(locale()); // XXX Again, proper length of converted string an issue here. // For now, assume the converted length is not larger. _CharT* __dest = static_cast<_CharT*>(__builtin_alloca(__len + 1)); __cvt.widen(__msg, __msg + __len, __dest); return basic_string<_CharT>(__dest); #endif return string_type(); } }; template locale::id messages<_CharT>::id; // Specializations for required instantiations. template<> string messages::do_get(catalog, int, int, const string&) const; // Include host and configuration specific messages virtual functions. #include template class messages_byname : public messages<_CharT> { public: typedef _CharT char_type; typedef basic_string<_CharT> string_type; explicit messages_byname(const char* __s, size_t __refs = 0) : messages<_CharT>(__refs) { _M_name_messages = __s; if (_M_c_locale_messages != _S_c_locale) _S_destroy_c_locale(_M_c_locale_messages); _S_create_c_locale(_M_c_locale_messages, __s); } protected: virtual ~messages_byname() { } }; // Subclause convenience interfaces, inlines. // NB: These are inline because, when used in a loop, some compilers // can hoist the body out of the loop; then it's just as fast as the // C is*() function. template inline bool isspace(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::space, __c); } template inline bool isprint(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::print, __c); } template inline bool iscntrl(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::cntrl, __c); } template inline bool isupper(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::upper, __c); } template inline bool islower(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::lower, __c); } template inline bool isalpha(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::alpha, __c); } template inline bool isdigit(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::digit, __c); } template inline bool ispunct(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::punct, __c); } template inline bool isxdigit(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::xdigit, __c); } template inline bool isalnum(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::alnum, __c); } template inline bool isgraph(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::graph, __c); } template inline _CharT toupper(_CharT __c, const locale& __loc) { return use_facet >(__loc).toupper(__c); } template inline _CharT tolower(_CharT __c, const locale& __loc) { return use_facet >(__loc).tolower(__c); } } // namespace std #endif Top 10 Lines: Line Count 108 44 104 4 Execution Summary: 2 Executable lines in this file 2 Lines executed 100.00 Percent of the file executed 48 Total number of line executions 24.00 Average executions per line