Example #1
0
CirCut*
CirCut::merge(const CirCut* cut) const {
	// check if signature implies that the merged cut is too big
	if(numOfOne(_sign | cut->getSign()) > _maxCutSize) return 0;

	CirCut* retCut = new CirCut;

   unsigned n1 = size(), n2 = cut->size();
   unsigned p1 = 0, p2 = 0;
   while(p1 < n1 || p2 < n2){
      if(p2 == n2) 
         retCut->addLeafForce( getLeaf(p1++) );
      else if(p1 == n1) 
         retCut->addLeafForce( cut->getLeaf(p2++) );
      else if(getLeaf(p1) < cut->getLeaf(p2))
         retCut->addLeafForce( getLeaf(p1++) );
      else if(getLeaf(p1) > cut->getLeaf(p2))
         retCut->addLeafForce( cut->getLeaf(p2++) );
      else
         p2++;
   }

	if(retCut->size() > _maxCutSize){
		delete retCut;
		retCut = 0;
	}
	return retCut;
}
Example #2
0
bool
CirCut::dominateCut(const CirCut* cut) const {
	if((_sign & cut->getSign()) != _sign) return false;
   unsigned n1 = size(), n2 = cut->size();
	for(unsigned i1=0, i2=0; i1<n1 && i2<n2; ++i1){
      while(i2 < n2 && cut->getLeaf(i2) < getLeaf(i1)) i2++;
      if(i2 == n2 || cut->getLeaf(i2) != getLeaf(i1)) return false;
   }
	return true;
}
void *BusyWork(void *t)
{
  long tid;
  tid = (long)t;
  //fprintf(fp_log, "Thread %ld starting...\n", tid);
  
  float score;
  float sum;
  int iIndex, tindex, i, j;
  int begin_index, end_index, divide;
  divide = numberOfInstances / NUM_THREADS;
  begin_index = (int)tid * divide;
  end_index = (int)(tid+1) * divide;
  sum = 0;
  for(iIndex = begin_index; iIndex < end_index; iIndex+=F) {
    score = 0;
    for(tindex = 0; tindex < nbTrees; tindex+=T) {
      for (i=0; i<F; i++)
        for (j=0; j<T; j++)
          score += getLeaf(trees[tindex+j], features[iIndex+i])->threshold;
    }
    sum += score;
    if(printScores) {
      fprintf(fp_log, "Thread %ld:%f\n", tid, sum);
    }
  }
  //fprintf(fp_log, "Thread %ld's score=%f\n", tid, sum);
  //fprintf(fp_log, "Thread %ld done.\n", tid);
  
  //exit thread and pass back sum
  thread_sum[tid] = sum;
  pthread_exit((void*) t);
}
  void printLongResults(const MatrixType& matrix, IterationType& iter, const SolverOptions& options)
  {
    const double elapsed = getTime() - startTime;
    std::cout.precision(5);
    std::cout.setf(std::ios::fixed);
    std::cout << "Library: desola" << std::endl;
    std::cout << "Matrix: " << getLeaf(options.getFile()) << std::endl;
    std::cout << "Matrix Size: " << num_cols(matrix) << std::endl;
    std::cout << "Compiler: " << getCompiler() << std::endl;
    std::cout << "Code Caching: " << getStatus(configManager.codeCachingEnabled()) << std::endl;
    std::cout << "Loop Fusion: " << getStatus(configManager.loopFusionEnabled()) << std::endl;
    std::cout << "Array Contraction: " << getStatus(configManager.arrayContractionEnabled()) << std::endl;
    std::cout << "Iterations: " << iter.iterations() << std::endl;
    std::cout << "Liveness Analysis: " << getStatus(configManager.livenessAnalysisEnabled()) << std::endl;
    std::cout << "Time per Iteration: " << elapsed / iter.iterations() << " seconds" << std::endl;
    std::cout << "Compile Time: " << statsCollector.getCompileTime() << " seconds" << std::endl;
    std::cout << "Compile Count: " << statsCollector.getCompileCount() << std::endl;
    std::cout << "Total Time: " << elapsed << " seconds" << std::endl;
    std::cout << "FLOPs: " << statsCollector.getFlops() << std::endl;
    std::cout << "High-Level Fusion: " << getStatus(configManager.highLevelFusionEnabled()) << std::endl;
    std::cout << "Single For-Loop Sparse Iteration: " << getStatus(configManager.singleForLoopSparseIterationEnabled()) << std::endl;
    std::cout << "Sparse Row Length Specialisation: " << getStatus(configManager.sparseSpecialisationEnabled()) << std::endl;

    if (options.useSparse())
      std::cout << "NNZ: " << nnz(matrix) << std::endl;

    if (configManager.livenessAnalysisEnabled())
      std::cout << std::endl << "Warning: FLOPs figure may be misleading with liveness analysis enabled." << std::endl;
  }
  void printShortResults(const MatrixType& matrix, IterationType& iter, const SolverOptions& options)
  {
    const double elapsed = getTime() - startTime;
    const char d = ':';

    std::cout.precision(5);
    std::cout.setf(std::ios::fixed);
    std::cout << d;
    std::cout << "lib=desola" << d;
    std::cout << "mat=" << getLeaf(options.getFile()) << d;
    std::cout << "mat_n=" << num_cols(matrix) << d;
    std::cout << "compiler=" << getCompiler() << d;
    std::cout << "code_cache=" << getStatus(configManager.codeCachingEnabled()) << d;
    std::cout << "fusion=" << getStatus(configManager.loopFusionEnabled()) << d;
    std::cout << "contraction=" << getStatus(configManager.arrayContractionEnabled()) << d;
    std::cout << "liveness=" << getStatus(configManager.livenessAnalysisEnabled()) << d;
    std::cout << "iterations=" << iter.iterations() << d;
    std::cout << "compile_time=" << statsCollector.getCompileTime() << d;
    std::cout << "compile_count=" << statsCollector.getCompileCount() << d;
    std::cout << "total_time=" << elapsed << d;
    std::cout << "flop=" << statsCollector.getFlops() << d;
    std::cout << "high_level_fusion=" << getStatus(configManager.highLevelFusionEnabled()) << d;
    std::cout << "single_for_loop_sparse=" << getStatus(configManager.singleForLoopSparseIterationEnabled()) << d;
    std::cout << "specialise_sparse=" << getStatus(configManager.sparseSpecialisationEnabled()) << d;

    if (options.useSparse())
      std::cout << "nnz=" << nnz(matrix) << d;

    std::cout << std::endl;
  }
