Example #1
0
File: parser.c Project: ihh/gertie
void parserPushTok (Parser *parser, int tok) {
  int old_len, j, i, k;
  Cell *j_cell, **new_cell;
  int *new_tokseq;
  Rule *rule, *rule_end;

  old_len = parser->len;
  j = old_len + 1;
  if (j >= parser->alloc) {
    parser->alloc *= 2;
    new_cell = SafeCalloc (parser->alloc, sizeof(Cell) + 1);
    new_tokseq = SafeCalloc (parser->alloc, sizeof(int));
    for (i = 0; i <= old_len; ++i)
      new_cell[i] = parser->cell[i];
    for (i = 0; i < old_len; ++i)
      new_tokseq[i] = parser->tokseq[i];
    SafeFree (parser->cell);
    SafeFree (parser->tokseq);
    parser->cell = new_cell;
    parser->tokseq = new_tokseq;
  }
  parser->tokseq[old_len] = tok;
  j_cell = cellNewTok (parser, j, tok);
  parser->cell[j] = j_cell;
  parser->len = j;

  rule_end = parser->rule + parser->rules;
  for (i = old_len; i >= 0; --i)
    for (rule = parser->rule; rule != rule_end; ++rule) {
      for (k = i; k <= j; ++k) {
	cell_inc_p
	  (j_cell, i, j, rule->lhs_sym,
	   parser_get_p(parser,i,k,rule->rhs1_sym) * parser_get_p(parser,k,j,rule->rhs2_sym) * rule->rule_prob);
	if (parser->debug)
	  printf ("%g  -->  p(%d,%d,%d) += p(%d,%d,%d) * p(%d,%d,%d) * %g;\n",
		  parser_get_p(parser,i,j,rule->lhs_sym),
		  i,j,rule->lhs_sym, i,k,rule->rhs1_sym, k,j,rule->rhs2_sym, rule->rule_prob);
  
	cell_inc_q
	  (j_cell, i, j, rule->lhs_sym,
	   parser_get_p(parser,i,k,rule->rhs1_sym) * parser_get_q(parser,k,rule->rhs2_sym) * rule->rule_prob);
	if (parser->debug)
	  printf ("%g  -->  q(%d,%d) += p(%d,%d,%d) * q(%d,%d) * %g;\n",
		  parser_get_q(parser,i,rule->lhs_sym),
		  i,rule->lhs_sym, i,k,rule->rhs1_sym, k,rule->rhs2_sym, rule->rule_prob);
      }
      cell_inc_q
	(j_cell, i, j, rule->lhs_sym,
	 parser_get_q(parser,i,rule->rhs1_sym) * rule->rule_prob);
      if (parser->debug)
	printf ("%g  -->  q(%d,%d) += q(%d,%d) * %g;\n",
		parser_get_q(parser,i,rule->lhs_sym),
		i,rule->lhs_sym, i,rule->rhs1_sym, rule->rule_prob);
    }
}
Example #2
0
File: parser.c Project: ihh/gertie
Cell* cellNew (Parser *parser, int j) {
  Cell *cell;
  int sym;
  cell = SafeMalloc (sizeof (Cell));
  cell->p = SafeCalloc (parser->symbols * (j+1), sizeof (double));
  cell->q = SafeCalloc (parser->symbols * (j+1), sizeof (double));
  for (sym = 0; sym < parser->symbols; ++sym) {
    cell_get_p(cell,j,j,sym) = parser->p_empty[sym];
    cell_get_q(cell,j,j,sym) = 1. - parser->p_empty[sym];
  }
  return cell;
}
Example #3
0
/* CopyResults: copy results from one file to another up to lastGen*/
int CopyResults (FILE *toFile, char *fromFileName, int lastGen)
{
    int     longestLine;
    char    *strBuf, *strCpy, *word;
    FILE    *fromFile;

    if ((fromFile = OpenBinaryFileR(fromFileName)) == NULL)
        return ERROR;

    longestLine = LongestLine(fromFile)+10;
    SafeFclose(&fromFile);
    strBuf = (char *) SafeCalloc (2*(longestLine+2),sizeof(char));
    strCpy = strBuf + longestLine + 2;

    if ((fromFile = OpenTextFileR(fromFileName)) == NULL)
        return ERROR;
    
    while (fgets(strBuf,longestLine,fromFile)!=NULL)
        {
        strncpy(strCpy,strBuf,longestLine);
        word = strtok(strCpy," ");
        /* atoi returns 0 when word is not integer number */
        if (atoi(word)>lastGen)
            break;
        fprintf (toFile,"%s",strBuf);
        fflush (toFile);
        }
    
    SafeFclose(&fromFile);
    free(strBuf);
    return (NO_ERROR);
}
static int* GetIntListToArray(PyObject* pyList, int* size,
			      const int minVal, const int maxVal) {
  int i;
  int* result;
  PyObject* item;

  assert(PyList_Check(pyList));
  *size = PyList_GET_SIZE(pyList);
  result = SafeCalloc(*size,sizeof(int));
  for (i=0; i<*size; i++) {
    item = PyList_GET_ITEM(pyList,i);
    if (! PyInt_Check(item)) {
      PyErr_Format(PyExc_TypeError,"element %i not an integer",i);
      free(result);
      return NULL;
    }
    result[i]=PyInt_AsLong(item);
    if (result[i] > maxVal || result[i] < minVal) {
      PyErr_Format(PyExc_TypeError,"element %i = %i not in [%i,%i]",
		   i,result[i],minVal,maxVal);
      free(result);
      return NULL;
    }
  }
  return result;
}
Example #5
0
/* GetIntSummary: Get summary statistics for a number of runs (int version) */
void GetIntSummary (int **vals, int nRows, int *rowCount, Stat *theStats, int HPD)

