Ejemplo n.º 1
0
/*
 * Reads the network from the given file into the global adjacency list unordered map.
 */
void load_network(std::string filename) {
	GraphSize source, target, max, cur_size;
	NodePair nodes;
	Node *node, *srcnode, *tarnode;

	// load file and iterate through each line of input
	std::ifstream infile(filename);
	if ( infile.is_open() ) {
		while ( infile >> source >> target ) { 
			// check for resize
			if ( source >= nodevec.size() || target >= nodevec.size() ) {
				max = std::max( source, target );
				cur_size = nodevec.size();
				nodevec.resize( max + 1 );
				while ( cur_size <= max ) {
					nodevec[cur_size++] = new Node();
				}
			}

			// get source node
			srcnode = nodevec[source];
			srcnode->setId( source );

			// get target node
			tarnode = nodevec[target];
			tarnode->setId( target );

			// add new undirected edge
			srcnode->addEdge( tarnode );
			tarnode->addEdge( srcnode );
		}
	}
	infile.close( );
}
Ejemplo n.º 2
0
void cGraphMaster::internal_sort(NodeVec& tree) {
  sort(tree.begin(), tree.end());
  for (NodeVec::iterator it = tree.begin(); it != tree.end(); ++it) {
    internal_sort(it->same_childs);
    internal_sort(it->diff_childs);
  }
}
Ejemplo n.º 3
0
void PseudoBooleanProcessor::learn(const NodeVec& assertions){
  NodeVec::const_iterator ci, cend;
  ci = assertions.begin(); cend=assertions.end();
  for(; ci != cend; ++ci ){
    learn(*ci);
  }
}
Ejemplo n.º 4
0
int main()
{
	NodeVec kmax;
	kmax.reserve(600);
	int k = 500;
	GenData();
	GetkMax(kmax, k);
	for_each(kmax.begin(), kmax.end(), print); //输出是按照堆的顺序输出,如果要有序的话,可以先sort_heap一下
    cout<<endl;
	return 0;
}
Ejemplo n.º 5
0
int main ( int argc , char** argv ) {
	double start, end;

	// get cmdline args
	std::string input_file = argv[1];
	std::string output_file = argv[2];
	int num_steps = atoi( argv[3] );

	// check for valid input file
	if ( !utils::fexists( input_file ) ) { 
		printf( "Error: Input file does not exist.\n" );
		return 1;
	}

	// initialize adjacency list vector hash
	printf( "Loading network edges from %s\n", input_file.c_str() );
	start = omp_get_wtime();
	load_network( input_file );
	end = omp_get_wtime();
	printf( "Time to read input file = %lf seconds\n", end - start );
	
	// compute the normalized credit after numSteps
	printf("\nComputing the Credit Values for %d Rounds:\n", num_steps);
	CreditVec C( nodevec.size(), 1 ); // initialize credit at t=0 to 1 for each node
	CreditVec C_( nodevec.size(), 0 );
	std::vector<CreditVec> updates( num_steps );

	for (int i=0; i<num_steps; ++i) {
		printf("round %d = ", i+1);

		start = omp_get_wtime();
		credit_update(C, C_);
		end = omp_get_wtime();
		printf( "%f seconds\n", end - start );

		// store credit update before overwriting timestep t
		updates[i] = C_;

		C = C_; // C(t+1) becomes C(t) for next iteration
	}

	// output credit value results after the final step
	printf( "\nOutputting Network and Random Walk Data to %s\n", output_file.c_str() );
	write_output( output_file, updates );

	// free heap memory
	for ( auto& node: nodevec ) {
		delete node;
	}

	return 0 ;
}
Ejemplo n.º 6
0
Archivo: MLGDao.cpp Proyecto: caomw/mld
bool MLGDao::verticalCopyHLinks( const Node& source,
                                 const Node& target,
                                 Direction dir,
                                 bool safe,
                                 const ObjectsPtr& subset,
                                 const WeightMergerFunc& f )
{
    if( safe ) {  // Check source and target affiliation
        if( !checkAffiliation(source.id(), target.id(), dir) ) {
            return false;
        }
    }

    // Get source's neighbors
    ObjectsPtr srcNeighbors;
    if( subset )
        srcNeighbors = subset; // Temporary borrow
    else
        srcNeighbors.reset(m_g->Neighbors(source.id(), hlinkType(), Any));

    ObjectsIt it(srcNeighbors->Iterator());
    while( it->HasNext() ) {
        oid_t current = it->Next();
        NodeVec kin;
        if( dir == TOP )
            kin = getParentNodes(current);
        else
            kin = getChildNodes(current);

        if( kin.empty() ) {
            LOG(logERROR) << "MLGDao::verticalCopyHLinks: node as no parents";
            return false;
        }

        HLink currentLink = getHLink(source.id(), current);
        // For each child or parent
        for( Node& k: kin ) {
            HLink link = getHLink(target.id(), k.id());
            if( link.id() == Objects::InvalidOID ) {  // Top HLink doesn't exist
                addHLink(target, k, currentLink.weight());
            }
            else {  // Update top HLink with functor
                link.setWeight( f(link.weight(), currentLink.weight()) );
                if( !updateHLink(link) ) {
                    LOG(logERROR) << "MLGDao::verticalCopyHLinks: Failed to update top/bottom nodes HLINK";
                    return false;
                }
            }
        }
    }
    return true;
}
Ejemplo n.º 7
0
void PseudoBooleanProcessor::applyReplacements(NodeVec& assertions){
  for(size_t i=0, N=assertions.size(); i < N; ++i){
    Node assertion = assertions[i];
    Node res = applyReplacements(assertion);
    assertions[i] = res;
  }
}
Ejemplo n.º 8
0
void cGraphMaster::addNode(AIMLentry& entry, NodeType curr_type, NodeVec& tree, unsigned long rec, bool insert_ordered) {
  list<string>& curr_list = entry.getList(curr_type);
  string head = curr_list.front();
  curr_list.pop_front();
  bool last_tok = curr_list.empty();

  Node node;
  node.key = head;
  node.type = curr_type;

  for (NodeVec::iterator it = tree.begin(); it != tree.end(); ++it) {
    if (it->key == head) {
      if (last_tok) {
        if (curr_type == NODE_TOPIC) it->templ = entry.templ;
        else addNode(entry, nextNodeType(curr_type), it->diff_childs, rec+1);
      }
      else addNode(entry, curr_type, it->same_childs, rec+1);
      
      return;
    }
  }

  if (!last_tok) addNode(entry, curr_type, node.same_childs, rec+1);
  else {
    if (curr_type == NODE_TOPIC) { node.templ = entry.templ; gm_size++; }
    else addNode(entry, nextNodeType(curr_type), node.diff_childs, rec+1);
  }

  if (insert_ordered) tree.insert(lower_bound(tree.begin(), tree.end(), node), node);
  else tree.insert(tree.end(), node);
}
Ejemplo n.º 9
0
static void NoStateSort(NodeVecVec& nodeVecVec, std::vector<const Sprite*>& spriteVec)
{
    // no sorting, just copy sprites from nodeVecVec to spriteVec
    NodeVecVec::iterator vecVecIter = nodeVecVec.begin();
    NodeVecVec::iterator vecVecEnd = nodeVecVec.end();
    for(; vecVecIter != vecVecEnd; ++vecVecIter)
    {
        NodeVec* v = (*vecVecIter);
        NodeVec::iterator vecIter = v->begin();
        NodeVec::iterator vecEnd = v->end();
        for(; vecIter != vecEnd; ++vecIter)
        {
            const Sprite* sprite = (*vecIter)->sprite;
            if (sprite != s_screenSprite)
                spriteVec.push_back(sprite);
        }
    }
}
Ejemplo n.º 10
0
bool cGraphMaster::getMatch(InputIterator input, NodeType curr_type, const NodeVec& tree, MatcherStruct& ms, unsigned long rec) {
  // save head of input and advance iterator
  string input_front = *input;
  input++;
    
   //cout<<"tree.front().key="<<tree.front().key<<endl;

  _DBG_CODE(msg_dbg() << "[" << rec << "]getMatch(" << curr_type << ") HEAD: [" << input_front << "] last input?:" << boolalpha << input.isDone() << endl);
  
  /** FIRST WILDCARD: try to match the '_' wildcard **/
  if (tree.front().key == "_") {
    _DBG_CODE(msg_dbg() << "[" << rec << "]" << "Looking in '_'" << endl);
    if (getMatchWildcard(input, curr_type, tree.front(), ms, rec, input_front)) { if (ms.log) ms.logMatch("_", curr_type); return true; }
  }
  
  /** KEYS: if wildcard didn't matched, look for specific matching keys against current input_front **/
  _DBG_CODE(msg_dbg() << "[" << rec << "]" << "KEYS" << endl);
  Node tmp_node;
  tmp_node.key = input_front;
  NodeVec::const_iterator it = lower_bound(tree.begin(), tree.end(), tmp_node);
  // if there was a match
  if (it != tree.end() && it->key == input_front) {
    // if there are more tokens on input
    if (!input.isDone()) {
      // if I have something to match with, then look for a match
      if (!it->same_childs.empty()) {
        if (getMatch(input, curr_type, it->same_childs, ms, rec+1)) { if (ms.log) ms.logMatch(it->key, curr_type); return true; }
      }
    }
    // else, this is the last token
    else {
      // get the the next type of nodes to match if necessary
      list<string> match_list;
      if (curr_type != NODE_TOPIC && !it->diff_childs.empty()) ms.user.getMatchList(NodeType(curr_type+1), match_list);

      // if in previous situation check if there's a match deeper
      if (curr_type != NODE_TOPIC && !it->diff_childs.empty() &&
          getMatch(match_list, nextNodeType(curr_type), it->diff_childs, ms, rec+1))
      {
        if (ms.log) ms.logMatch(it->key, curr_type); return true;
      }
      // if I'm in the final type of nodes, it needs to be a leaf to have a match
      else if (curr_type == NODE_TOPIC && !it->templ.empty()) {
        ms.templ = it->templ;
        if (ms.log) ms.logMatch(it->key, curr_type);
        return true;
      }
    }
  }

  /** LAST WILDCARD: if above didn't matched repeat procedure for '_' **/
  if (tree.back().key == "*") {
    _DBG_CODE(msg_dbg() << "[" << rec << "]" << "Looking in '*'" << endl);
    if (getMatchWildcard(input, curr_type, tree.back(), ms, rec, input_front)) { if (ms.log) ms.logMatch("*", curr_type); return true; }
  }
  
  return false;
}
Ejemplo n.º 11
0
void GetkMax(NodeVec& rtv, int k)
{
	int i ;
	for( i = 0 ; i < k ; ++i) rtv.push_back(i);
	make_heap(rtv.begin(), rtv.end(), compare());
	while(i < MaxN)
	{
		if(compare()(i, rtv[0]))
		{
			pop_heap(rtv.begin(), rtv.end(), compare());
			rtv.pop_back();
			rtv.push_back(i);
			push_heap(rtv.begin(), rtv.end(), compare());
		}
		++i;
	}
}
Ejemplo n.º 12
0
/*
 * Writes the network and random walk information to the given file.
 */
