int main() {

  igraph_t g;
  igraph_vector_t v;
  int ret;

  /* without edges */
  igraph_empty(&g, 5, IGRAPH_DIRECTED);
  igraph_add_vertices(&g, 2, 0);
  igraph_add_vertices(&g, 3, 0);
  igraph_add_vertices(&g, 1, 0);
  igraph_add_vertices(&g, 4, 0);
  if (igraph_vcount(&g) != 15)  {
    return 1;
  }
  igraph_delete_vertices(&g, igraph_vss_1(2));
  if (igraph_vcount(&g) != 14)  {
    return 2;
  }
  igraph_destroy(&g);
   
  igraph_vector_init(&v, 8);
  VECTOR(v)[0]=0; VECTOR(v)[1]=1;
  VECTOR(v)[2]=1; VECTOR(v)[3]=2;
  VECTOR(v)[4]=2; VECTOR(v)[5]=3;
  VECTOR(v)[6]=2; VECTOR(v)[7]=2;
  igraph_create(&g, &v, 0, 0);
  igraph_vector_destroy(&v);

  /* resize vector */
  igraph_delete_vertices(&g, igraph_vss_1(2));
  if (igraph_vcount(&g) != 3) {
    return 3;
  }
  if (igraph_ecount(&g) != 1) {
    return 4;
  }

  /* error test */
  igraph_set_error_handler(igraph_error_handler_ignore);
  ret=igraph_delete_vertices(&g, igraph_vss_1(3));
  if (ret != IGRAPH_EINVVID) {
    return 5;
  }
  
  igraph_destroy(&g);

  return 0;
}
/** 
 * \ingroup interface
 * \function igraph_empty_attrs
 * \brief Creates an empty graph with some vertices, no edges and some graph attributes.
 *
 * </para><para>
 * Use this instead of \ref igraph_empty() if you wish to add some graph
 * attributes right after initialization. This function is currently
 * not very interesting for the ordinary user, just supply 0 here or 
 * use \ref igraph_empty().
 * \param graph Pointer to a not-yet initialized graph object.
 * \param n The number of vertices in the graph, a non-negative
 *          integer number is expected.
 * \param directed Whether the graph is directed or not.
 * \param attr The attributes. 
 * \return Error code:
 *         \c IGRAPH_EINVAL: invalid number of vertices.
 * 
 * Time complexity: O(|V|) for a graph with
 * |V| vertices (and no edges).
 */
int igraph_empty_attrs(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed, void* attr) {

  if (n<0) {
    IGRAPH_ERROR("cannot create empty graph with negative number of vertices",
		  IGRAPH_EINVAL);
  }
  
  if (!IGRAPH_FINITE(n)) {
    IGRAPH_ERROR("number of vertices is not finite (NA, NaN or Inf)", IGRAPH_EINVAL);
  }

  graph->n=0;
  graph->directed=directed;
  IGRAPH_VECTOR_INIT_FINALLY(&graph->from, 0);
  IGRAPH_VECTOR_INIT_FINALLY(&graph->to, 0);
  IGRAPH_VECTOR_INIT_FINALLY(&graph->oi, 0);
  IGRAPH_VECTOR_INIT_FINALLY(&graph->ii, 0);
  IGRAPH_VECTOR_INIT_FINALLY(&graph->os, 1);
  IGRAPH_VECTOR_INIT_FINALLY(&graph->is, 1);

  VECTOR(graph->os)[0]=0;
  VECTOR(graph->is)[0]=0;

  /* init attributes */
  graph->attr=0;
  IGRAPH_CHECK(igraph_i_attribute_init(graph, attr));

  /* add the vertices */
  IGRAPH_CHECK(igraph_add_vertices(graph, n, 0));
  
  IGRAPH_FINALLY_CLEAN(6);
  return 0;
}
예제 #3
0
int GraphRepresentation::buildIGraphTopology() {
    int source_vertex_id, destination_vertex_id;
    igraph_i_set_attribute_table(&igraph_cattribute_table);
    igraph_empty(&igraph, 0, true);
    //cout << "iGraph: number of nodes: " << dm->number_of_nodes << endl;
    //cout << "iGraph: number number_of_connections nodes: " << dm->number_of_connections << endl;
    for (int i = 0; i < dm->network_nodes.size(); i++) {
        NetworkNode *nn = dm->network_nodes[i];
        for (int j = 0; j < nn->connections.size(); j++) {
            NetworkConnection *nc = nn->connections[j];
            map <string, int>::iterator index_it;
            /*find that node - if exists*/
            index_it = reverse_node_index.find(nc->src_label);
            /*check if the source node exists in the reverse index*/
            if (index_it == reverse_node_index.end()) {
                /*it does not exist...add it*/
                source_vertex_id = igraph_vcount(&igraph);
                igraph_add_vertices(&igraph, 1, 0);
                reverse_node_index.insert(pair<string, int>(nc->src_label, source_vertex_id));
                igraph_cattribute_VAS_set(&igraph, "NODEID", source_vertex_id, nc->src_label.c_str());
                //cout << "added node " << nc->src_label << " in the igraph" << endl;
            } else {
                source_vertex_id = (*index_it).second;
            }
            index_it = reverse_node_index.find(nc->dst_label);
            /*check if the destination node exists in the reverse index*/
            if (index_it == reverse_node_index.end()) {
                /*it does not exist...add it*/
                destination_vertex_id = igraph_vcount(&igraph);
                igraph_add_vertices(&igraph, 1, 0);
                reverse_node_index.insert(pair<string, int>(nc->dst_label, destination_vertex_id));
                igraph_cattribute_VAS_set(&igraph, "NODEID", destination_vertex_id, nc->dst_label.c_str());
                //cout << "added node " << nc->dst_label << " in the igraph" << endl;
            } else {
                destination_vertex_id = (*index_it).second;
            }
            /*add an edge in the graph*/
            igraph_add_edge(&igraph, source_vertex_id, destination_vertex_id);
            igraph_cattribute_EAS_set(&igraph, "LID", igraph_ecount(&igraph) - 1, nc->LID.to_string().c_str());
            reverse_edge_index.insert(pair<string, int>(nc->LID.to_string(), igraph_ecount(&igraph) - 1));
        }
    }
    for (int i = 0; i < dm->network_nodes.size(); i++) {
        NetworkNode *nn = dm->network_nodes[i];
        igraph_cattribute_VAS_set(&igraph, "iLID", i, nn->iLid.to_string().c_str());
    }
}
예제 #4
0
파일: graph.cpp 프로젝트: ntamas/igraphpp
void Graph::addVertices(long int numVertices) {
    assert(m_pGraph);
    IGRAPH_TRY(igraph_add_vertices(m_pGraph, numVertices, 0));
}
예제 #5
0
igraph_vector_t *ggen_analyze_lowest_single_ancestor(igraph_t *g)
{
	unsigned long i,v,l,vid,r;
	int err = 0;
	igraph_vector_t toposort,itopo;
	igraph_vector_t *lsa;
	igraph_t tree;
	igraph_vs_t vs;
	igraph_vit_t vit;
	lca_metadata md;

	if(g == NULL)
		return NULL;

	err = igraph_vector_init(&toposort,igraph_vcount(g));
	if(err) return NULL;

	err = igraph_topological_sorting(g,&toposort,IGRAPH_OUT);
	if(err) goto d_tp;

	/* build a reverse index of the toposort */
	err = igraph_vector_init(&itopo,igraph_vcount(g));
	if(err) goto d_tp;

	for(i = 0; i < igraph_vcount(g); i++)
	{
		v = VECTOR(toposort)[i];
		VECTOR(itopo)[v] = i;
	}

	err = igraph_empty(&tree,1,IGRAPH_DIRECTED);
	if(err) goto d_i;

	lsa = calloc(1,sizeof(igraph_vector_t*));
	if(lsa == NULL) goto cleanup;

	err = igraph_vector_init(lsa,igraph_vcount(g));
	if(err) goto f_l;

	for(v = 1; v < igraph_vcount(g); v++)
	{
		vid = VECTOR(toposort)[v];

		tree_lca_metadata_init(&tree,&md);
		tree_lca_preprocessing(&tree,0,&md);

		/* iterate over parents of v in g
		 * The lsa of a node is the LCA of all its parents in our
		 * special tree.
		 */
		igraph_vs_adj(&vs, vid, IGRAPH_IN);
		igraph_vit_create(g,vs,&vit);
		l = VECTOR(itopo)[IGRAPH_VIT_GET(vit)];
		IGRAPH_VIT_NEXT(vit);

		for(vit;!IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit))
		{
			tree_lca_query(&tree,l,VECTOR(itopo)[IGRAPH_VIT_GET(vit)],&r,&md);
			l = r;
		}

		igraph_vit_destroy(&vit);
		igraph_vs_destroy(&vs);
		tree_lca_metadata_free(&tree,&md);

		// update tree
		err = igraph_add_vertices(&tree,1,NULL);
		if(err) goto d_l;

		err = igraph_add_edge(&tree,l,v);
		if(err) goto d_l;

		VECTOR(*lsa)[vid] = VECTOR(toposort)[l];
	}
	goto cleanup;