Function* getFunction(Tree *ft, char *name, size_t nameLen) {
    Tree *leaf = getLeaf(ft, name, nameLen);
    if (leaf != NULL) {
        return leaf->data;
    }
    return NULL;
}
Example #7
0
bool
CirCut::containGateId(unsigned id) const {
	// can use binary search as well
	// cut size is small so linear search is OK
	for(unsigned i=0, n=size(); i<n; ++i)
		if(getLeaf(i) == id) return true;
	return false;
}
Example #8
0
VarTree::IteratorVisible VarTree::getItem( int index )
{
   Iterator it =
        m_flat ? getLeaf( index + 1 )
               : getVisibleItem( index + 1 );

   return IteratorVisible( it, this );
}
Example #9
0
bool
CirCut::operator == (const CirCut& cut) const {
   if(getSign() != cut.getSign()) return false;
   if(size() != cut.size()) return false;
   for(unsigned i=0, n=size(); i<n; ++i){
      if(getLeaf(i) != cut.getLeaf(i)) return false;
   }
   return true;
}
Tag* AddressSpace::getTag( const String &fullPath )
{
	try
	{
		return getLeaf( fullPath );
	}
	catch( frl::Exception& ){}
	return getBranch( fullPath );
}
const Waypoint* ChartElemNavaids::getNavaid(const QString& id, Waypoint::WptType type) const
{
    if (id.isEmpty()) return 0;
    QString leaf_id = getLeafID(id, type);
    const TreeBase* leaf = getLeaf(leaf_id);

    if (!leaf) return 0;
    //MYASSERT(leaf->inherits("ChartElemNavaid"));
    return ((ChartElemNavaid*)leaf)->getNavaid();
}
Example #12
0
Heap*
Heap::getLeaf(Heap* currPos)
{
	Heap* leaf=NULL;
	if(currPos->left==NULL && currPos->right==NULL)
	{
		return currPos;
	}
	if(currPos->left!=NULL)
	{
		leaf=getLeaf(currPos->left);
		return leaf;
	}
	if(currPos->right!=NULL)
	{
		leaf=getLeaf(currPos->right);
		return leaf;
	}
	return leaf;
}
Status addCoreFunction(Tree *ft, char *name, size_t nameLen, char* (*function)(List*)) {
    Tree* leaf = getLeaf(ft, name, nameLen);
    
    Function* coreFunc = calloc(FUNCTION_SIZE, 1);
    coreFunc->type = CORE;
    coreFunc->version.core.function = function;
    
    leaf->data = function;
    
    return OK;
}
Status addScriptFunction(Tree *ft, char *name, size_t nameLen, char *function, size_t functionLen) {
    Tree *leaf = getLeaf(ft, name, nameLen);

    Function* scriptFunc = calloc(FUNCTION_SIZE, 1);
    scriptFunc->type = SCRIPT;
    scriptFunc->version.script.script = function;
    scriptFunc->version.script.len = functionLen;

    leaf->data = scriptFunc;
    
    return OK;
}
void SchedGraphCommon::eraseIncomingEdges(SchedGraphNodeCommon* node, 
					  bool addDummyEdges) {
  // Delete and disconnect all in-edges for the node
  for (SchedGraphNodeCommon::iterator I = node->beginInEdges();
       I != node->endInEdges(); ++I) {
    SchedGraphNodeCommon* srcNode = (*I)->getSrc();
    srcNode->removeOutEdge(*I);
    delete *I;
    
    if (addDummyEdges && srcNode != getRoot() &&
	srcNode->beginOutEdges() == srcNode->endOutEdges()) { 
      
      // srcNode has no more out edges, so add an edge to dummy EXIT node
      assert(node != getLeaf() && "Adding edge that was just removed?");
      (void) new SchedGraphEdge(srcNode, getLeaf(),
				SchedGraphEdge::CtrlDep, 
				SchedGraphEdge::NonDataDep, 0);
    }
  }
  
  node->inEdges.clear();
}
Example #16
0
inline std::vector<TID> BTree<KeyType, KeyComparator>::lookupRange(KeyType begin, KeyType end) {
  KeyType left = begin;
  KeyType right = end;

  /* if given end-limit is lower than begin, we need to swap both borders*/
  if (smallerComparator(end, begin)) {
    left = end;
    right = begin;
  }

  std::vector<TID> lookupSet;
  Leaf<KeyType, KeyComparator> leftLeaf = getLeaf(left);
  int position = EntriesHelper::findPosition<KeyType, KeyComparator, TID>(
      leftLeaf.entries, left,
      0, leftLeaf.header.keyCount,
      smallerComparator);
  BufferFrame * currentFrame = nullptr;
  while (true) {
    while (position < leftLeaf.header.keyCount) {
      Entry<KeyType, TID> entry = leftLeaf.entries[position];
      if (begin <= entry.key && entry.key <= end){
        lookupSet.push_back(entry.value);
      }
      position++;
    }
    if (position == leftLeaf.header.keyCount) {
      //reached end of leaf and need to check the next leaf
      uint64_t nextLeaf = leftLeaf.header.nextLeafPageId;
      if (nextLeaf != LeafHeader::INVALID_PAGE_ID) {
        // set next leaf and reset position to first entry
        if (currentFrame != nullptr){
          bufferManager.unfixPage(*currentFrame, false);
          currentFrame = nullptr;
        }
        currentFrame = &bufferManager.fixPage(this->segmentId, nextLeaf, true);
        leftLeaf = * reinterpret_cast<Leaf<KeyType, KeyComparator> *>(currentFrame->getData());
        position = 0;
      } else {
        // end of leaves reached, we cannot look further so we return the set
        break;
      }
    } else {
      break;
    }
  }
  if (currentFrame != nullptr){
    bufferManager.unfixPage(*currentFrame, false);
  }
  return lookupSet;
}
  void printLongResults(const MatrixType& matrix, IterationType& iter, const SolverOptions& options)
  {
    const double elapsed = getTime() - startTime;
    std::cout.precision(5);
    std::cout.setf(std::ios::fixed);
    std::cout << "Library: MTL" << std::endl;
    std::cout << "Matrix: " << getLeaf(options.getFile()) << std::endl;
    std::cout << "Matrix Size: " << num_cols(matrix) << std::endl;
    std::cout << "Iterations: " << iter.iterations() << std::endl;
    std::cout << "Time per Iteration: " << elapsed / iter.iterations() << " seconds" << std::endl;
    std::cout << "Total Time: " << elapsed << " seconds" << std::endl;

    if (options.useSparse())
      std::cout << "NNZ: " << nnz(matrix) << std::endl;
  }