void write_output ( std::string filename, std::vector<CreditVec> updates ) {
	FILE * pfile = fopen ( filename.c_str(), "w" );
	GraphSize id;
	
	// sort nodevec by id
   	std::sort( nodevec.begin(), nodevec.end(), nodecomp() );

	for ( auto& node : nodevec ) {
		id = node->id();
		if ( id != -1 ) {
			fprintf( pfile, "%lu\t%lu", id, node->edgeCount() );
			// output update values for node n
			for ( int i = 0; i < updates.size(); ++i ) {
				fprintf( pfile, "\t%.6lf", updates[i][id] );
			}
			fprintf( pfile, "\n" );
		}
	}

	fclose( pfile );
}
Ejemplo n.º 13
0
static void DumpNodeVecVec()
{
    // nodeVecVec is topologically sorted.
    printf("nodeVecVec = [\n");
    NodeVecVec::iterator vecVecIter = s_nodeVecVec.begin();
    NodeVecVec::iterator vecVecEnd = s_nodeVecVec.end();
    for(; vecVecIter != vecVecEnd; ++vecVecIter)
    {
		NodeVec* v = (*vecVecIter);
		assert(v);
		printf("    [ ");
		NodeVec::iterator vecIter = v->begin();
		NodeVec::iterator vecEnd = v->end();
		for(; vecIter != vecEnd; ++vecIter)
		{
			printf("%s ", (*vecIter)->sprite->GetName().c_str());
		}
		printf("]\n");
    }
    printf("]\n");
}
Ejemplo n.º 14
0
static void TextureStateSort(NodeVecVec& nodeVecVec, std::vector<const Sprite*>& spriteVec)
{
    // use the nodeVecVec and state sort each sub vec by texture.
    NodeVecVec::iterator vecVecIter = nodeVecVec.begin();
    NodeVecVec::iterator vecVecEnd = nodeVecVec.end();
    for(; vecVecIter != vecVecEnd; ++vecVecIter)
    {
        // Each NodeVec can be sorted by texture.
        // iterate over each sprite and insert into s_texMap.
		NodeVec* v = (*vecVecIter);
		NodeVec::iterator vecIter = v->begin();
		NodeVec::iterator vecEnd = v->end();
		for(; vecIter != vecEnd; ++vecIter)
        {
            const Sprite* sprite = (*vecIter)->sprite;
            if (sprite != s_screenSprite)
            {
                TexMap::iterator mapIter = s_texMap.find(sprite->GetTexture());
                assert(mapIter != s_texMap.end());
                mapIter->second.push_back(sprite);
            }
        }

        // Now iterate over s_texMap and insert into spriteVec
        TexMap::iterator mapIter = s_texMap.begin();
        TexMap::iterator mapEnd = s_texMap.end();
        for (; mapIter != mapEnd; ++mapIter)
        {
            SpriteVec::iterator sVecIter = mapIter->second.begin();
            SpriteVec::iterator sVecEnd = mapIter->second.end();
            for (; sVecIter != sVecEnd; ++sVecIter)
                spriteVec.push_back(*sVecIter);
        }

        // clean s_texMap
        mapIter = s_texMap.begin();
        for (; mapIter != mapEnd; ++mapIter)
            mapIter->second.clear();
    }
}
Ejemplo n.º 15
0
/*
 * Computes a credit update for the next time step given the current credit values for 
 * each node in the network.  Uses paralellism by mapping updates to available cores
 * through the OpenMP framework.
 * 
 * @params: C - stores the current credit values for each node in the network
 * 			C_ - stores the credit values for each node at time step t+1
 */