{

    int     i, j, nVals;
    MrBFlt  *theValues, *p;

    nVals = 0;
    for (i=0; i<nRows; i++)
        nVals += rowCount[i];

    theValues = (MrBFlt *) SafeCalloc (nVals, sizeof(MrBFlt));

    /* extract values */
    p = theValues;
    for (i=0; i<nRows; i++)
        {
        for (j=0; j<rowCount[i]; j++)
            {
            (*p++) = (MrBFlt) (vals[i][j]);
            }
        }
    
    /* get statistics */
    MeanVariance (theValues, nVals, &(theStats->mean), &(theStats->var));
    if (HPD == YES)
        LowerUpperMedian (theValues, nVals, &(theStats->lower), &(theStats->upper), &(theStats->median));
    else
        LowerUpperMedian (theValues, nVals, &(theStats->lower), &(theStats->upper), &(theStats->median));

    free (theValues);
}
Example #6
0
/*
   ============
   =
   = initFromFile:
   =
   ============
 */
void initFromFile(void)
{
	wadinfo_t	wad;
	lumpinfo_t	*lumps;
	int		i;

	/* read in the header */
	fread(&wad, sizeof(wad), 1, wad_i.handle);
	if (strncmp(wad.identification, "PWAD", 4))
	{
		Error("initFromFile: specified WAD is not a PWAD");
	}

	/* read in the lumpinfo */
	fseek(wad_i.handle, wad.infotableofs, SEEK_SET);

	wad_i.info = (STORAGE *) SafeMalloc(sizeof(STORAGE));
	wad_i.info->data = (lumpinfo_t *) SafeCalloc(wad.numlumps,
				sizeof(lumpinfo_t));
	wad_i.info->count = wad.numlumps;
	wad_i.info->size = sizeof(lumpinfo_t);
	lumps = wad_i.info->data;

	fread(lumps, sizeof(lumpinfo_t), wad.numlumps, wad_i.handle);

	for (i = 0; i < wad.numlumps; i++, lumps++)
	{
		lumps->filepos = bswapl(lumps->filepos);
		lumps->size = bswapl(lumps->size);
	}

	return;
}
Example #7
0
/* SafeStrcat: Allocate or reallocate target to fit result; assumes ptr is NULL if not allocated */
char *SafeStrcat (char **target, const char *source)
{
    if (*target == NULL)
        *target = (char *) SafeCalloc (strlen(source)+1, sizeof(char));
    else
        *target = (char *) SafeRealloc ((void *)*target, (size_t)(strlen(source)+strlen(*target)+1)*sizeof(char));

    if (*target)
        strcat(*target,source);

    return (*target);
}
Example #8
0
File: parser.c Project: ihh/gertie
Parser* parserNew (int symbols, int rules) {
  Parser* parser;
  parser = SafeMalloc (sizeof (Parser));
  parser->symbols = symbols;
  parser->rules = rules;
  parser->len = 0;
  parser->alloc = 1;
  parser->debug = 0;
  parser->rule = SafeMalloc (rules * sizeof (Rule));
  parser->p_empty = SafeCalloc (symbols, sizeof (double));
  parser->cell = SafeMalloc (sizeof (Cell*));
  parser->tokseq = NULL;
  parser->cell[0] = NULL;
  return parser;
}
Example #9
0
/* CopyTreeResults: copy tree results upto lastGen from one file to another. numTrees is return containing number of trees that were copied. */
int CopyTreeResults (FILE *toFile, char *fromFileName, int lastGen, int *numTrees)
{
    int     longestLine;
    char    *strBuf, *strCpy, *word;
    FILE    *fromFile;
    
    (*numTrees) = 0;

    if ((fromFile = OpenBinaryFileR(fromFileName)) == NULL)
        return ERROR;

    longestLine = LongestLine(fromFile)+10;
    SafeFclose(&fromFile);
    strBuf = (char *) SafeCalloc (2*(longestLine+2),sizeof(char));
    strCpy = strBuf + longestLine + 2;

    if ((fromFile = OpenTextFileR(fromFileName)) == NULL)
        return ERROR;
    
    while (fgets(strBuf,longestLine,fromFile)!=NULL)
        {
        strncpy(strCpy,strBuf,longestLine);
        word = strtok(strCpy," ");
        if (strcmp(word,"tree")==0)
            {
            word = strtok(NULL," ");
            /* atoi returns 0 when word is not integer number,
               4 is offset to get rid of "rep." in tree name */
            if (atoi(word+4)>lastGen)
                break;
            (*numTrees)++;
            fprintf (toFile,"%s",strBuf);
            }
        else if (*numTrees == 0)   /* do not print the end statement */
            fprintf (toFile,"%s",strBuf);
        fflush (toFile);
        }
        
    SafeFclose(&fromFile);
    free(strBuf);
    return (NO_ERROR);
}
static double* GetPyFloatListToArrayOfDoubles(const char*const argName,
					      const int requiredSize,
					      const double minVal,
					      const double maxVal,
					      PyObject* pyList) {
  int i, size;
  double* result;
  PyObject* item;

  assert(PyList_Check(pyList));
  size = PyList_GET_SIZE(pyList);
  if (requiredSize != size) {
    PyErr_Format(PyExc_TypeError,"%s:list size should be %i not %i",
		 argName,requiredSize,size);
    return NULL;
  }
  result = SafeCalloc(requiredSize,sizeof(double));
  for (i=0; i<requiredSize; i++) {
    item = PyList_GET_ITEM(pyList,i);
    if (PyInt_Check(item)) result[i] = PyInt_AsLong(item);
    else if (PyFloat_Check(item)) result[i]=PyFloat_AsDouble(item);
    else {
      PyErr_Format(PyExc_TypeError,"%s:element %i not an int or float",
		   argName,i);
      free(result);
      return NULL;
    }
    if (result[i] > maxVal || result[i] < minVal) {
      PyErr_Format(PyExc_TypeError,"%s:element %i not in required range",
		   argName,i);
      free(result);
      return NULL;
    }
  }
  return result;
}
/* The numChecks field must already be set */
void InitVarNode(VariableNode*const vn) {
  vn->edges = SafeCalloc(vn->numChecks,sizeof(GraphEdge*));
}
void InitCheckNode(CheckNode*const cn, const int numVars) {
  cn->numVars = numVars;
  cn->edges = SafeCalloc(numVars,sizeof(GraphEdge*));
}
Example #13
0
/* CopyProcessSsFile: copy results from one file to another up to lastStep. Also marginalLnLSS is collected for processed steps*/
int CopyProcessSsFile (FILE *toFile, char *fromFileName, int lastStep, MrBFlt *marginalLnLSS, MrBFlt * splitfreqSS)
{
    int     longestLine, run, curStep, i;
    double  tmp;
    char    *strBuf, *strCpy, *word, *tmpcp;
    FILE    *fromFile;

    if ((fromFile = OpenBinaryFileR(fromFileName)) == NULL)
        return ERROR;

    longestLine = LongestLine(fromFile)+10;
    SafeFclose(&fromFile);
    strBuf = (char *) SafeCalloc (2*(longestLine+2),sizeof(char));
    strCpy = strBuf + longestLine + 2;

    if ((fromFile = OpenTextFileR(fromFileName)) == NULL)
        return ERROR;
    
    while (fgets(strBuf,longestLine,fromFile)!=NULL)
        {
        strncpy(strCpy,strBuf,longestLine);
        word = strtok(strCpy," \t\n");
        /* atoi returns 0 when word is not integer number */
        if (atoi(word)>lastStep)
            break;
        fprintf (toFile,"%s",strBuf);
        fflush (toFile);
        curStep = atoi(word);
        if ( curStep > 0 )
            {
            strtok(NULL,"\t\n"); /*skip power*/
            for (run=0; run<chainParams.numRuns; run++)
                {
                tmpcp = strtok(NULL,"\t\n");
                if(tmpcp == NULL )
                    {
                    MrBayesPrint ("%s   Error: In .ss file not enough ellements on the string :%s        \n", spacer, strBuf);
                    return ERROR;
                    }
                tmp = atof(tmpcp);
                if(tmp == 0.0 )
                    {
                    MrBayesPrint ("%s   Error: Value of some step contribution is 0.0 or not a number in .ss file. Sting:%s        \n", spacer, strBuf);
                    return ERROR;
                    }
                marginalLnLSS[run]+=tmp;
                }
			for (i=0; i<numTopologies; i++)
				{
                tmpcp = strtok(NULL,"\t\n");
                if(tmpcp == NULL )
                    {
                    MrBayesPrint ("%s   Error: In .ss file not enough ellements on the string :%s        \n", spacer, strBuf);
                    return ERROR;
                    }
                tmp = atof(tmpcp);
                splitfreqSS[i*chainParams.numStepsSS + curStep-1] = tmp;                
    			}
            }
        }
    
    SafeFclose(&fromFile);
    free(strBuf);
    return (NO_ERROR);
}
Example #14
0
/*------------------------------------------------------------------------
|
|	InitBeagleInstance: create and initialize a beagle instance
|
-------------------------------------------------------------------------*/
int InitBeagleInstance (ModelInfo *m, int division)
{
    int                     i, j, k, c, s, *inStates, numPartAmbigTips;
    double                  *inPartials;
    SafeLong                *charBits;
    BeagleInstanceDetails   details;
    long preferedFlags, requiredFlags;
	int resource;
    
    if (m->useBeagle == NO)
        return ERROR;
    
    /* at least one eigen buffer needed */
    if (m->nCijkParts == 0)
        m->nCijkParts = 1;

    /* allocate memory used by beagle */
    m->logLikelihoods          = (MrBFlt *) SafeCalloc ((numLocalChains)*m->numChars, sizeof(MrBFlt));
    m->inRates                 = (MrBFlt *) SafeCalloc (m->numGammaCats, sizeof(MrBFlt));
    m->branchLengths           = (MrBFlt *) SafeCalloc (2*numLocalTaxa, sizeof(MrBFlt));
    m->tiProbIndices           = (int *) SafeCalloc (2*numLocalTaxa, sizeof(int));
    m->inWeights               = (MrBFlt *) SafeCalloc (m->numGammaCats*m->nCijkParts, sizeof(MrBFlt));
    m->bufferIndices           = (int *) SafeCalloc (m->nCijkParts, sizeof(int));
    m->eigenIndices            = (int *) SafeCalloc (m->nCijkParts, sizeof(int));
    m->childBufferIndices      = (int *) SafeCalloc (m->nCijkParts, sizeof(int));
    m->childTiProbIndices      = (int *) SafeCalloc (m->nCijkParts, sizeof(int));
    m->cumulativeScaleIndices  = (int *) SafeCalloc (m->nCijkParts, sizeof(int));

    numPartAmbigTips = 0;
    if (m->numStates != m->numModelStates)
        numPartAmbigTips = numLocalTaxa;
    else
        {
        for (i=0; i<numLocalTaxa; i++)
            {
            if (m->isPartAmbig[i] == YES)
                numPartAmbigTips++;
            }
        }

	if (beagleResourceCount == 0) 
		{
		preferedFlags = beagleFlags;
		} 
		else 
		{
		resource = beagleResource[beagleInstanceCount % beagleResourceCount];
		preferedFlags = beagleFlags;		
		}
	
    requiredFlags = 0L;
    
    if (beagleScalingScheme == MB_BEAGLE_SCALE_ALWAYS)
        requiredFlags |= BEAGLE_FLAG_SCALERS_LOG; //BEAGLE_FLAG_SCALERS_RAW; 
 

    /* TODO: allocate fewer buffers when nCijkParts > 1 */
    /* create beagle instance */
    m->beagleInstance = beagleCreateInstance(numLocalTaxa,
                                             m->numCondLikes * m->nCijkParts,
                                             numLocalTaxa - numPartAmbigTips,
                                             m->numModelStates,
                                             m->numChars,
                                            (numLocalChains + 1) * m->nCijkParts,
                                             m->numTiProbs*m->nCijkParts,
                                             m->numGammaCats,
                                             m->numScalers * m->nCijkParts,
											 (beagleResourceCount == 0 ? NULL : &resource),
                                             (beagleResourceCount == 0 ? 0 : 1),                                             
                                             preferedFlags,
                                             requiredFlags,
                                             &details);

    if (m->beagleInstance < 0)
        {
        MrBayesPrint ("%s   Failed to start BEAGLE instance\n", spacer);
        return (ERROR);
        }
    else
        {
		MrBayesPrint( "\n%s   Using BEAGLE resource %i for division %d:", spacer, details.resourceNumber, division+1);
#if defined (THREADS_ENABLED)
        MrBayesPrint( " (%s)\n", (tryToUseThreads ? "threaded" : "non-threaded"));
#else
		MrBayesPrint( " (non-threaded)\n");
#endif
    	MrBayesPrint( "%s      Rsrc Name : %s\n", spacer, details.resourceName);
    	MrBayesPrint( "%s      Impl Name : %s\n", spacer, details.implName);    
    	MrBayesPrint( "%s      Flags:", spacer);
    	BeaglePrintFlags(details.flags);
    	MrBayesPrint( "\n");
		beagleInstanceCount++;			
        }

    /* initialize tip data */
    inStates = (int *) SafeMalloc (m->numChars * sizeof(int));
    if (!inStates)
        return ERROR;
    inPartials = (double *) SafeMalloc (m->numChars * m->numModelStates * sizeof(double));
    if (!inPartials)
        return ERROR;
    for (i=0; i<numLocalTaxa; i++)
        {
        if (m->isPartAmbig[i] == NO)
            {
            charBits = m->parsSets[i];
            for (c=0; c<m->numChars; c++)
                {
                for (s=j=0; s<m->numModelStates; s++)
                    {
                    if (IsBitSet(s, charBits))
                        {
                        inStates[c] = s;
                        j++;
                        }
                    }
                if (j == m->numModelStates)
                    inStates[c] = j;
                else
                    assert(j==1);
                charBits += m->nParsIntsPerSite;
                }
            beagleSetTipStates(m->beagleInstance, i, inStates);
            }
        else /* if (m->isPartAmbig == YES) */
            {
            k = 0;
            charBits = m->parsSets[i];
            for (c=0; c<m->numChars; c++)
                {
                for (s=0; s<m->numModelStates; s++)
                    {
                    if (IsBitSet(s%m->numStates, charBits))
                        inPartials[k++] = 1.0;
                    else
                        inPartials[k++] = 0.0;
                    }
                charBits += m->nParsIntsPerSite;
                }
            beagleSetTipPartials(m->beagleInstance, i, inPartials);
            }
        }
    free (inStates);
    free (inPartials);

    return NO_ERROR;
}