Example #18
0
//--------------------------------------------------------------
// destructor
Colonization::~Colonization()
{
  for (int i = 0; i < m_branches.length(); i++)
  {
    Branch* branch = getBranch(i);
    delete branch;
  }
  m_branches.removeAll();

  for (int i = 0; i < m_leaves.length(); i++)
  {
    Leaf* leaf = getLeaf(i);
    delete leaf;
  }
  m_leaves.removeAll();
}
Example #19
0
    TID N::getAnyChildTid(const N *n, bool &needRestart) {
        const N *nextNode = n;

        while (true) {
            const N *node = nextNode;
            auto v = node->readLockOrRestart(needRestart);
            if (needRestart) return 0;

            nextNode = getAnyChild(node);
            node->readUnlockOrRestart(v, needRestart);
            if (needRestart) return 0;

            assert(nextNode != nullptr);
            if (isLeaf(nextNode)) {
                return getLeaf(nextNode);
            }
        }
    }
Example #20
0
VarTree::Iterator VarTree::getItemFromSlider()
{
    // a simple (int)(...) causes rounding errors !
#ifdef _MSC_VER
#       define lrint (int)
#endif
    VarPercent &rVarPos = getPositionVar();
    double percentage = rVarPos.get();

    int indexMax = m_flat ? (countLeafs() - 1)
                          : (visibleItems() - 1);

    int index = lrint( (1.0 - percentage)*(double)indexMax );

    Iterator it_first = m_flat ? getLeaf( index + 1 )
                               : getVisibleItem( index + 1 );
    return it_first;
}
  void printShortResults(const MatrixType& matrix, IterationType& iter, const SolverOptions& options)
  {
    const double elapsed = getTime() - startTime;
    const char d = ':';

    std::cout.precision(5);
    std::cout.setf(std::ios::fixed);
    std::cout << d;
    std::cout << "lib=mtl" << d;
    std::cout << "mat=" << getLeaf(options.getFile()) << d;
    std::cout << "mat_n=" << num_cols(matrix) << d;
    std::cout << "iterations=" << iter.iterations() << d;
    std::cout << "total_time=" << elapsed << d;

    if (options.useSparse())
      std::cout << "nnz=" << nnz(matrix) << d;

    std::cout << std::endl;
  }