void credit_update (CreditVec &C, CreditVec &C_) {
	double sum;
	GraphSize id;
	Node *node;

	// compute credit for the next time step
	#pragma omp parallel for private( sum, node, id ) shared( C, C_ )
	for ( GraphSize i = 0; i < nodevec.size(); ++i ) {
		node = nodevec[i];
		id = node->id();
		if ( id != -1 ) {
			sum = 0;
			for ( auto& tarnode: *(node->getEdges()) ) {
				sum += C[tarnode->id()] / tarnode->edgeCount();
			}
			C_[id] = sum;
		}
	}
}
Ejemplo n.º 16
0
/*
 * DeleteCFG()
 *  Remove one CFG.
 */
void DeleteCFG(GraphNode *Root)
{
    NodeVec VisitStack;
    NodeSet Visited;
    
    VisitStack.push_back(Root);
    while(VisitStack.size())
    {
        GraphNode *Parent = VisitStack.back();
        VisitStack.pop_back();
        
        if (Visited.count(Parent))
            continue;
        
        Visited.insert(Parent);
        NodeVec &Child = Parent->getSuccessor();
        for (int i = 0, e = Child.size(); i < e; i++)
            VisitStack.push_back(Child[i]);
    }

    for (NodeSet::iterator I = Visited.begin(), E = Visited.end(); I != E; I++)
        delete *I;
}