d_l:
	igraph_vector_destroy(lsa);
f_l:
	free(lsa);
	lsa = NULL;
cleanup:
	igraph_destroy(&tree);
d_i:
	igraph_vector_destroy(&itopo);
d_tp:
	igraph_vector_destroy(&toposort);
	return lsa;
}
예제 #6
0
/* Fan-in/ Fan-out method
*/
igraph_t *ggen_generate_fifo(gsl_rng *r, unsigned long n, unsigned long od, unsigned long id)
{
    igraph_t *g = NULL;
    igraph_vector_t available_od;
    igraph_vector_t out_degrees;
    igraph_vector_t vertices;
    igraph_vector_t choice;
    igraph_vector_t edges;
    unsigned long max;
    unsigned long i,j,k;
    unsigned long vcount = 1;
    int err;

    ggen_error_start_stack();
    if(r == NULL)
        GGEN_SET_ERRNO(GGEN_EINVAL);

    if(id == 0 || od == 0 || od > n || id > n)
        GGEN_SET_ERRNO(GGEN_EINVAL);

    g = malloc(sizeof(igraph_t));
    GGEN_CHECK_ALLOC(g);
    GGEN_FINALLY3(free,g,1);

    GGEN_CHECK_IGRAPH(igraph_empty(g,1,1));
    GGEN_FINALLY3(igraph_destroy,g,1);

    GGEN_CHECK_IGRAPH(igraph_vector_init(&available_od,n));
    GGEN_FINALLY(igraph_vector_destroy,&available_od);
    GGEN_CHECK_IGRAPH(igraph_vector_init(&out_degrees,n));
    GGEN_FINALLY(igraph_vector_destroy,&out_degrees);
    GGEN_CHECK_IGRAPH(igraph_vector_init(&vertices,n));
    GGEN_FINALLY(igraph_vector_destroy,&vertices);
    GGEN_CHECK_IGRAPH(igraph_vector_init(&choice,n));
    GGEN_FINALLY(igraph_vector_destroy,&choice);
    GGEN_CHECK_IGRAPH(igraph_vector_init(&edges,n*2));
    GGEN_FINALLY(igraph_vector_destroy,&edges);
    while(vcount < n)
    {
        // never trigger errors as it doesn't allocate or free memory
        igraph_vector_resize(&available_od,vcount);
        igraph_vector_resize(&out_degrees,vcount);
        igraph_vector_resize(&vertices,vcount);

        // compute the available out degree of each vertex
        GGEN_CHECK_IGRAPH(igraph_degree(g,&out_degrees,igraph_vss_all(),IGRAPH_OUT,0));

        // fill available with od and substract out_degrees
        igraph_vector_fill(&available_od,od);
        GGEN_CHECK_IGRAPH(igraph_vector_sub(&available_od,&out_degrees));

        if(gsl_ran_bernoulli(r,0.5))     //Fan-out Step
        {
            // find max
            max = igraph_vector_max(&available_od);

            // register all vertices having max as outdegree
            j = 0;
            for (i = 0; i < vcount; i++)
                if(VECTOR(available_od)[i] == max)
                    VECTOR(vertices)[j++] = i;

            // choose randomly a vertex among availables
            GGEN_CHECK_GSL_DO(i = gsl_rng_uniform_int(r,j));

            // how many children ?
            GGEN_CHECK_GSL_DO(j = gsl_rng_uniform_int(r,max));
            j = j+1;

            // create all new nodes and add edges
            GGEN_CHECK_IGRAPH(igraph_add_vertices(g,j,NULL));

            // cannot fail
            igraph_vector_resize(&edges,j*2);

            for(k = 0; k < j; k++)
            {
                VECTOR(edges)[2*k] = i;
                VECTOR(edges)[2*k+1] = vcount + k;
            }
            vcount+=k;
        }
        else	//Fan-In Step
        {
            // register all vertices having an available outdegree
            j = 0;
            for (i = 0; i < vcount; i++)
                if(VECTOR(available_od)[i] > 0)
                    VECTOR(vertices)[j++] = i;

            // we can add at most id vertices
            max =( j > id)? id: j;
            // how many edges to add
            GGEN_CHECK_GSL_DO(k = gsl_rng_uniform_int(r,max));
            k = k+1;

            // choose that many nodes and add edges from them to the new node
            // cannot fail either
            igraph_vector_resize(&choice,k);

            gsl_ran_choose(r,VECTOR(choice),k,
                           VECTOR(vertices),j,sizeof(VECTOR(vertices)[0]));

            // add a vertex to the graph
            GGEN_CHECK_IGRAPH(igraph_add_vertices(g,1,NULL));

            igraph_vector_resize(&edges,k*2);
            // be carefull, vcount is the last ID of vertices not vcount +1
            for(i = 0; i < k; i++)
            {
                VECTOR(edges)[2*i] = VECTOR(choice)[i];
                VECTOR(edges)[2*i+1] = vcount;
            }
            vcount++;

        }
        // in all cases, edges should be added
        GGEN_CHECK_IGRAPH(igraph_add_edges(g,&edges,NULL));
    }
    ggen_error_clean(1);
    return g;
ggen_error_label:
    return NULL;
}
예제 #7
0
/*****************************************************************************
 * Main
 ****************************************************************************/