Example #22
0
template<typename PointT, typename LeafT, typename OctreeT> bool
pcl::octree::OctreePointCloudSearch<PointT, LeafT, OctreeT>::voxelSearch (
    const PointT& point, std::vector<int>& pointIdx_data)
{
  OctreeKey key;
  bool b_success = false;

  // generate key
  genOctreeKeyforPoint (point, key);

  LeafT* leaf = getLeaf (key);

  if (leaf)
  {
    leaf->getData (pointIdx_data);
    b_success = true;
  }

  return (b_success);
}
Example #23
0
/**
 * Index lookup for a key. Returns the rid if found, else -1.
 * Assuming the index on a candidate key.
 */
int BPlusTree::lookUp(int key) {
    BufferManager *bm = BufferManager::getInstance(dbName);

    int height = 0;
    //TreeNode **trace = (TreeNode **)malloc(10);
    TreeNode **trace = new TreeNode *[10];
    for (int i = 0; i < 10; i++)
        trace[i] = NULL;

    TreeNode *leafNode = getLeaf(key, trace, &height);
    int nofPairs = leafNode->getNoPairs();
    int ithKey = readInt(leafNode->getBuffPage(),
            2 * SIZE_INT + PTR_SIZE);
    int keyCount;
    int rid;
    cout << nofPairs << endl;
    for (keyCount = 0; keyCount < nofPairs && key > ithKey; keyCount++) {

        //cout<<"in lookup for insert ithkey "<<ithKey<<endl;
        ithKey = readInt(leafNode->getBuffPage(),
                2 * SIZE_INT + (keyCount + 1) * PAIR_SIZE + PTR_SIZE);
        //cout<<"loop "<<keyCount<<endl;
    }
    rid = readInt(leafNode->getBuffPage(),
            2 * SIZE_INT + (keyCount) * PAIR_SIZE);
    cout << "key " << key << "rid " << rid << endl;
    //unpin the trace 
    for (int level = 1; trace[level] != NULL; level++) {
        bm->unpinPage(trace[level]->getBuffPage(), false);
        delete trace[level];
    }
    free(trace);
    if (nofPairs == 0)
        return -1;


    if (key == ithKey && keyCount < nofPairs)
        return rid;
    else
        return -1;
}
Example #24
0
void
CirCut::genCutFunc()
{
   CirGate* gate;
   // set supports
   CirGate::incDfsFlag();
   for(unsigned i=0, n=size(); i<n; ++i){
      gate = cirMgr->getGateById(getLeaf(i));
      if(gate->getFecPhase())
         gate->setGateFunc(~bddMgr->getSupport(i+1));
      else
         gate->setGateFunc( bddMgr->getSupport(i+1));
   }
   // generate function
   gate = cirMgr->getGateById(getRoot());
   gate->genGateFunc();
   if(gate->getFecPhase())
      setFunc(~gate->getGateFunc());
   else
      setFunc( gate->getGateFunc());
}
Example #25
0
/**
 * Delete an entry from the index. For now, assume the index
 * to be on a candidate key.
 */
void BPlusTree::deleteEntry(int key) {

    BufferManager *bm = BufferManager::getInstance(dbName);
    int height;
    //TreeNode **trace = (TreeNode **)malloc(10);

    TreeNode **trace = new TreeNode *[10];
    for (int i = 0; i < 10; i++)
        trace[i] = NULL;

    TreeNode *leafNode = getLeaf(key, trace, &height);

    int rid = lookUpWithoutUnpin(key, leafNode);

    if (rid == -1)
        cout << "key doesnot exists" << endl;
    else {

        recursiveDeleteEntry(leafNode, key, rid, trace, height);
    }
}
void SchedGraphCommon::eraseOutgoingEdges(SchedGraphNodeCommon* node, 
					  bool addDummyEdges) {
  // Delete and disconnect all out-edges for the node
  for (SchedGraphNodeCommon::iterator I = node->beginOutEdges();
       I != node->endOutEdges(); ++I) {
    SchedGraphNodeCommon* sinkNode = (*I)->getSink();
    sinkNode->removeInEdge(*I);
    delete *I;
    
    if (addDummyEdges &&
	sinkNode != getLeaf() &&
	sinkNode->beginInEdges() == sinkNode->endInEdges()) {
      
      //sinkNode has no more in edges, so add an edge from dummy ENTRY node
      assert(node != getRoot() && "Adding edge that was just removed?");
      (void) new SchedGraphEdge(getRoot(), sinkNode,
				SchedGraphEdge::CtrlDep, 
				SchedGraphEdge::NonDataDep, 0);
    }
  }
  
  node->outEdges.clear();
}
Example #27
0
/*
Function: cvSeqLabel 
Description: Implements the sequential labeling algorithm on binary images 
             to extract the connected components.
Dependencies: Uses the OpenCV library
Arguments: in - binary image containing background (0) and foreground (!0) pixels
           out - image containing the labels (0 - background, 1-255 connected objects' labels )

Limitations: Allows only 255 labels. Assumes output image is clear.
Author: Alex 03/01/2006
*/
int cvSeqLabel( IplImage *in, IplImage *out, IplImage *tmp)
{
	int i, j, label = 0, minlabel, originalb, originalc, equiv_array[MAX_LABELS];
	int width, height, stride;
	unsigned char *input, *output;
	int *temp;
	unsigned char *pai, *pbi, *pci, *pdi;
	int *pao, *pbo, *pco, *pdo;
	
	memset( equiv_array, 0, sizeof(int)*MAX_LABELS );

	input=(unsigned char*)in->imageData;
	output=(unsigned char*)out->imageData;
	temp=(int*)tmp->imageData;
		
	//fprintf(stdout, "initial temp[]=%d\n", temp[0]);
	
	width = out->width;
	height = out->height;
	stride = tmp->widthStep/sizeof(int);
	
	
	// first pixel
	if(input[0])
		temp[0] = ++label;

	//first line
	for(i = 1; i < width; i++)
	{
		if(input[i])
		{
			if(input[i-1])   // test left neighbor
			{
				temp[i] = temp[i-1];  //preserve connected label
			}
			else
			{
				if(label == MAX_LABELS-1)
				         return MAX_LABELS-1; // end of free labels
				temp[i] = ++label; //new label
			}
		}
	}

	pai = input + stride;	pci = input;
	pao = temp + stride;	pco = temp;
	

	//remaining lines
	for(i = 1; i < height; i++)
	{
        //first column
		if(*pai)
		{
			if(*pci) //test up neighbor
			{
				*pao = *pco; //preserve connected label
			}
			else
			{
				//label+=4;
				if(label == MAX_LABELS - 1)
				         return -2;
				*pao = ++label; //new label
			}
		}
		pbi = pai++; pbo = pao++; pdi = pci++; pdo = pco++;

		// remaining columns
		for(j = 1; j < width; j++)
		{
			if(*pai)
			{
				if(*pbi)
				{
					*pao = *pbo;
					if(*pci)				// resolving equivalences
						if( *pco != *pbo )
						{
							//if (originalb==-1)
							//	return -1;
							if( originalb = getLeaf(*pbo, equiv_array) )
							{
								//if (originalc = getLeaf(*pco, equiv_array))
								//	return -1;
								if( originalc = getLeaf(*pco, equiv_array) )
								{
									if( originalc != originalb)
                                        equiv_array[originalc-1] = originalb;
								}
								else  // c is leaf
								{
									if(*pco != originalb)
										equiv_array[*pco-1] = originalb;
								}
								*pco = originalb;
							}
							else // b is leaf
							{
								//originalc = getLeaf(*pco, equiv_array);
								//if (originalc==-1)
								//	return -1;
								if( originalc = getLeaf(*pco, equiv_array) )
								{
									if(originalc != *pbo) {
										equiv_array[originalc-1] = *pbo;
                                  }
								}
								else  // c is leaf
								{
									equiv_array[*pco-1] = *pbo;
								}
								*pco = *pbo;
							}
						}
				}
				else if(*pdi)
				{
					*pao = *pdo;
				}
				else if(*pci)
				{
					*pao = *pco;
				}
				else
				{
					//label+=4;
					if(label == MAX_LABELS-1)
				         return -3;
					*pao = ++label;  // new label
//					if(label > MAX_LABELS)
//						return -1;  //ran out of labels
				}
			}
			pai++; pbi++; pci++; pdi++; pao++; pbo++; pco++; pdo++;
		}
	}
	
	// fusing labels
	for( i = 1; i <= label; i++ )
	{
		minlabel = getLeaf(i, equiv_array);
		//if (minlabel==-1)
		//	return -1;
		if( minlabel )
		{
			equiv_array[i-1] = minlabel;
		}
	}
	
	// processing image
	for( i = 0; i < height; i++ )
	{
		for( j = 0; j < width; j++ )
		{
			if( temp[i*stride+j] )
			{
				
				if( equiv_array[ temp[i*stride+j] -1 ] )
				{
					temp[i*stride+j] = equiv_array[ temp[i*stride+j] -1 ];
				}
			}
		}
	}
	
	//convert from label image (integer) to output image (unsigned char)
	for( i = 0; i < height; i++ )
		for( j = 0; j < width; j++ )
			output[i*stride+j]  = (unsigned char)temp[i*stride+j];
			

	return label;						
}
Example #28
0
void Vegetation_Bgc::delta() {

	/// some environment variables
	double co2 = ed->m_atms.co2;
	double par = ed->m_a2l.par;
	//double pet = ed->m_l2a.pet;
	double eet = ed->m_l2a.eet;

	double tempunnormleaf;
	tempunnormleaf = getUnnormleaf(ed->prveetmx, eet, tmp_vegs.unnormleaf);
	del_vegs.unnormleaf = tempunnormleaf - tmp_vegs.unnormleaf;
	bd->m_vegd.leaf = getLeaf(tempunnormleaf);

	if (bd->cd->vegtype <= 0) {
		double alleaf = bgcpar.leafmxc / (1.0 + bgcpar.kleafc * exp(bgcpar.cov
				* tmp_vegs.c));
		bd->m_vegd.foliage = alleaf / bgcpar.leafmxc;
		//  		bd->m_vegd.lai = bgcpar.sla *alleaf * bd->m_vegd.leaf;
	} else {
		bd->m_vegd.foliage = getFoliage();
	}

	bd->m_vegd.lai = bgcpar.sla * bgcpar.leafmxc * bd->m_vegd.foliage
			* bd->m_vegd.leaf;
	bd->m_vegd.fpc = 1.0 - exp(-0.5 * bd->m_vegd.lai);

	del_a2v.ingpp = getGPP(co2, par, bd->m_vegd.leaf, bd->m_vegd.foliage,
			bd->m_vegd.ftemp, bd->m_vegd.gv);

	del_soi2v.innuptake = sb->getNuptake(bd->m_vegd.foliage, bd->m_vegd.raq10,
			bgcpar.kn1, calpar.nmax);
	if (del_soi2v.innuptake < 0.0) {
		del_soi2v.innuptake = 0.0;
	}

	del_v2soi.ltrfalc = calpar.cfall * tmp_vegs.c;
	if (del_v2soi.ltrfalc < 0.)
		del_v2soi.ltrfalc = 0.;
	del_v2soi.ltrfaln = calpar.nfall * tmp_vegs.strn;
	if (del_v2soi.ltrfaln < 0.)
		del_v2soi.ltrfaln = 0.;

	bd->m_vegd.kr = getKr(tmp_vegs.c);
	del_v2a.rm = getRm(tmp_vegs.c, bd->m_vegd.raq10, bd->m_vegd.kr);
	del_a2v.innpp = del_a2v.ingpp - del_v2a.rm;

	del_v2a.rg = 0.;
	if (del_a2v.innpp > 0.0) {
		del_v2a.rg = 0.25 * del_a2v.innpp;
		del_a2v.innpp *= 0.75;
	}

	/// need to put the following lines here
	/// since in the deltanfeed del_a2v.npp is used
	del_soi2v.nuptake = del_soi2v.innuptake;
	del_soi2v.suptake = del_soi2v.nuptake;
	del_soi2v.luptake = 0.0;
	del_a2v.gpp = del_a2v.ingpp;
	del_a2v.npp = del_a2v.innpp;
	del_v2v.nmobil = 0.0;
	del_v2v.nresorb = 0.0;

}
void QuadSynopsis::buildGraph(int lvl,int idx,vector<int> low, vector<int> high,string & graph)
{
	stringstream ss;
	int leaf_offset;
	ss<<"id"<<id<<"node"<<lvl<<"idx"<<idx;


	string fillcolor ="white";
	string style = "filled";
	bool isClock = false;
	bool isCurr = false;
	if(lvl == prev_victim.lvl && idx == prev_victim.idx)
	{
		//fillcolor="#B4CDCD"; // awlays keep track of the clock //
		isClock = true;
	}

	//isClock = false;

	if(lvl == curr_leaf.lvl && idx == curr_leaf.idx)
		{
			//fillcolor="#B4CDCD"; // awlays keep track of the clock //
			isCurr = true;
		}

	if(isLeaf(lvl,idx))
	{


		bool val = getLeaf(lvl,idx);

		if(val)
			fillcolor="green";
		else
			fillcolor="tomato";

		//if(isClock)
		//					fillcolor="#B4CDCD";
		if(isCurr)
			fillcolor="yellow";


		if(low[0]<0)
		{
			fillcolor = "gray";
			ss<<"[style="<<style<<",fillcolor=\""<<fillcolor<<"\",color=black,label = \"";
					ss<<"[ UNUSED ] ";
					unused++;

		}
		else
		{
			int used_val = getUsed(lvl,getLeafOffset(lvl,idx));

			ss<<"[style="<<style<<",fillcolor=\""<<fillcolor<<"\",color=black,label = \"";
			ss<<"[ "<<getVector(low)<<","<<getVector(high)<<"]";// used ="<<used_val;
			//if(val)
			//	ss<<" [HAZ]";
			//if(isClock)
			//					ss<<", CLOCK";
			if(low.size() ==1)
			{
				int len = high[0]-low[0]+1;
				ss<<", len = "<<len;
			}
		}


		ss<<"\"];\n";
		graph+= ss.str();

	}
	else //we need the kids too
	{

		vector< vector<int> > lowb= getChildrenLowerBounds(low,high);
		vector< vector<int> > highb = getChildrenUpperBounds(low,high);

		int first_child = getFirstChild(lvl,idx);
		//if(isClock)
		//			fillcolor="#B4CDCD";
		if(isCurr)
				fillcolor="yellow";
		ss<<"[style="<<style<<",fillcolor=\""<<fillcolor<<"\",label = \"";
		ss<<"[ "<<getVector(low)<<","<<getVector(high)<<"]";
		//if(isClock)
			//		ss<<", CLOCK";
		ss<<"\"];\n";
		//connect it to its kids :))
		//"node1" -> "node2";

		for(int i=0;i<lowb.size();i++)
                ss<<"\"id"<<id<<"node"<<lvl<<"idx"<<idx<<"\" -> \"id"<<id<<"node"<<lvl+1<<"idx"<<first_child+i<<"\";\n";

		graph+= ss.str();

		for(int i=0;i<lowb.size();i++)

			buildGraph(lvl+1,first_child+i,lowb[i],highb[i],graph);



	}


}
Example #30
0
int main(int argc, char** args) {
  if(!isPresentCL(argc, args, (char*) "-ensemble") ||
     !isPresentCL(argc, args, (char*) "-instances") ||
     !isPresentCL(argc, args, (char*) "-maxLeaves")) {
    return -1;
  }

  char* configFile = getValueCL(argc, args, (char*) "-ensemble");
  char* featureFile = getValueCL(argc, args, (char*) "-instances");
  int maxNumberOfLeaves = atoi(getValueCL(argc, args, (char*) "-maxLeaves"));
  int printScores = isPresentCL(argc, args, (char*) "-print");

  // Read ensemble
  FILE *fp = fopen(configFile, "r");
  int nbTrees;
  fscanf(fp, "%d", &nbTrees);

  // Array of pointers to tree roots, one per tree in the ensemble
  StructPlus** trees = (StructPlus**) malloc(nbTrees * sizeof(StructPlus*));
  int tindex = 0;

  // Number of nodes in a tree does not exceed (maxLeaves * 2)
  int maxTreeSize = 2 * maxNumberOfLeaves;
  long treeSize;

  for(tindex = 0; tindex < nbTrees; tindex++) {
    fscanf(fp, "%ld", &treeSize);

    trees[tindex] = createNodes(maxTreeSize);

    char text[20];
    long line = 0;
    fscanf(fp, "%s", text);
    while(strcmp(text, "end") != 0) {
      long id;
      fscanf(fp, "%ld", &id);

      // A "root" node contains a feature id and a threshold
      if(strcmp(text, "root") == 0) {
        int fid;
        float threshold;
        fscanf(fp, "%d %f", &fid, &threshold);
        setRoot(trees[tindex], id, fid, threshold);
      } else if(strcmp(text, "node") == 0) {
        int fid;
        long pid;
        float threshold;
        int leftChild = 0;
        // Read Id of the parent node, feature id, subtree (left or right),
        // and threshold
        fscanf(fp, "%ld %d %d %f", &pid, &fid, &leftChild, &threshold);

        // Find the parent node, based in parent id
        int parentIndex = 0;
        for(parentIndex = 0; parentIndex < maxTreeSize; parentIndex++) {
          if(trees[tindex][parentIndex].id == pid) {
            break;
          }
        }
        // Add the new node
        if(trees[tindex][parentIndex].fid >= 0) {
          addNode(trees[tindex], parentIndex, line, id, leftChild, fid, threshold);
        }
      } else if(strcmp(text, "leaf") == 0) {
        long pid;
        int leftChild = 0;
        float value;
        fscanf(fp, "%ld %d %f", &pid, &leftChild, &value);

        int parentIndex = 0;
        for(parentIndex = 0; parentIndex < maxTreeSize; parentIndex++) {
          if(trees[tindex][parentIndex].id == pid) {
            break;
          }
        }
        if(trees[tindex][parentIndex].fid >= 0) {
          addNode(trees[tindex], parentIndex, line, id, leftChild, 0, value);
        }
      }
      line++;
      fscanf(fp, "%s", text);
    }
    // Re-organize tree memory layout
    trees[tindex] = compress(trees[tindex]);
  }
  fclose(fp);

  // Read instances (SVM Light format
  int numberOfFeatures = 0;
  int numberOfInstances = 0;

  fp = fopen(featureFile, "r");
  fscanf(fp, "%d %d", &numberOfInstances, &numberOfFeatures);
  int divisibleNumberOfInstances = numberOfInstances;
  while(divisibleNumberOfInstances % F !=0)
    divisibleNumberOfInstances++;
  float** features = (float**) malloc(divisibleNumberOfInstances * sizeof(float*));
  int i = 0; int j=0;
  for(i = 0; i < divisibleNumberOfInstances; i++) {
    features[i] = (float*) malloc(numberOfFeatures * sizeof(float));
  }

  float fvalue;
  int fIndex = 0, iIndex = 0;
  int ignore;
  char text[20];
  char comment[1000];
  for(iIndex = 0; iIndex < numberOfInstances; iIndex++) {
    fscanf(fp, "%d %[^:]:%d", &ignore, text, &ignore);
    for(fIndex = 0; fIndex < numberOfFeatures; fIndex++) {
      fscanf(fp, "%[^:]:%f", text, &fvalue);
      features[iIndex][fIndex] = fvalue;
    }
    fscanf(fp, "%[^\n]", comment);
  }
  // Compute scores for instances using the ensemble and
  // measure elapsed time
  float sum = 0; // Dummy value just so gcc wouldn't optimize the loop out
  float score;
  struct timeval start, end;

  int divide_number, remainder;
  divide_number = nbTrees / T;
  remainder = nbTrees % T;
  gettimeofday(&start, NULL);
  
  //SOT
  for (tindex = 0; tindex < nbTrees - remainder; tindex+=T) 
  {
    score = 0;
    for (iIndex = 0; iIndex < numberOfInstances; iIndex+=F)
      for (j=0; j<T; j++)
        for (i=0; i<F; i++)
          score += getLeaf(trees[tindex+j], features[iIndex+i])->threshold;
    if (printScores) 
      printf("%f\n", score);
    sum += score;
  }
  
  //deal with remain trees
  score = 0;
  for (iIndex = 0; iIndex < numberOfInstances; iIndex+=F)
    for (j=0; j<remainder; j++)
      for (i=0; i<F; i++)
        score += getLeaf(trees[nbTrees - remainder+j], features[iIndex+i])->threshold;
  if(printScores)
    printf("%f\n", score);
  sum += score;
  
  gettimeofday(&end, NULL);

  printf("Time per instance (ns): %5.2f\n",
         (((end.tv_sec * 1000000 + end.tv_usec) -
           (start.tv_sec * 1000000 + start.tv_usec))*1000/((float) numberOfInstances)));
  printf("Ignore this number: %f\n", sum);

  // Free used memory
  for(tindex = 0; tindex < nbTrees; tindex++) {
    destroyTree(trees[tindex]);
  }
  free(trees);
  for(i = 0; i < numberOfInstances; i++) {
    free(features[i]);
  }
  free(features);
  fclose(fp);
  return 0;
}