int main(int argc, char **argv) {

    srand ( time(NULL) );
       
    /******************************
     * Command Line Parser
     ******************************/
         
    bool mono_lib(false), print_gate(false), print_solns(false), print_sat(false), print_blif(false), print_verilog(false);
    int num_threads, budget;
    float remove_percent(0.6);
    vector<string> test_args;
    
    po::options_description optional_args("Usage: [options]");
    optional_args.add_options()
        ("circuit",         po::value<string>(),                                    "input circuit")
        ("tech_lib",        po::value<string>(),                                    "tech library")
        ("continue_file,c", po::value<string>(),                                    "input report to continue from")
        ("mono_lib,m",      po::value(&mono_lib)->zero_tokens(),                    "treat each gate as a nand")
        ("budget,b",        po::value<int>(&budget)->default_value(100000000),      "minisat conflict budget (-1 = unlimited)")
        ("remove_edges,e",  po::value<float>(&remove_percent)->default_value(0.6),  "edge percent to remove")
        ("print_graph",     po::value(&print_gate)->zero_tokens(),                  "print H graph")
        ("print_solns",     po::value(&print_solns)->zero_tokens(),                 "print isos")
        ("print_blif",      po::value(&print_blif)->zero_tokens(),                  "print G blif circuit")
        ("print_verilog",   po::value(&print_verilog)->zero_tokens(),               "print verilog circuits")
        ("test,t",          po::value< vector<string> >(&test_args),                 "Run test suite #: \n"
                                                                                    "  -99: Beta Testing \n"
                                                                                    "  -1: Mem Testing \n"
                                                                                    "   0: L0 [count, remove_percent] \n"
                                                                                    "   1: L1 [count, remove_percent] \n"
                                                                                    "   2: S1 - Random [min S1] \n"
                                                                                    "   3: S1 - Greedy [min S1] \n")
        ("num_threads,n",   po::value<int>(&num_threads)->default_value(1),         "Number of threads")
        ("wdir,w",          po::value<string>()->default_value("./wdir"),           "Output directory")
        ("help,h",                                                                  "produce help message")
    ;

    po::positional_options_description positional_args;
    positional_args.add("circuit", 1);
    positional_args.add("tech_lib", 1);
    positional_args.add("test", -1);
    po::variables_map vm;

    try {
        po::store(po::command_line_parser(argc, argv).options(optional_args).positional(positional_args).run(), vm);
        po::notify(vm);
    } catch(exception& e) {
        cerr << "error: " << e.what() << "\n";
        return 1;
    } catch(...) {
        cerr << "Exception of unknown type!\n";
    }

    if (vm.count("help")) {
        cout << optional_args << "\n";
        return 0;
    }

    string circuit_filename, circuit_name, tech_filename, tech_name, working_dir, report_filename;
   
    // input circuit
    if (vm.count("circuit") == 1) {
        circuit_filename = vm["circuit"].as<string>();
        circuit_name = circuit_filename.substr(circuit_filename.rfind('/')+1);
        circuit_name = circuit_name.substr(0, circuit_name.find('.'));
    } else {
        cout << optional_args << "\n";
        return 0;
    }

    // input tech lib
    if (vm.count("tech_lib")) {
        tech_filename = vm["tech_lib"].as<string>();
        tech_name = tech_filename.substr(tech_filename.rfind('/')+1);
        tech_name = tech_name.substr(0, tech_name.find('.'));
    } else {
        cout << optional_args << "\n";
        return 0;
    }

    cout << "Circuit : " << circuit_filename << "\n";
    cout << "Tech Lib: " << tech_filename << "\n";

   
    /******************************
     * Setup working dir
     ******************************/
    working_dir = vm["wdir"].as<string>();
    mkdir(working_dir.c_str(), S_IRWXU);
    cout << "WDIR    : " << working_dir << "\n";


    /******************************
     * Convert circuit using tech_lib
     ******************************/
    string outfile = working_dir + circuit_filename.substr(circuit_filename.rfind('/'));
    cout << "Outfile : " << outfile << "\n";
   // sis_convert(circuit_filename, tech_filename, outfile);
cout << "I'm here!\n";
    circuit_filename = outfile;
    // copy tech_lib
    if ( tech_filename != string(working_dir + tech_filename.substr(tech_filename.rfind('/')) ) ) {
        ifstream src( tech_filename.c_str() );
        ofstream dst( string(working_dir + tech_filename.substr(tech_filename.rfind('/')) ).c_str() );
        dst << src.rdbuf();
        dst.close();
    }

   
    /******************************
     * Load circuit
     ******************************/
    Circuit circuit;
    load_circuit(&circuit, circuit_filename, mono_lib);
    
    Security *security;
    Circuit G, H;
    G.copy(&circuit);
    G.remove_io();

    circuit.save( working_dir + "/circuit.gml" );
    G.save( working_dir + "/G_circuit.gml" );


    /****************************************************************
     * print G
     ****************************************************************/
    if ( test_args.size() > 0 && -1 == atoi(test_args[0].c_str())) {
         G.print();
    }


    /****************************************************************
     * L0
     ****************************************************************/
    if ( test_args.size() > 0 && 0 == atoi(test_args[0].c_str())) {

        int max_count(2);
        if (test_args.size() == 2)
            max_count = atoi(test_args[1].c_str());

        H.copy(&G);
        H.rand_del_edges(remove_percent);
        H.save( working_dir + "/H_circuit.gml" );

        security = new Security(&G, &H);
        security->setConfBudget(budget);

        cout << "Rand L0: |V(G)| = "  << (int) igraph_vcount(&G);
        cout << ", |E(G)| = "         << (int) igraph_ecount(&G);
        cout << ", |V(H)| = "         << (int) igraph_vcount(&H);
        cout << ", |E(H)| = "         << (int) igraph_ecount(&H) << "\n";
        
        cout << " " << boolalpha << security->L0(max_count, false) << endl;
    }



    /****************************************************************
     * L1
     ****************************************************************/
    if ( test_args.size() > 0 && 1 == atoi(test_args[0].c_str())) {

        int max_L1(2);
        if (test_args.size() == 2)
            max_L1 = atoi(test_args[1].c_str());

        H.copy(&G);
        H.rand_del_edges(remove_percent);
        
        if (vm.count("continue_file")) {
            H.rand_del_edges((float) 1.0);
            string filename = vm["continue_file"].as<string>();
            ifstream file;
            try {
                file.open(filename.c_str());
                
                while (file.good()) {
                    string line;
                    int L0, L1;
                    Edge edge;

                    getline(file, line);
                    if (parse(line, &G, L1, L0, edge)) {
                        if (L1 >= max_L1) {
                            H.add_edge(edge);
                            cout << "L1 = " << max_L1 << ", +<" << edge.first << "," << edge.second << ">" << endl;
                        }
                    }
                }
            } catch(...) {}
        }

        H.save( working_dir + "/H_circuit.gml" );

        security = new Security(&G, &H);
        security->setConfBudget(budget);

        cout << "Rand L1: |V(G)| = "  << (int) igraph_vcount(&G);
        cout << ", |E(G)| = "         << (int) igraph_ecount(&G);
        cout << ", |V(H)| = "         << (int) igraph_vcount(&H);
        cout << ", |E(H)| = "         << (int) igraph_ecount(&H) << "\n";
        
        cout << " " << boolalpha << security->L1(max_L1, false) << endl;
    }



    /****************************************************************
     * #L1
     ****************************************************************/
    if ( test_args.size() == 1 && 2 == atoi(test_args[0].c_str())) {

        int max_L1(2);
        if (test_args.size() == 2)
            max_L1 = atoi(test_args[1].c_str());

        H.copy(&G);
        H.rand_del_edges(remove_percent);

        if (vm.count("continue_file")) {
            H.rand_del_edges((float) 1.0);
            string filename = vm["continue_file"].as<string>();
            ifstream file;
            try {
                file.open(filename.c_str());
                
                while (file.good()) {
                    string line;
                    int L0, L1;
                    Edge edge;

                    getline(file, line);
                    if (parse(line, &G, L1, L0, edge)) {
                        H.add_edge(edge);
                        max_L1 = L1;
                        cout << "L1 = " << max_L1 << ", +<" << edge.first << "," << edge.second << ">" << endl;
                    }
                }
            } catch(...) {}
        }

        H.save( working_dir + "/H_circuit.gml" );

        security = new Security(&G, &H);
        security->setConfBudget(budget);

        cout << "Rand L1: |V(G)| = "  << (int) igraph_vcount(&G);
        cout << ", |E(G)| = "         << (int) igraph_ecount(&G);
        cout << ", |V(H)| = "         << (int) igraph_vcount(&H);
        cout << ", |E(H)| = "         << (int) igraph_ecount(&H) << "\n";
        cout << " " << security->L1(false);
    }



    /****************************************************************
     * S1_rand
     ****************************************************************/
    if ( test_args.size() == 1 && 3 == atoi(test_args[0].c_str())) {

        int max_L1 = G.max_L1();
        H.copy(&G);
        H.rand_del_edges((float) 1.0);

        security = new Security(&G, &H);
        security->setConfBudget(budget);

        string output;
        output = "S1_rand ("  + G.get_name() + ")";
        output = report(output, &G, &H, max_L1);
        cout << output;

        security->S1_rand(num_threads);
    }



    /****************************************************************
     * S1_greedy
     ****************************************************************/
    if ( test_args.size() >= 1 && 4 == atoi(test_args[0].c_str())) {

        int min_L1(2), max_L1 = G.max_L1();
        H.copy(&G);
        H.rand_del_edges((float) 1.0);
        bool done(false);
        
        if ( test_args.size() == 3 ) {
            min_L1 = atoi(test_args[1].c_str());
            max_L1 = atoi(test_args[2].c_str());
        } else if ( test_args.size() == 2 )
            min_L1 = atoi(test_args[1].c_str());

        if (vm.count("continue_file")) {
            string filename = vm["continue_file"].as<string>();
            ifstream file;
		
		for (int eid = 0; eid < igraph_ecount(&G); eid++)
			SETEAS(&G, "style", eid, "invis");

            try {
                file.open(filename.c_str());
                
//		int last_sec;
//		Edge prev_edge;
//		bool first = true;
                while (file.good()) {
                    string line;
                    int L0, L1;
                    Edge edge;

                    getline(file, line);
		    
		
                    if (parse(line, &G, L1, L0, edge)) {
                        if (L1 < min_L1) {
                            done = true;
                            break;
                        }

//			if (first) { last_sec = L1; first = false; prev_edge = edge;}
//			else
//			{
//				if (last_sec != L1)
//				{

					
//					H.del_edge(prev_edge);
//					string gmlfilename;
//					char num[3];
//					sprintf(num, "%d", last_sec);		
//					gmlfilename = working_dir + "/H_circuit_" + num + ".gml";
//					string gvfilename = working_dir + "/H_circuit_" + num + ".gv";
//					string psfilename = working_dir + "/H_circuit_" + num + ".ps";					
					//H.save( gmlfilename );
//					G.save( gmlfilename );

//					H.add_edge(prev_edge);
//					string command = "gml2gv -o" + gvfilename + " " + gmlfilename;
//					system(command.c_str());
//					command = "dot -Tps -Nstyle=filled -Ncolorscheme=accent8 -Nshape=circle -Nlabel=\"\" -o " + psfilename + " " + gvfilename;
//					system(command.c_str());
//					last_sec = L1;
//				}
//				prev_edge = edge;
//				int eid;
//				igraph_get_eid(&G, &eid, edge.first, edge.second, true, false);
//				SETEAS(&G, "style", eid, "solid");

//			}
			
				
                        H.add_edge(edge);
                        max_L1 = L1;
                        cout << "L1 = " << max_L1 << ", +<" << edge.first << "," << edge.second << ">" << endl;
                    }
                }
//		return 0;
            } catch(...) {}
        }

        if ( test_args.size() == 3 ) {
            min_L1 = atoi(test_args[1].c_str());
            max_L1 = atoi(test_args[2].c_str());
        } else if ( test_args.size() == 2 )
            min_L1 = atoi(test_args[1].c_str());

        security = new Security(&G, &H);
        security->setConfBudget(budget);
	
        string output;
        output = "S1_greedy ("  + G.get_name() + ")";
        output = report(output, &G, &H, max_L1);
        cout << output;

        fstream report;
        if (!done)
	{
		clock_t tic = clock();
            security->S1_greedy(num_threads, min_L1, max_L1);
		clock_t toc = clock();
          cout << endl << "Heuristic took: ";
          cout << (double) (toc-tic)/CLOCKS_PER_SEC << endl;
	}

    }


    /****************************************************************
     * k-isomorphism
     ****************************************************************/
    if ( test_args.size() >= 1 && 10 == atoi(test_args[0].c_str())) {

        int min_L1(2), max_L1 = G.max_L1();

	if ( test_args.size() == 3 ) {
            min_L1 = atoi(test_args[1].c_str());
            max_L1 = atoi(test_args[2].c_str());
        } else if ( test_args.size() == 2 )
            min_L1 = atoi(test_args[1].c_str());

	igraph_vector_t match_vert;
	igraph_vector_init(&match_vert, 0);
	for (int i = 0; i < igraph_vcount(&G); i++)
	{
			int color = VAN(&G, "colour", i);
			if (igraph_vector_size(&match_vert) < color + 1)
				for (int j = igraph_vector_size(&match_vert); j <= color; j++)
				{
					igraph_vector_push_back(&match_vert, 0);
				}
			VECTOR(match_vert)[color]++;
	}

	igraph_t temp;
//	igraph_copy(&temp, &G);
//	igraph_destroy(&G);
//	for (min_L1 = max_L1; min_L1 >= 1; min_L1--) {
//		igraph_copy(&G, &temp);
	int count = 0;
	for (int i = 0; i < igraph_vector_size(&match_vert); i++)
	{
		int n = ((int) VECTOR(match_vert)[i]) % min_L1; if (n == 0) continue;
		for (int j = 0; j < min_L1 - n; j++)
		{ count++;
			igraph_add_vertices(&G, 1, 0);
			SETVAN(&G, "colour", igraph_vcount(&G) - 1, i);
		}
	}
	
cout << count << " "; cout.flush();
        H.copy(&G);
        H.rand_del_edges((float) 1.0);
        bool done(false);
        
        security = new Security(&G, &H);
        security->setConfBudget(budget);
	
        string output;
        output = "S1_greedy ("  + G.get_name() + ")";
        output = report(output, &G, &H, max_L1);
//        cout << output;

        fstream report;
        if (!done)
	{
		clock_t tic = clock();
            security->kiso(min_L1, max_L1);
		clock_t toc = clock();
  //        cout << endl << "Heuristic took: ";
   //       cout << (double) (toc-tic)/CLOCKS_PER_SEC << endl;
	} //igraph_destroy(&G);}

    }

/****************************************************************
     * Tree test
     ****************************************************************/
    if ( test_args.size() >= 1 && 7 == atoi(test_args[0].c_str())) {

        int min_L1(2), max_L1 = G.max_L1();

	//G.erase();
	igraph_vs_t vs;
	igraph_vs_all(&vs);

	igraph_delete_vertices(&G, vs);
	const int depth = 7;
	igraph_add_vertices(&G, pow(2,depth)-1, 0);
	for (int i=0; i < pow(2,depth-1); i++)
	{
		int level = floor(log(i+1)/log(2));
		igraph_add_edge(&G,i,pow(2,level+1) + (i-pow(2,level))*2 - 1);
		igraph_add_edge(&G,i,pow(2,level+1) + (i-pow(2,level))*2);
	}	

	for (int i=0; i < igraph_vcount(&G); i++)
	{
		SETVAN(&G, "colour", i, 0);
		SETVAS(&G, "type", i, "invf101");
		string label = "label";
		SETVAS(&G, "label", i, label.c_str());
	}

        H.copy(&G);
	for (int i=0; i < igraph_vcount(&H); i++)
	{
		SETVAN(&H, "colour", i, 0);
	}

        H.rand_del_edges((float) 1.0);
        
        if ( test_args.size() == 3 ) {
            min_L1 = atoi(test_args[1].c_str());
            max_L1 = atoi(test_args[2].c_str());
        } else if ( test_args.size() == 2 )
            min_L1 = atoi(test_args[1].c_str());


        if ( test_args.size() == 3 ) {
            min_L1 = atoi(test_args[1].c_str());
            max_L1 = atoi(test_args[2].c_str());
        } else if ( test_args.size() == 2 )
            min_L1 = atoi(test_args[1].c_str());

	cout << "I'm here!"; cout.flush();
        security = new Security(&G, &H);
        security->setConfBudget(budget);
	
        string output;
	cout << "I'm here!";
        output = "S1_greedy ("  + G.get_name() + ")";
	cout << "I'm here!";
        output = report(output, &G, &H, max_L1);
        cout << output;

	cout << "I'm here!";
        security->S1_greedy(num_threads, min_L1, max_L1);

    }

/****************************************************************
     * Compute security level G if no wires are lifted
     ****************************************************************/
    if ( test_args.size() >= 1 && 5 == atoi(test_args[0].c_str())) {

        H.copy(&G);
        security = new Security(&G, &H);
        security->setConfBudget(budget);
   H.rand_del_edges((float) 0.0);

//	security->clean_solutions();

        string output;
        output = "Security of circuit ("  + G.get_name() + ") if no wires are lifted: ";
        cout << output;
        
        security->S1_self();

    }



/****************************************************************
     * Solve LIFT(G, k, eta)
     ****************************************************************/

if ( test_args.size() >= 1 && 6 == atoi(test_args[0].c_str())) {

        int min_L1(2), max_L1 = G.max_L1(), eta = igraph_ecount(&G);
	H.copy(&G);
//        H.rand_del_edges((float) 1.0);
        
        if ( test_args.size() == 3 ) {
            min_L1 = atoi(test_args[1].c_str());
            eta = atoi(test_args[2].c_str());
        } else if ( test_args.size() == 2 )
            min_L1 = atoi(test_args[1].c_str());

        security = new Security(&G, &H);
        security->setConfBudget(budget);
	
    
	clock_t tic = clock();
	security->rSAT(min_L1, max_L1, eta);
	clock_t toc = clock();
	cout << endl << "SAT took: ";
	cout << (double) (toc-tic)/CLOCKS_PER_SEC << endl;

    }

/****************************************************************
     * Solve LIFT(G, k, eta, u)
     ****************************************************************/

if ( test_args.size() >= 1 && 8 == atoi(test_args[0].c_str())) {

        int min_L1(2), max_L1 = G.max_L1(), eta = igraph_ecount(&G), u;
	H.copy(&G);
//        H.rand_del_edges((float) 1.0);
        
        if ( test_args.size() == 4 ) {
		u = atoi(test_args[1].c_str());
            min_L1 = atoi(test_args[2].c_str());
            eta = atoi(test_args[3].c_str());
        } else if ( test_args.size() == 3 )
	{
		u = atoi(test_args[1].c_str());
            min_L1 = atoi(test_args[2].c_str());
} 
else if ( test_args.size() == 2 )
		u = atoi(test_args[1].c_str());

        security = new Security(&G, &H);
        security->setConfBudget(budget);
	
    
	clock_t tic = clock();
	security->rSAT(min_L1, max_L1, eta, u, true);
	clock_t toc = clock();
	cout << endl << "SAT took: ";
	cout << (double) (toc-tic)/CLOCKS_PER_SEC << endl;

    }

/****************************************************************
     * Solve LIFT(G, k, eta, u)
     ****************************************************************/

if ( test_args.size() >= 1 && 9 == atoi(test_args[0].c_str())) {

        int min_L1(2), max_L1 = G.max_L1(), eta = igraph_ecount(&G), u;
	H.copy(&G);
//        H.rand_del_edges((float) 1.0);
        
        if ( test_args.size() == 4 ) {
		u = atoi(test_args[1].c_str());
            min_L1 = atoi(test_args[2].c_str());
            eta = atoi(test_args[3].c_str());
        } else if ( test_args.size() == 3 )
	{
		u = atoi(test_args[1].c_str());
            min_L1 = atoi(test_args[2].c_str());
} 
else if ( test_args.size() == 2 )
		u = atoi(test_args[1].c_str());

        security = new Security(&G, &H);
        security->setConfBudget(budget);
	
    
	clock_t tic = clock();
	security->rSAT(min_L1,max_L1, eta, u);
	clock_t toc = clock();
	cout << endl << "SAT took: ";
	cout << (double) (toc-tic)/CLOCKS_PER_SEC << endl;

    }

/****************************************************************
     * simulated annealing
     ****************************************************************/


if ( test_args.size() >= 1 && 10 == atoi(test_args[0].c_str())) {
    const double MAX_TEMP = 100000.0;
    const int MAX_ITERATIONS = 2000;
    const double TEMP_CHANGE = 0.98;
    int no_of_edges = 20;
    int min_L1(2), max_L1 = G.max_L1();
    H.copy(&G);
    H.rand_del_edges(igraph_ecount(&G) - no_of_edges);
    security = new Security(&G, &H);
    security->setConfBudget(budget);
    int current_k_security = security->L1(); 
    int best_k_security = current_k_security;
    delete security;
    double temperature = MAX_TEMP;
    srand( time(NULL));

    for (int iter = 0; iter < MAX_ITERATIONS; iter++) {
        bool done(false);
        
        // H.rand_del_edges(1);
        vector<Edge> unlifted_edge_list;
        for (int eid = 0; eid < igraph_ecount(&H); eid++) {
            Edge edge = H.get_edge(eid);
            unlifted_edge_list.push_back(edge);
        }
        random_shuffle(unlifted_edge_list.begin(), unlifted_edge_list.end());
        H.del_edge(unlifted_edge_list[0]);

 
        vector<Edge> edge_list;
        for (int eid = 0; eid < igraph_ecount(&G); eid++) {
            Edge edge = G.get_edge(eid);
            if (!H.test_edge(edge)) edge_list.push_back(edge);
        }
        random_shuffle(edge_list.begin(), edge_list.end());
        H.add_edge(edge_list[0]);

        security = new Security(&G, &H);
        security->setConfBudget(budget);
	
        int new_k_security = security->L1();
        if (new_k_security >= current_k_security) { 
            current_k_security = new_k_security;
            if (current_k_security >= best_k_security) best_k_security = current_k_security;
        }
        else {
            if (exp((new_k_security-current_k_security)/temperature) >= ((double) rand())/ RAND_MAX);
            else {
                H.add_edge(unlifted_edge_list[0]);
                H.add_edge(edge_list[0]);
            }
        }
        temperature *= TEMP_CHANGE;
        if ((iter + 1 )% 10 == 0) cout << " > iteration " << iter + 1 << ", temp=" << temperature << ", best=" << best_k_security << endl;             
    }
}



    /****************************************************************
     * L1(label)
     ****************************************************************/
    if ( test_args.size() >= 1 && 5 == atoi(test_args[0].c_str())) {

        string label = "";
        if (test_args.size() == 2)
            label = test_args[1];

        int max_L1(2);
        H.copy(&G);
        H.rand_del_edges(remove_percent);
        
        if (vm.count("continue_file")) {
            H.rand_del_edges((float) 1.0);
            string filename = vm["continue_file"].as<string>();
            ifstream file;
            try {
                file.open(filename.c_str());
                
                while (file.good()) {
                    string line;
                    int L0, L1;
                    Edge edge;

                    getline(file, line);
                    if (parse(line, &G, L1, L0, edge)) {
                        H.add_edge(edge);
                        max_L1 = L1;
                        cout << "L1 = " << max_L1 << ", +<" << edge.first << "," << edge.second << ">" << endl;
                    }
                }
            } catch(...) {}
        }

        H.save( working_dir + "/H_circuit.gml" );

        security = new Security(&G, &H);
        security->setConfBudget(budget);

        security->L1(label);       
    }


    if ( test_args.size() >= 1 && atoi(test_args[0].c_str()) >= 0) {
        H.save( working_dir + "/H_circuit.gml" );
        delete security;
    }

    if (print_gate)
        G.print();

    if (print_blif)
        print_file(circuit_filename);
        
    if (print_solns)
        security->print_solutions();

    if (print_verilog)
        security->print_solutions();


    printf("\n\ndone 0 \n");
    return 0;
}
예제 #8
0
int main() {
  
  igraph_t g, g2;
  FILE *ifile;
  igraph_vector_t gtypes, vtypes, etypes;
  igraph_strvector_t gnames, vnames, enames;
  long int i;
  igraph_vector_t y;
  igraph_strvector_t id;
  char str[20];

  /* turn on attribute handling */
  igraph_i_set_attribute_table(&igraph_cattribute_table);
  
  ifile=fopen("LINKS.NET", "r");
  if (ifile==0) {
    return 10;
  }
  igraph_read_graph_pajek(&g, ifile);
  fclose(ifile);

  igraph_vector_init(&gtypes, 0);
  igraph_vector_init(&vtypes, 0);
  igraph_vector_init(&etypes, 0);
  igraph_strvector_init(&gnames, 0);
  igraph_strvector_init(&vnames, 0);
  igraph_strvector_init(&enames, 0);
  
  igraph_cattribute_list(&g, &gnames, &gtypes, &vnames, &vtypes, 
			 &enames, &etypes);
  
  /* List attribute names and types */
  printf("Graph attributes: ");
  for (i=0; i<igraph_strvector_size(&gnames); i++) {
    printf("%s (%i) ", STR(gnames, i), (int)VECTOR(gtypes)[i]);
  }
  printf("\n");
  printf("Vertex attributes: ");
  for (i=0; i<igraph_strvector_size(&vnames); i++) {
    printf("%s (%i) ", STR(vnames, i), (int)VECTOR(vtypes)[i]);
  }
  printf("\n");
  printf("Edge attributes: ");
  for (i=0; i<igraph_strvector_size(&enames); i++) {
    printf("%s (%i) ", STR(enames, i), (int)VECTOR(etypes)[i]);
  }
  printf("\n");

  print_attributes(&g);

  /* Copying a graph */
  igraph_copy(&g2, &g);
  print_attributes(&g2);
  igraph_destroy(&g2);
  
  /* Adding vertices */
  igraph_add_vertices(&g, 3, 0);
  print_attributes(&g);

  /* Adding edges */
  igraph_add_edge(&g, 1, 1);
  igraph_add_edge(&g, 2, 5);
  igraph_add_edge(&g, 3, 6);
  print_attributes(&g);

  /* Deleting vertices */
  igraph_delete_vertices(&g, igraph_vss_1(1));
  igraph_delete_vertices(&g, igraph_vss_1(4));
  print_attributes(&g);

  /* Deleting edges */
  igraph_delete_edges(&g, igraph_ess_1(igraph_ecount(&g)-1));
  igraph_delete_edges(&g, igraph_ess_1(0));
  print_attributes(&g);

  /* Set graph attributes */
  SETGAN(&g, "id", 10);
  if (GAN(&g, "id") != 10) {
    return 11;
  }
  SETGAS(&g, "name", "toy");
  if (strcmp(GAS(&g, "name"), "toy")) {
    return 12;
  }
  
  /* Delete graph attributes */
  DELGA(&g, "id");
  DELGA(&g, "name");
  igraph_cattribute_list(&g, &gnames, 0,0,0,0,0);
  if (igraph_strvector_size(&gnames) != 0) {
    return 14;
  }  

  /* Delete vertex attributes */
  DELVA(&g, "x");
  DELVA(&g, "shape");
  DELVA(&g, "xfact");
  DELVA(&g, "yfact");
  igraph_cattribute_list(&g, 0,0, &vnames, 0,0,0);  
  if (igraph_strvector_size(&vnames) != 2) {
    return 15;
  }
  
  /* Delete edge attributes */
  igraph_cattribute_list(&g, 0,0,0,0,&enames,0);
  i=igraph_strvector_size(&enames);
  DELEA(&g, "hook1");
  DELEA(&g, "hook2"); 
  DELEA(&g, "label");
  igraph_cattribute_list(&g, 0,0,0,0,&enames,0);
  if (igraph_strvector_size(&enames) != i-3) {
    return 16;
  }
  
  /* Set vertex attributes */
  SETVAN(&g, "y", 0, -1);
  SETVAN(&g, "y", 1, 2.1);
  if (VAN(&g, "y", 0) != -1 || 
      VAN(&g, "y", 1) != 2.1) {
    return 17;
  }
  SETVAS(&g, "id", 0, "foo");
  SETVAS(&g, "id", 1, "bar");
  if (strcmp(VAS(&g, "id", 0), "foo") ||
      strcmp(VAS(&g, "id", 1), "bar")) {
    return 18;
  }

  /* Set edge attributes */
  SETEAN(&g, "weight", 2, 100.0);
  SETEAN(&g, "weight", 0, -100.1);
  if (EAN(&g, "weight", 2) != 100.0 ||
      EAN(&g, "weight", 0) != -100.1) {
    return 19;
  }
  SETEAS(&g, "color", 2, "RED");
  SETEAS(&g, "color", 0, "Blue");
  if (strcmp(EAS(&g, "color", 2), "RED") ||
      strcmp(EAS(&g, "color", 0), "Blue")) {
    return 20;
  }      

  /* Set vector attributes as vector */
  igraph_vector_init(&y, igraph_vcount(&g));
  igraph_vector_fill(&y, 1.23);
  SETVANV(&g, "y", &y);
  igraph_vector_destroy(&y);
  for (i=0; i<igraph_vcount(&g); i++) {    
    if (VAN(&g, "y", i) != 1.23) {
      return 21;
    }
  }
  igraph_vector_init_seq(&y, 0, igraph_vcount(&g)-1);
  SETVANV(&g, "foobar", &y);
  igraph_vector_destroy(&y);
  for (i=0; i<igraph_vcount(&g); i++) {
    if (VAN(&g, "foobar", i) != i) {
      return 22;
    }
  }  
  
  igraph_strvector_init(&id, igraph_vcount(&g));
  for (i=0; i<igraph_vcount(&g); i++) {
    snprintf(str, sizeof(str)-1, "%li", i);
    igraph_strvector_set(&id, i, str);
  }
  SETVASV(&g, "foo", &id);
  igraph_strvector_destroy(&id);
  for (i=0; i<igraph_vcount(&g); i++) {
    printf("%s ", VAS(&g, "foo", i));
  }
  printf("\n");
  igraph_strvector_init(&id, igraph_vcount(&g));
  for (i=0; i<igraph_vcount(&g); i++) {
    snprintf(str, sizeof(str)-1, "%li", i);
    igraph_strvector_set(&id, i, str);
  }
  SETVASV(&g, "id", &id);
  igraph_strvector_destroy(&id);
  for (i=0; i<igraph_vcount(&g); i++) {
    printf("%s ", VAS(&g, "id", i));
  }
  printf("\n");  
  
  /* Set edge attributes as vector */
  igraph_vector_init(&y, igraph_ecount(&g));
  igraph_vector_fill(&y, 12.3);
  SETEANV(&g, "weight", &y);
  igraph_vector_destroy(&y);
  for (i=0; i<igraph_ecount(&g); i++) {    
    if (EAN(&g, "weight", i) != 12.3) {
      return 23;
    }
  }
  igraph_vector_init_seq(&y, 0, igraph_ecount(&g)-1);
  SETEANV(&g, "foobar", &y);
  igraph_vector_destroy(&y);
  for (i=0; i<igraph_ecount(&g); i++) {
    if (VAN(&g, "foobar", i) != i) {
      return 24;
    }
  }  
  
  igraph_strvector_init(&id, igraph_ecount(&g));
  for (i=0; i<igraph_ecount(&g); i++) {
    snprintf(str, sizeof(str)-1, "%li", i);
    igraph_strvector_set(&id, i, str);
  }
  SETEASV(&g, "foo", &id);
  igraph_strvector_destroy(&id);
  for (i=0; i<igraph_ecount(&g); i++) {
    printf("%s ", EAS(&g, "foo", i));
  }
  printf("\n");
  igraph_strvector_init(&id, igraph_ecount(&g));
  for (i=0; i<igraph_ecount(&g); i++) {
    snprintf(str, sizeof(str)-1, "%li", i);
    igraph_strvector_set(&id, i, str);
  }
  SETEASV(&g, "color", &id);
  igraph_strvector_destroy(&id);
  for (i=0; i<igraph_ecount(&g); i++) {
    printf("%s ", EAS(&g, "color", i));
  }
  printf("\n");    

  /* Delete all remaining attributes */
  DELALL(&g);
  igraph_cattribute_list(&g, &gnames, &gtypes, &vnames, &vtypes, &enames, &etypes);
  if (igraph_strvector_size(&gnames) != 0 ||
      igraph_strvector_size(&vnames) != 0 ||
      igraph_strvector_size(&enames) != 0) {
    return 25;
  }

  /* Destroy */
  igraph_vector_destroy(&gtypes);
  igraph_vector_destroy(&vtypes);
  igraph_vector_destroy(&etypes);  
  igraph_strvector_destroy(&gnames);
  igraph_strvector_destroy(&vnames);
  igraph_strvector_destroy(&enames);

  igraph_destroy(&g);

  return 0;
}
void igraph_i_graphml_sax_handler_end_document(void *state0) {
  struct igraph_i_graphml_parser_state *state=
    (struct igraph_i_graphml_parser_state*)state0;
  long i, l;
  int r;
  igraph_i_attribute_record_t idrec, eidrec;
  const char *idstr="id";
  igraph_bool_t already_has_vertex_id=0, already_has_edge_id=0;

  if (!state->successful) return;

  if (state->index<0) {

    igraph_vector_ptr_t vattr, eattr, gattr;
    long int esize=igraph_vector_ptr_size(&state->e_attrs);
    const void **tmp;
    r=igraph_vector_ptr_init(&vattr, 
			     igraph_vector_ptr_size(&state->v_attrs)+1);
    if (r) {
      igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, r);
      igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
      return;
    }
    IGRAPH_FINALLY(igraph_vector_ptr_destroy, &vattr);
    if (igraph_strvector_size(&state->edgeids) != 0) {
      esize++;      
    }
    r=igraph_vector_ptr_init(&eattr, esize);
    if (r) {
      igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, r);
      igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
      return;
    }
    IGRAPH_FINALLY(igraph_vector_ptr_destroy, &eattr);
    r=igraph_vector_ptr_init(&gattr, igraph_vector_ptr_size(&state->g_attrs));
    if (r) {
      igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, r);
      igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file");
      return;
    }
    IGRAPH_FINALLY(igraph_vector_ptr_destroy, &gattr);

    for (i=0; i<igraph_vector_ptr_size(&state->v_attrs); i++) {
      igraph_i_graphml_attribute_record_t *graphmlrec=
	VECTOR(state->v_attrs)[i];
      igraph_i_attribute_record_t *rec=&graphmlrec->record;

      /* Check that the name of the vertex attribute is not 'id'.
	 If it is then we cannot the complimentary 'id' attribute. */
      if (! strcmp(rec->name, idstr)) {
	already_has_vertex_id=1;
      }

      if (rec->type == IGRAPH_ATTRIBUTE_NUMERIC) {
	igraph_vector_t *vec=(igraph_vector_t*)rec->value;
	long int origsize=igraph_vector_size(vec);
	long int nodes=igraph_trie_size(&state->node_trie);
	igraph_vector_resize(vec, nodes);
	for (l=origsize; l<nodes; l++) {
	  VECTOR(*vec)[l]=IGRAPH_NAN;
	}
      } else if (rec->type == IGRAPH_ATTRIBUTE_STRING) {
	igraph_strvector_t *strvec=(igraph_strvector_t*)rec->value;
	long int origsize=igraph_strvector_size(strvec);
	long int nodes=igraph_trie_size(&state->node_trie);
	igraph_strvector_resize(strvec, nodes);
	for (l=origsize; l<nodes; l++) {
	  igraph_strvector_set(strvec, l, "");
	}
      }
      VECTOR(vattr)[i]=rec;
    }
    if (!already_has_vertex_id) {
      idrec.name=idstr;
      idrec.type=IGRAPH_ATTRIBUTE_STRING;
      tmp=&idrec.value;
      igraph_trie_getkeys(&state->node_trie, (const igraph_strvector_t **)tmp);
      VECTOR(vattr)[i]=&idrec;
    } else {
      igraph_vector_ptr_pop_back(&vattr);
      IGRAPH_WARNING("Could not add vertex ids, "
		     "there is already an 'id' vertex attribute");
    }

    for (i=0; i<igraph_vector_ptr_size(&state->e_attrs); i++) {
      igraph_i_graphml_attribute_record_t *graphmlrec=
	VECTOR(state->e_attrs)[i];
      igraph_i_attribute_record_t *rec=&graphmlrec->record;

      if (! strcmp(rec->name, idstr)) {
	already_has_edge_id=1;
      }

      if (rec->type == IGRAPH_ATTRIBUTE_NUMERIC) {
	igraph_vector_t *vec=(igraph_vector_t*)rec->value;
	long int origsize=igraph_vector_size(vec);
	long int edges=igraph_vector_size(&state->edgelist)/2;
	igraph_vector_resize(vec, edges);
	for (l=origsize; l<edges; l++) {
	  VECTOR(*vec)[l]=IGRAPH_NAN;
	}
      } else if (rec->type == IGRAPH_ATTRIBUTE_STRING) {
	igraph_strvector_t *strvec=(igraph_strvector_t*)rec->value;
	long int origsize=igraph_strvector_size(strvec);
	long int edges=igraph_vector_size(&state->edgelist)/2;
	igraph_strvector_resize(strvec, edges);
	for (l=origsize; l<edges; l++) {
	  igraph_strvector_set(strvec, l, "");
	}
      }
      VECTOR(eattr)[i]=rec;
    }
    if (igraph_strvector_size(&state->edgeids) != 0) {
      if (!already_has_edge_id) {
	long int origsize=igraph_strvector_size(&state->edgeids);
	eidrec.name=idstr;
	eidrec.type=IGRAPH_ATTRIBUTE_STRING;
	igraph_strvector_resize(&state->edgeids, 
				igraph_vector_size(&state->edgelist)/2);
	for (; origsize < igraph_strvector_size(&state->edgeids); origsize++) {
	  igraph_strvector_set(&state->edgeids, origsize, "");
	}
	eidrec.value=&state->edgeids;
	VECTOR(eattr)[(long int)igraph_vector_ptr_size(&eattr)-1]=&eidrec;
      } else {
	igraph_vector_ptr_pop_back(&eattr);
	IGRAPH_WARNING("Could not add edge ids, "
		       "there is already an 'id' edge attribute");
      }
    }

    for (i=0; i<igraph_vector_ptr_size(&state->g_attrs); i++) {
      igraph_i_graphml_attribute_record_t *graphmlrec=
	VECTOR(state->g_attrs)[i];
      igraph_i_attribute_record_t *rec=&graphmlrec->record;
      if (rec->type == IGRAPH_ATTRIBUTE_NUMERIC) {
	igraph_vector_t *vec=(igraph_vector_t*)rec->value;
	long int origsize=igraph_vector_size(vec);
	igraph_vector_resize(vec, 1);
	for (l=origsize; l<1; l++) {
	  VECTOR(*vec)[l]=IGRAPH_NAN;
	}
      } else if (rec->type == IGRAPH_ATTRIBUTE_STRING) {
	igraph_strvector_t *strvec=(igraph_strvector_t*)rec->value;
	long int origsize=igraph_strvector_size(strvec);
	igraph_strvector_resize(strvec, 1);
	for (l=origsize; l<1; l++) {
	  igraph_strvector_set(strvec, l, "");
	}
      }
      VECTOR(gattr)[i]=rec;
    }
    
    igraph_empty_attrs(state->g, 0, state->edges_directed, &gattr);
    igraph_add_vertices(state->g, igraph_trie_size(&state->node_trie),
			&vattr);
    igraph_add_edges(state->g, &state->edgelist, &eattr);

    igraph_vector_ptr_destroy(&vattr);
    igraph_vector_ptr_destroy(&eattr);
    igraph_vector_ptr_destroy(&gattr);
    IGRAPH_FINALLY_CLEAN(3);     
  }

  igraph_i_graphml_destroy_state(state);
}
예제 #10
0
VALUE cIGraph_initialize(int argc, VALUE *argv, VALUE self){

  igraph_t *graph;
  igraph_vector_t edge_v;
  VALUE vertex;
  VALUE directed;
  VALUE edges;
  VALUE attrs;
  VALUE v_ary;
  int vertex_n = 0;
  int current_vertex_id;
  int i;

  igraph_vector_ptr_t vertex_attr;
  igraph_vector_ptr_t edge_attr;

  igraph_i_attribute_record_t v_attr_rec;
  v_attr_rec.name  = "__RUBY__";
  v_attr_rec.type  = IGRAPH_ATTRIBUTE_PY_OBJECT;
  v_attr_rec.value = (void*)rb_ary_new();

  igraph_i_attribute_record_t e_attr_rec;
  e_attr_rec.name  = "__RUBY__";
  e_attr_rec.type  = IGRAPH_ATTRIBUTE_PY_OBJECT;
  e_attr_rec.value = (void*)rb_ary_new();

  rb_scan_args(argc,argv,"12", &edges, &directed, &attrs);

  //Initialize edge vector
  IGRAPH_FINALLY(igraph_vector_destroy,&edge_v);
  IGRAPH_FINALLY(igraph_vector_ptr_destroy,&vertex_attr);
  IGRAPH_FINALLY(igraph_vector_ptr_destroy,&edge_attr);

  IGRAPH_CHECK(igraph_vector_init_int(&edge_v,0));

  IGRAPH_CHECK(igraph_vector_ptr_init(&vertex_attr,0));
  IGRAPH_CHECK(igraph_vector_ptr_init(&edge_attr,0));

  Data_Get_Struct(self, igraph_t, graph);

  v_ary = rb_ary_new();

  if(!directed)
    IGRAPH_CHECK(igraph_to_undirected(graph,IGRAPH_TO_UNDIRECTED_COLLAPSE));

  //Loop through objects in edge Array
  for (i=0; i<RARRAY_LEN(edges); i++) {
    vertex = RARRAY_PTR(edges)[i];
    if(rb_ary_includes(v_ary,vertex)){
      //If @vertices includes this vertex then look up the vertex number
      current_vertex_id = NUM2INT(rb_funcall(v_ary,rb_intern("index"),1,vertex));
    } else {
      //Otherwise add to the list of vertices
      rb_ary_push(v_ary,vertex);
      current_vertex_id = vertex_n;
      vertex_n++;
      
      //Add object to list of vertex attributes
      rb_ary_push((VALUE)v_attr_rec.value,vertex);
      
    }
    IGRAPH_CHECK(igraph_vector_push_back(&edge_v,current_vertex_id));
    if (i % 2){
      if (attrs != Qnil){
	rb_ary_push((VALUE)e_attr_rec.value,RARRAY_PTR(attrs)[i/2]);
      } else {
	rb_ary_push((VALUE)e_attr_rec.value,Qnil);
      }
    }
  }

  IGRAPH_CHECK(igraph_vector_ptr_push_back(&vertex_attr, &v_attr_rec));
  IGRAPH_CHECK(igraph_vector_ptr_push_back(&edge_attr,   &e_attr_rec));

  if(igraph_vector_size(&edge_v) > 0){
    IGRAPH_CHECK(igraph_add_vertices(graph,vertex_n,&vertex_attr));
    IGRAPH_CHECK(igraph_add_edges(graph,&edge_v,&edge_attr));
  }

  igraph_vector_destroy(&edge_v);
  igraph_vector_ptr_destroy(&vertex_attr);
  igraph_vector_ptr_destroy(&edge_attr);

  IGRAPH_FINALLY_CLEAN(3);

  return self;

}
예제 #11
0
int ggen_transform_add(igraph_t *g, enum ggen_transform_t t)
{
	igraph_vector_t vertices;
	igraph_vector_t degrees;
	igraph_vector_t edges;
	unsigned int i,vcount,ssize;
	int err;

	if(g == NULL)
		return 1;

	vcount = igraph_vcount(g);

	err = igraph_vector_init(&vertices,vcount);
	if(err) return 1;

	err = igraph_vector_init(&degrees,vcount);
	if(err) goto error_id;

	/* find degree of each vertex, in if new source is wanted. */
	err = igraph_degree(g,&degrees,igraph_vss_all(),
		(t==GGEN_TRANSFORM_SOURCE)?IGRAPH_IN:IGRAPH_OUT,0);
	if(err) goto error;

	/* only sources or sinks are of interest */
	ssize = 0;
	for(i = 0; i < vcount; i++)
		if(VECTOR(degrees)[i] == 0)
			VECTOR(vertices)[ssize++] = i;

	/* we have something to do */
	if(ssize > 0)
	{
		err = igraph_add_vertices(g,1,NULL);
		if(err) goto error;

		err = igraph_vector_init(&edges,ssize*2);
		if(err) goto error;

		for(i = 0; i < ssize; i++)
		{
			if(t == GGEN_TRANSFORM_SOURCE)
			{
				VECTOR(edges)[2*i] = vcount;
				VECTOR(edges)[2*i+1] = VECTOR(vertices)[i];
			}
			else
			{
				VECTOR(edges)[2*i] = VECTOR(vertices)[i];
				VECTOR(edges)[2*i+1] = vcount;
			}
		}

		err = igraph_add_edges(g,&edges,NULL);
		igraph_vector_destroy(&edges);
		if(err) goto error;
	}
error:
	igraph_vector_destroy(&degrees);
error_id:
	igraph_vector_destroy(&vertices);
	return err;
}