예제 #1
0
int main(int argc, char **argv)
{
  char *inputFilename;
  char *outputFilename;

  if (!parseCmdLineSimple(argc, argv, "ss", &inputFilename, &outputFilename))
  {
    printf("Usage: mtx2gr input output\n");
    exit(1);
  }

  int nVertices;
  std::vector<int> srcs;
  std::vector<int> dsts;
  std::vector<int> edgeValues;
  loadGraph(inputFilename, nVertices, srcs, dsts, &edgeValues);
  printf("Read input file with %d vertices and %zd edges\n", nVertices, dsts.size());

  printf("Converting to CSR\n");
  std::vector<int> offsets(nVertices + 1);
  std::vector<int> csrDsts(dsts.size());
  std::vector<int> sortIndices(dsts.size());
  std::vector<int> sortedEdgeValues(dsts.size());
  edgeListToCSR<int>(nVertices, dsts.size(), &srcs[0], &dsts[0]
    , &offsets[0], &csrDsts[0], &sortIndices[0]);
  for (size_t i = 0; i < sortIndices.size(); ++i)
    sortedEdgeValues[i] = edgeValues[sortIndices[i]];

  printf("writing output\n");
  writeGraph_binaryCSR(outputFilename, nVertices, dsts.size()
    , &offsets[0], &csrDsts[0], &sortedEdgeValues[0]);
}
int MainWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QMainWindow::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0:
            loadGraph();
            break;
        case 1:
            saveGraph();
            break;
        case 2:
            saveGraphVrml();
            break;
        case 3:
            setDrawGraph((*reinterpret_cast< bool(*)>(_a[1])));
            break;
        case 4:
            setDrawHirarchy((*reinterpret_cast< bool(*)>(_a[1])));
            break;
        default:
            ;
        }
        _id -= 5;
    }
    return _id;
}
예제 #3
0
void testProgram()
{
	FILE *file1 = fopen("input.in", "r");
	FILE *file2 = fopen("output.data", "w");

	graph *G = loadGraph(file1);
	int **testcost = alocateMemoryForCost(G->noOfVertices);
	int *testpredecesors = allocateMemoryForPredecesors(G->noOfVertices);


	BellmanFord(G, 0, testcost, testpredecesors);
	for (int i = 0; i < G->noOfVertices; i++)
	{
		fprintf_s(file2, "%d\n", testcost[1][i]);
	}
	fclose(file1);
	fclose(file2);
	file1 = fopen("output.data", "r");
	file2 = fopen("result.txt", "r");

	if (compareFiles(file1, file2))
	{
		printf_s("Test succeded!\n");
	}
	else
	{
		printf_s("Test failed!\n");
	}

}
예제 #4
0
파일: main.cpp 프로젝트: Aura-Nicoleta/ADS
int main(){
//-----------------------------------------Loading and Printing the Graph------------------------------
	graph *G;

	FILE* f;
	f = fopen("cost.txt", "r");
	G = loadGraph(f);

	printf("\n Edges and Costs: \n");

	for(int i = 0; i < G->noOfEdges; i++){
		printf("[%d <-> %d] --- cost = %d \n", G->pEdge[i].source , G->pEdge[i].destination, G->pEdge[i].weight);
	}
//------------------------------------------------END---------------------------------------------------
//-----------------------------------------------PRIM---------------------------------------------------
	int V[50][50], Q[50], H[50], n = 0, r = 0, k=0;			//----|  Data for Prim's Alg
	// ce reprezinta???

	k = prim(V, Q, H, n, r, G);

	printf("\n Prim: \n");

	displayMST(H, n);

	printf("\n MST cost = %d \n", k);
//-----------------------------------------------END------------------------------------------------------
//---------------------------------------------Kruskall---------------------------------------------------

	int p, m, L[20];										//----|  Data for Kruskall's Alg

	krusk(n, m, L, G);
//-----------------------------------------------END-----------------------------------------------------
	system("pause");

}
예제 #5
0
ClusterEvaluator::ClusterEvaluator(Graph* g, hmap_uint_suint* cls, 
          hmap_uint_suint* nc, std::vector<std::string>* clbs, uint vnn) {
     loadGraph(g);
     loadClusters(cls, nc);
     cluster_labels = clbs;
     v_num_nodes = vnn;
}
예제 #6
0
파일: prim.c 프로젝트: magic003/notes
Graph* init() {
    Graph* g = newGraph(0);

    loadGraph(g, "mst.txt");

    parent = (int*) malloc((g->nvertices+1) * sizeof(int));
    int i;
    for (i = 0; i <= g->nvertices; i++) {
        parent[i] = -1;
    }

    return g;
}
예제 #7
0
void driverProgram(char *inputFile, char *outputFile)
{
	FILE *fin = fopen(inputFile, "r");
	FILE *fout = fopen(outputFile, "w");
	int source;
	graph *G = loadGraph(fin);
	int **cost = alocateMemoryForCost(G->noOfVertices);
	int *predecesors = allocateMemoryForPredecesors(G->noOfVertices);

	


	printf_s("Give the source vertex:");
	scanf_s("%d", &source);
	BellmanFord(G, source, cost, predecesors);
	for (int i = 0; i < G->noOfVertices; i++)
	{
		fprintf_s(fout, "%d\n", cost[1][i]);
	}

	while (true)
	{
		int destination;
		printf_s("Give the vertex to which you want to reconstruct the path:");
		scanf_s("%d", &destination);
		if (cost[1][destination] == infinite)
		{
			printf_s("there is no path to %d from %d\n", destination, source);
		}
		else if (cost[1][destination] == minfinite)
		{
			printf_s("it is a negative cycle cannot display path\n");
		}
		else
		{
			reconstructPath(source, destination, G, predecesors);
		}

		printf_s("Continue? \n1.Yes\n0.No\n");
		int dummy;
		scanf_s("%d",&dummy);
		if (dummy == 0)
		{
			break;
		}
	}
	fclose(fin);
	fclose(fout);
}
예제 #8
0
void QGraphWidget::open() {
    QSettings settings("LITIS", "GEM++gui");
    QString root;
    #if defined(LINUX)
        root = "/home";
    #elif defined(WIN32)
        root = "C:\\";
    #endif
    QString graphPath = settings.value(QString("%1_graph_path").arg(typeNames[type_]), root).toString();
    QString fileName = QFileDialog::getOpenFileName(this, "Open a graph file", graphPath, "Graph *.gml/*.gxl (*.gml *.gxl)");
    if(!fileName.isEmpty()) {
        loadGraph(fileName);
        settings.setValue(QString("%1_graph_path").arg(typeNames[type_]), QFileInfo(fileName).path());
    }
}
예제 #9
0
LoadGraphWindow::LoadGraphWindow( QWidget* parent )
{
	setModal( true );
	resize( 600,250 );
	setWindowTitle( tr( "Load graph from database" ) );

	loadButton = createButton( tr( "Load" ), SLOT( loadGraph() ) );
	removeButton = createButton( tr( "Remove" ), SLOT( removeGraph() ) );
	renameButton = createButton( tr( "Rename" ), SLOT( renameGraph() ) );

	QPushButton* cancelButton = new QPushButton( tr( "Cancel" ) );
	cancelButton->setFocusPolicy( Qt::NoFocus );
	connect( cancelButton, SIGNAL( clicked() ), this, SLOT( close() ) );

	numberOfGraphs = new QLabel;

	graphList << tr( "ID" ) << tr( "Name" ) << tr( "No. of layouts" ) << tr( "No. of nodes" ) << tr( "No. of edges" );
	graphsTable = new QTableWidget( this );
	graphsTable->setSelectionBehavior( QAbstractItemView::SelectRows );
	graphsTable->setRowCount( 0 );
	graphsTable->setColumnCount( 5 );
	graphsTable->setHorizontalHeaderLabels( graphList );
	graphsTable->horizontalHeader()->setResizeMode( 0, QHeaderView::Interactive );
	graphsTable->horizontalHeader()->setResizeMode( 1, QHeaderView::Stretch );
	graphsTable->horizontalHeader()->setResizeMode( 2, QHeaderView::ResizeToContents );
	graphsTable->horizontalHeader()->setResizeMode( 3, QHeaderView::ResizeToContents );
	graphsTable->horizontalHeader()->setResizeMode( 4, QHeaderView::ResizeToContents );
	graphsTable->verticalHeader()->hide();
	graphsTable->setShowGrid( true );

	createGraphTable();

	QHBoxLayout* buttonsLayout = new QHBoxLayout;
	buttonsLayout->addStretch();
	buttonsLayout->addWidget( loadButton );
	buttonsLayout->addWidget( renameButton );
	buttonsLayout->addWidget( removeButton );
	buttonsLayout->addWidget( cancelButton );

	QGridLayout* mainLayout = new QGridLayout;
	mainLayout->addWidget( graphsTable, 3, 0, 1, 3 );
	mainLayout->addWidget( numberOfGraphs, 4, 0, 1, 3 );
	mainLayout->addLayout( buttonsLayout, 5, 0, 1, 3 );
	setLayout( mainLayout );
}
예제 #10
0
파일: bandwith.c 프로젝트: magic003/notes
int main(int argc, char* argv[]) {
    Graph* g = newGraph(0);
    loadGraph(g, "graph.txt");

    int* result = (int*) malloc(g->nvertices * sizeof(int));

    bandwidth(g,result);

    printf("Bandwidth: ");
    int i;
    for(i=0; i<g->nvertices; i++) {
        printf("%d ", result[i]);
    }
    printf("\n");

    deleteGraph(g);
    return 0;
}
예제 #11
0
bool processMenu(int choice) {
	string name;
	switch(choice-1) {
		case CREATE_NODE: 
			createNode();
			break;
		case DELETE_NODE:
			deleteNode();
			break;
		case CREATE_RELATION:
			createRelation();
			break;
		case DELETE_RELATION:
			deleteRelation();
			break;
		case SAVE_GRAPH:
			saveGraph();
			break;
		case LOAD_GRAPH:
			loadGraph();
			break;
		case DISPLAY_GRAPH:
			displayGraph();
			break;
		case RUN_PRIM:
			runPrim();
			break;
		case QUIT:
			return true;
			break;
		default:
			cout << "Invalid input" << endl;
			cout << endl;
			break;
	}
	return false;
}
void run(context_t& ctx, bool directed) {
    bool is_master = ctx.dc.procid() == 0;
    timer_start(is_master);

#ifdef GRANULA
    granula::operation powergraphJob("PowerGraph", "Id.Unique", "Job", "Id.Unique");
    granula::operation loadGraph("PowerGraph", "Id.Unique", "LoadGraph", "Id.Unique");
    if(is_master) {
        cout<<powergraphJob.getOperationInfo("StartTime", powergraphJob.getEpoch())<<endl;
        cout<<loadGraph.getOperationInfo("StartTime", loadGraph.getEpoch())<<endl;
    }
#endif

    // process parmaeters
    global_directed = directed;

    // load graph
    timer_next("load graph");
    graph_type graph(ctx.dc);
    load_graph(graph, ctx);
    graph.finalize();

#ifdef GRANULA
    if(is_master) {
        cout<<loadGraph.getOperationInfo("EndTime", loadGraph.getEpoch())<<endl;
    }
#endif

    // start engine
    timer_next("initialize engine");
    graphlab::omni_engine<triangle_count> engine(ctx.dc, graph, "synchronous", ctx.clopts);
    engine.signal_all();

#ifdef GRANULA
    granula::operation processGraph("PowerGraph", "Id.Unique", "ProcessGraph", "Id.Unique");
    if(is_master) {
        cout<<processGraph.getOperationInfo("StartTime", processGraph.getEpoch())<<endl;
    }
#endif

    // run algorithm
    timer_next("run algorithm");
    engine.start();

#ifdef GRANULA
    if(is_master) {
        cout<<processGraph.getOperationInfo("EndTime", processGraph.getEpoch())<<endl;
    }
#endif

#ifdef GRANULA
    granula::operation offloadGraph("PowerGraph", "Id.Unique", "OffloadGraph", "Id.Unique");
    if(is_master) {
        cout<<offloadGraph.getOperationInfo("StartTime", offloadGraph.getEpoch())<<endl;
    }
#endif

    // print output
    if (ctx.output_enabled) {
        timer_next("print output");
        vector<pair<graphlab::vertex_id_type, vertex_data_type> > data;
        collect_vertex_data(graph, data, is_master);

        for (size_t i = 0; i < data.size(); i++) {
            (*ctx.output_stream) << data[i].first << " " << data[i].second.clustering_coef << endl;
        }
    }

    timer_end();

#ifdef GRANULA
    if(is_master) {
        cout<<offloadGraph.getOperationInfo("EndTime", offloadGraph.getEpoch())<<endl;
        cout<<powergraphJob.getOperationInfo("EndTime", powergraphJob.getEpoch())<<endl;
    }
#endif

}
예제 #13
0
파일: do_bienen.c 프로젝트: lindknecht/bees
int main(int argc, char **argv)
{
	double B_max = 10, w = 0.5, b = 5, p_star = 0.05, p = 0.7, 
	 theta = 0.3, a = 0.001, z = 0, use2Opt = 1, use2OptE = 1, 
	 repeat = 1, z_max = 1000;
	struct tag {
		char *tag;
		double *var;
	} tags[] = {
		{"B_max", &B_max}, 
		{"w", &w}, 
		{"b", &b}, 
		{"p_star", &p_star}, 
		{"p", &p}, 
		{"theta", &theta}, 
		{"a", &a},
		{"z", &z}, 
		{"use2Opt", &use2Opt}, 
		{"use2OptE", &use2OptE},
		{"repeat", &repeat},
		{"z_max", &z_max},
		{NULL, NULL}
	};

	if (argc != 3) {
		fprintf(stderr, "SYNTAX: %s <filename of graph> <filename of control file>\n", argv[0]);
		exit(1);
	}
	if (loadGraph(argv[1]))
		printf("File %s not found.\n", argv[1]);
	header();
	FILE *f = fopen(argv[2], "r");
	if (f == NULL) {
		printf("Cannot open file %s.\n", argv[2]);
		exit(1);
	}
	char buffer[256];
	while (fgets(buffer, 255, f)) {
		char this_tag[256], this_experiment[256];
		char *bp = buffer;
		while ((*bp != 0) && isspace(*bp))
			bp++;
		if (*bp == 0)
			continue;
		if (strncmp(buffer, "run", 3) == 0) {
			sscanf(buffer, "%s %s", this_tag, this_experiment);
			for (int run = 0; run < repeat; run++) {
				fprintf(stderr, "Run %s (%d / %.0lf)\n", this_experiment, run, repeat);
				initialize();
				double time_used = 0;
				for (int z = 1; z <= z_max; z++) {
					double start_time = get_utime();
					iteration(B_max, w, b, p_star, p, theta, a, (int) z, (int) use2Opt, (int) use2OptE);
					time_used += get_utime() - start_time;
					output((int) use2Opt, (int) use2OptE, w, p_star, p, theta, a, b, (int) B_max, 
					 run, z, time_used, this_experiment);
				}
			}
		} else {
			char this_tag[256];
			double this_value;
			
			sscanf(buffer, "%s %lf", this_tag, &this_value);
			struct tag *t;
			for (t = tags; t->tag; t++) {
				if (strcmp(this_tag, t->tag) == 0) {
					*t->var = this_value;
					break;
				}
			}
			if (!t->tag) {
				fprintf(stderr, "Unrecognized tag %s in control file.\n", this_tag);
				exit(1);
			}
		}
	}

	return 0;
}
예제 #14
0
파일: pageRank.cpp 프로젝트: DDEMB/ADS
int main()
{
	FILE* fin = NULL;
	char c, fileName[20];
	int i;

	do
	{
		printf ("\n    <<<<<<<<<<<<<<<<<<<<<<   MENU   >>>>>>>>>>>>>>>>>>>>>>\n\n");
		printf ("\n    1. Generate a new test file AND display it;");
		printf ("\n    2. Generate a new test file WITHOUT displaying it;\n");
		printf ("\n    3. Load an existing test file AND display it;");
		printf ("\n    4. Load an existing test file WITHOUT displaying it;\n");
		printf ("\n    5. Exit the program.\n");

		printf ("\n Choose an option ('c' to clear screen): ");
		scanf (" %c", &c);

		if (c == 'c')
		{
			for (i = 0; i < 100; i++)
			{
				printf ("\n");
			}
		}

		else if (c == '1')
		{
			printf ("\nGenerate a new test file and display it. Input its name:\n");
			scanf ("%s", fileName);
			graphGenerator (fileName);
			displayGraph (fin, fileName);
		}

		else if (c == '2')
		{
			printf ("\nGenerate a new test file. Input its name:\n");
			scanf ("%s", fileName);
			graphGenerator (fileName);
		}

		else if (c == '3')
		{
			printf ("\nLoad an existing test file and display it. Input its name:\n");
			scanf ("%s", fileName);
			displayGraph (fin, fileName);
		}

		else if (c == '4')
		{
			printf ("\nLoad an existing test file. Input its name:\n");
			scanf ("%s", fileName);
		}

		else if (c == '5')
		{
			exit(1);
		}

		else
		{
			printf ("\nThe key you pressed is not a valid option. Please press 1, 2, 3, 4 or 5.\n\n");
		}

		if (c == '1' || c == '2' || c == '3' || c == '4')
		{
			fin = fopen (fileName, "r");

			if (fin == NULL) 
			{
				perror ("\n\tError opening file\n");
			}
			else
			{
				int nodes;
				double beta;

				printf ("\nDefine the damping factor (best between 0.8 and 0.9): ");
				scanf ("%lf", &beta);

				double **M = loadGraph (fin, nodes);
				M = createMatrix_M (M, nodes, beta);

				double **B = createMatrix_B (nodes, beta);
				M = matrixSum (M, B, nodes);
				deallocMatrix <double> (B, nodes);

				//
				printf("\n Matrix A = M + B \n");
				displayMatrix (M, nodes, nodes);
				//

				powerIteration (M, nodes, beta);

				fclose (fin);
			}
		}

	} while (true);

	return 0;
}
int main(int argc, char *argv[])
{
  string inputFile = "./dissect/as/as20000102.dimacs";  
  string outputFile = "./graph";
  bool display_output = true;
  bool write_graph_files = true;
  bool gro_calc = false;
  bool ncp_calc = false;
  int core_to_start = -1;
  //User input

  for(int i=1;i<argc;i++)
    {
      stringstream ss;
      if(strcmp(argv[i], "-i")==0)
	inputFile = argv[i+1];

      if(strcmp(argv[i], "-o")==0)
	outputFile = argv[i+1];

      if(strcmp(argv[i], "-silent")==0)
	display_output = false;

      if(strcmp(argv[i], "-nofile")==0)
	write_graph_files = false;

      if(strcmp(argv[i], "-gromov")==0)
	gro_calc = true;
   
      if(strcmp(argv[i], "-ncp")==0)
	ncp_calc = true;

      if(strcmp(argv[i], "-core")==0)
	core_to_start = atoi(argv[i+1]);
    }

  ////Default values

  if(inputFile.length()==0)
    {
      cerr<<"You must provide an input file\n";
      exit(EXIT_FAILURE);
    }

  //////////////////////////////////////////////////////////////
  //-----------------------------------------------------------
  //////////////////////////////////////////////////////////////

  Graph G_o = loadGraph(inputFile,"\t",false);
  Graph G = connected(G_o);
 
  vector<int> core;
  vector<v_size_t> distances;
  vector<v_size_t> num_paths;

  v_size_t N_paths,D,n;
  int max_core = 0;
  double A_d, A_p;

  A_d = 0;
  A_p = 0;

  D       = 0;
  N_paths = 0;
  n       = num_vertices(G);

  graph_traits<Graph>::vertex_iterator vi, vie;
  property_map<Graph, vertex_index_t>::type index = get(vertex_index,G);

  core = k_core(G);
  

  for(int i=0;i<core.size();++i)
    {
      if(core[i] > max_core)
	max_core = core[i];
    }
  
  if(core_to_start<=0)
    core_to_start = max_core;

  for(tie(vi,vie) = vertices(G); vi != vie; ++vi)
    {
      Vert v = *vi;
      //cout<<G[v].core_num<<" ";
      BFS_source_all(v,G,distances,num_paths);

      size_t size = distances.size();

      for(size_t i=0;i<size;++i)
	{

	  if(distances[i] > D)
	    D = distances[i];

	  A_p += num_paths[i] * distances[i];
	  A_d += distances[i];
	  N_paths += num_paths[i];
	}
    }

  A_p /= N_paths;
  A_d /= (pow(n, 2) - n);

  cout<<"Max Core: "<<max_core<<" The diameter: "<<D<<" The avg. path: "<<A_p<<" The avg. dist: "<<A_d<<" The size: "<<n<<"\n";
  cout.flush();

  string periph_diam   = outputFile;
  string collapse_diam = outputFile;
  string core_diam     = outputFile;

  ofstream file_periph;
  ofstream file_collapse;
  ofstream file_core;

  periph_diam.append("_periph_diam.out");
  collapse_diam.append("_collapse_diam.out");
  core_diam.append("_core_diam.out");

  file_periph.open(periph_diam.c_str());
  file_collapse.open(collapse_diam.c_str());
  file_core.open(core_diam.c_str());
  
  file_periph<<(max_core+1)<<"\t"<<D<<"\t"<<A_d<<"\t"<<A_p<<"\n";
  file_collapse<<(max_core+1)<<"\t"<<D<<"\t"<<A_d<<"\t"<<A_p<<"\n";
  file_core<<(max_core+1)<<"\t"<<0<<"\t"<<0<<"\t"<<"\n";

  Graph G_core, G_periph, G_collapse;
  vector<v_size_t> core_list;
  vector<v_size_t> periph_list;

  for(int i=1;i<=max_core;i++)
    periph_list.push_back(i);


  for(int i=max_core; i>0; --i)
    {

      core_list.push_back(i);
      periph_list.pop_back();

      if(i<=core_to_start)
	{
	  G_core     = get_k_shells(core_list,G);
	  G_periph   = get_k_shells(periph_list,G);
	  G_collapse = collapse_core(i,G); 

	  stringstream ssperiph;
	  ssperiph<<i;
	  string outputPeriph   = outputFile;
	  string outputCore     = outputFile;
	  string outputCollapse = outputFile;
	  outputPeriph.append("_periph_");
	  outputCore.append("_core_");
	  outputCollapse.append("_collapse_");
	  outputPeriph.append(ssperiph.str());
	  outputCore.append(ssperiph.str());
	  outputCollapse.append(ssperiph.str());
	  outputPeriph.append(".dimacs");
	  outputCore.append(".dimacs");
	  outputCollapse.append(".dimacs");

	  if(write_graph_files)
	    {
	      write_dimacs(G_periph,outputPeriph);
	      write_dimacs(G_core,outputCore);
	      write_dimacs(G_collapse,outputCollapse);
	    }
	  //Need to make something that checks number of connected components, and then runs this on each one.  Just because the whole graph is connected doesn't mean the cores have to be.

	  D = 0;
	  v_size_t n_core = num_vertices(G_core);
	  A_p = 0;
	  A_d = 0;
	  N_paths = 0;
	  for(tie(vi,vie) = vertices(G_core); vi != vie; ++vi)
	    {
	      Vert v = *vi;

	      BFS_source_all(v,G_core,distances,num_paths);

	      size_t size = distances.size();

	      for(size_t j=0;j<size;++j)
		{

		  if(distances[j] > D)
		    D = distances[j];

		  A_p += num_paths[j]*distances[j];
		  A_d += distances[j];
		  N_paths += num_paths[j];
		}
	    }

	  A_p /= N_paths;

	  vector<bool> found(n_core,false);
	  v_size_t current_comp = 0;
	  vector<v_size_t> comp_size;
	  vector<v_size_t> component(n_core);

	  index = get(vertex_index,G_core);

	  for(tie(vi,vie)=vertices(G_core);vi!=vie;++vi)
	    {
	      Vert v = *vi;
	      v_size_t vind = index[v];
	      v_size_t current_comp_size = 0;

	      if(!found[vind])
		{
		  BFS_vertices_found(v,G_core,found,current_comp,component,current_comp_size);
		  comp_size.push_back(current_comp_size);
		  ++current_comp;
		}
	    }
	  if(display_output)
	    cout<<"\nCore: "<<i<<"\n";

	  double sum_of_components = 0;
      
	  if(display_output)
	    cout<<"# of components in core: "<<comp_size.size()<<" Size of core: "<<num_vertices(G_core)<<"\n";

      
	  for(size_t j=0;j<comp_size.size();++j)
	    {
	      if(comp_size[j] > (num_vertices(G_core)/10.0) && display_output)
		cout<<"Component "<<j<<" Size: "<<comp_size[j]<<"\n";

	      sum_of_components += pow(comp_size[j],2)-comp_size[j];
	    }
      

	  A_d /= sum_of_components;

	  if(display_output)
	    cout<<"The diameter: "<<D<<" The avg. path: "<<A_p<<" The avg. dist: "<<A_d<<" The size: "<<n_core<<"\n";

	  file_core<<(i)<<"\t"<<D<<"\t"<<A_d<<"\t"<<A_p<<"\n";
	  
	  cout.flush();

	  //////////////////////////////////////////////	
	  if(gro_calc && n_core>4)
	    {
	      G_core = connected(G_core);
	      
	      //cout<<"Vertices in new core: "<<num_vertices(G_core)<<"\n";

	      BFS_distance(G_core);
	    
	      vector< vector<double> > delta = calc_gromov(G_core,D);
	      stringstream ss,tt;

	      ss<<i;
	      unsigned long numQuad = 0;
	      for(size_t j=0;j<delta.size();++j)
		numQuad += delta[j][0];

	      ofstream outGrom;
	      string outputFileGrom = outputFile;
	      outputFileGrom.append("_gromov_core_");
	      outputFileGrom.append(ss.str());
	      outputFileGrom.append(".txt");
	      outGrom.open(outputFileGrom.c_str());

	      tt<<i;

	      ofstream outAvg;
	      string outputFileAvg = outputFile;
	      outputFileAvg.append("_avg_distr_core_");
	      outputFileAvg.append(tt.str());
	      outputFileAvg.append(".txt");
	      outAvg.open(outputFileAvg.c_str());
	      outGrom<<"#Note: Hyperbolicity only calculated on largest component of core\n";
	      outGrom<<"#Column format: \n";
	      outGrom<<"#Max Length in Quadruplet\tNumber of Quadruplets\n";

	      for(size_t j=0;j<delta.size();++j)
		{
		  outGrom<<"#~\t"<<j+1<<"\t"<<delta[j][0]<<"\n";
		}

	      outGrom<<"#Column format: \n";
	      outGrom<<"#Delta\tPercent of quadruplets for each length\n";

	      for(size_t j=1;j<delta[0].size();j++)
		{
		  //size_t size = delta[i].size();	

	  
		  outGrom<<(j-1)/2.0<<"\t";
		  for(size_t k=0;k<delta.size();k++)
		    {
		      if(delta[k][0]!=0)
			(delta[k])[j] = (delta[k])[j]/(delta[k])[0];
	  
	      
		      outGrom<<delta[k][j]<<"\t";
		    }
		  outGrom<<"\n";
	  
		}

	      for(size_t k=0;k<delta.size();k++)
		{
		  double avg = 0;
		  for(size_t j=1;j<delta[k].size();j++)
		    {
		      avg += delta[k][j]*(j-1)/2.0;
		    }
		  outAvg<<k+1<<"\t"<<avg<<"\n";
		}

	      outGrom.close();
	      outAvg.close();
	    }

	  ////////////////////////////////////////////////////////



	  v_size_t n_periph = num_vertices(G_periph);

	  found.assign(n_periph,false);
	  current_comp = 0;
	  comp_size.clear();
	  component.assign(n_periph,0);

	  index = get(vertex_index,G_periph);

	  for(tie(vi,vie)=vertices(G_periph);vi!=vie;++vi)
	    {
	      Vert v = *vi;
	      v_size_t vind = index[v];
	      v_size_t current_comp_size = 0;

	      if(!found[vind])
		{
		  BFS_vertices_found(v,G_periph,found,current_comp,component,current_comp_size);
		  comp_size.push_back(current_comp_size);
		  ++current_comp;
		}
	    }


	  if(display_output)
	    cout<<"# of components in periphery: "<<comp_size.size()<<" Size of periphery: "<<num_vertices(G_periph)<<"\n";

	  for(size_t j=0;j<comp_size.size();++j)
	    if(comp_size[j] > (num_vertices(G_periph)/10.0) && display_output)
	      cout<<"Component "<<j<<" Size: "<<comp_size[j]<<"\n";



	  G_periph = connected(G_periph);
	  n_periph = num_vertices(G_periph);

	  /////////////////////////////////////////////////////////////////////
	  ////////////////////////////////////////////////////////////////////
	  //ncp
	  //////////////////////////////////////////////////////////////////////

	  // v_size_t max_community = n_periph/2;
	  // vector<double> ncp_periph = ncp_calc(G_periph,max_community,1,.001,false);

	  // stringstream ssncp;
	  // ssncp<<i;
	  // string outputNcp = outputFile;
	  // ofstream output_file_ncp;
	  // outputNcp.append("_ncp_periph_");
	  // outputNcp.append(ssncp.str());
	  // outputNcp.append(".txt");

	  // output_file_ncp.open(outputNcp.c_str());

	  // for(v_size_t k=0; k<max_community;++k)
	  // 	output_file_ncp<<(k+1)<<"\t"<<ncp_periph[k]<<"\n";

	  // output_file_ncp.close();


	  // string label = outputFile;
	  // label.append(" ncp plot");

	  // string title = outputFile;
	  // title.append(" NCP Plot");

	  // vector<int> int_to_vec;
	  // int_to_vec.push_back(2);

	  // vector<string> string_to_vec;
	  // string_to_vec.push_back(label);

	  // string outputPNG = "";
	  // outputPNG.append(outputFile);
	  // outputPNG.append("_ncp_periph_");
	  // outputPNG.append(ssncp.str());
	  // outputPNG.append("_ncp_plot");

	  // produce_loglog_plot(outputNcp,outputPNG,outputPNG,int_to_vec,string_to_vec,title,"Community size", "Conductance","",false);


	  // /////////////////////////////////////////////////////////////////////////
	  // /////////////////////////////////////////////////////////////////////////
	  D = 0;
	  A_p = 0;
	  A_d = 0;
	  N_paths = 0;
	  for(tie(vi,vie) = vertices(G_periph); vi != vie; ++vi)
	    {
	      Vert v = *vi;

	      BFS_source_all(v,G_periph,distances,num_paths);

	      size_t size = distances.size();

	      for(size_t j=0;j<size;++j)
		{

		  if(distances[j] > D)
		    D = distances[j];

		  A_p += num_paths[j]*distances[j];
		  A_d += distances[j];
		  N_paths += num_paths[j];
		}
	    }

	  A_p /= N_paths;
	  A_d /= (pow(n_periph,2)-n_periph);
	


	  if(gro_calc && n_periph>4)
	    {
	      BFS_distance(G_periph);
	    
	      vector< vector<double> > delta = calc_gromov(G_periph,D);
	      stringstream ss,tt;

	      ss<<i;
	      unsigned long numQuad = 0;
	      for(size_t j=0;j<delta.size();++j)
		{
		  numQuad += delta[j][0];
		}

	      

	      ofstream outGrom;
	      string outputFileGrom = outputFile;
	      outputFileGrom.append("_gromov_periph_");
	      outputFileGrom.append(ss.str());
	      outputFileGrom.append(".txt");
	      outGrom.open(outputFileGrom.c_str());
	      
	      tt<<i;

	      ofstream outAvg;
	      string outputFileAvg = outputFile;
	      outputFileAvg.append("_avg_distr_periph_");
	      outputFileAvg.append(tt.str());
	      outputFileAvg.append(".txt");
	      outAvg.open(outputFileAvg.c_str());
	      outGrom<<"#Column format: \n";
	      outGrom<<"#Max Length in Quadruplet\tNumber of Quadruplets\n";

	      
	      for(size_t j=0;j<delta.size();++j)
		{
		  outGrom<<"#~\t"<<j+1<<"\t"<<delta[j][0]<<"\n";
		}

	      outGrom<<"#Column format: \n";
	      outGrom<<"#Delta\tPercent of quadruplets for each length\n";
	     
	      for(size_t j=1;j<delta[0].size();j++)
		{
		  //size_t size = delta[i].size();	

	  
		  outGrom<<(j-1)/2.0<<"\t";
		  for(size_t k=0;k<delta.size();k++)
		    {
		      if(delta[k][0]!=0)
			(delta[k])[j] = (delta[k])[j]/(delta[k])[0];
	  
	      
		      outGrom<<delta[k][j]<<"\t";
		    }
		  outGrom<<"\n";	  
		}

	      for(size_t k=0;k<delta.size();k++)
		{
		  double avg = 0;
		  for(size_t j=1;j<delta[k].size();j++)
		    {
		      avg += delta[k][j]*(j-1)/2.0;
		    }
		  outAvg<<k+1<<"\t"<<avg<<"\n";
		}

	      outGrom.close();
	      outAvg.close();
	    }

	  //cout<<"\nCore: "<<i<<"\n";
	  if(display_output)      
	    cout<<"The diameter: "<<D<<" The avg. path: "<<A_p<<" The avg. dist: "<<A_d<<" The size: "<<n_periph<<"\n";

	  file_periph<<(i)<<"\t"<<D<<"\t"<<A_d<<"\t"<<A_p<<"\n";

	  cout.flush();
	  //////////////////////////////////////////////////
	  //////////////////////////////////////////////////

	  D = 0;
	  v_size_t n_collapse = num_vertices(G_collapse);
	  A_p = 0;
	  A_d = 0;
	  N_paths = 0;
	  for(tie(vi,vie) = vertices(G_collapse); vi != vie; ++vi)
	    {
	      Vert v = *vi;

	      BFS_source_all(v,G_collapse,distances,num_paths);

	      size_t size = distances.size();

	      for(size_t j=0;j<size;++j)
		{

		  if(distances[j] > D)
		    D = distances[j];

		  A_p += num_paths[j]*distances[j];
		  A_d += distances[j];
		  N_paths += num_paths[j];
		}
	    }

	  A_p /= N_paths;

	  found.assign(n_collapse,false);
	  current_comp = 0;
	  comp_size.clear();
	  component.assign(n_collapse,0);

	  index = get(vertex_index,G_collapse);

	  for(tie(vi,vie)=vertices(G_collapse);vi!=vie;++vi)
	    {
	      Vert v = *vi;
	      v_size_t vind = index[v];
	      v_size_t current_comp_size = 0;

	      if(!found[vind])
		{
		  BFS_vertices_found(v,G_collapse,found,current_comp,component,current_comp_size);
		  comp_size.push_back(current_comp_size);
		  ++current_comp;
		}
	    }


	  sum_of_components = 0;
      
	  if(display_output)
	    cout<<"# of components in collapse: "<<comp_size.size()<<" Size of collapse: "<<num_vertices(G_collapse)<<"\n";

	  cout.flush();
	  for(size_t j=0;j<comp_size.size();++j)
	    {
	      if(comp_size[j] > (num_vertices(G_collapse)/10.0) && display_output)
		cout<<"Component "<<j<<" Size: "<<comp_size[j]<<"\n";

	      sum_of_components += pow(comp_size[j],2)-comp_size[j];
	    }
      

	  A_d /= sum_of_components;

	  if(display_output)
	    cout<<"The diameter: "<<D<<" The avg. path: "<<A_p<<" The avg. dist: "<<A_d<<" The size: "<<n_collapse<<"\n";

	  file_collapse<<(i)<<"\t"<<D<<"\t"<<A_d<<"\t"<<A_p<<"\n";

	  cout.flush();
	  //////////////////////////////////////////////	
	  if(gro_calc && n_collapse>4)
	    {
	      BFS_distance(G_collapse);
	    
	      vector< vector<double> > delta = calc_gromov(G_collapse,D);
	      stringstream ss,tt;

	      ss<<i;
	      unsigned long numQuad = 0;
	      for(size_t j=0;j<delta.size();j++)
		numQuad += delta[j][0];

	      ofstream outGrom;
	      string outputFileGrom = outputFile;
	      outputFileGrom.append("_gromov_collapse_");
	      outputFileGrom.append(ss.str());
	      outputFileGrom.append(".txt");
	      outGrom.open(outputFileGrom.c_str());

	      tt<<i;

	      ofstream outAvg;
	      string outputFileAvg = outputFile;
	      outputFileAvg.append("_avg_distr_collapse_");
	      outputFileAvg.append(tt.str());
	      outputFileAvg.append(".txt");
	      outAvg.open(outputFileAvg.c_str());
	      outGrom<<"#Column format: \n";
	      outGrom<<"#Max Length in Quadruplet\tNumber of Quadruplets\n";

	      for(size_t j=0;j<delta.size();j++)
		{
		  outGrom<<"#~\t"<<j+1<<"\t"<<delta[j][0]<<"\n";
		}

	      outGrom<<"#Column format: \n";
	      outGrom<<"#Delta\tPercent of quadruplets for each length\n";

	      for(size_t j=1;j<delta[0].size();j++)
		{
		  //size_t size = delta[i].size();	

	  
		  outGrom<<(j-1)/2.0<<"\t";
		  for(size_t k=0;k<delta.size();k++)
		    {
		      if(delta[k][0]!=0)
			(delta[k])[j] = (delta[k])[j]/(delta[k])[0];
	  
	      
		      outGrom<<delta[k][j]<<"\t";
		    }
		  outGrom<<"\n";
	  
		}

	      for(size_t k=0;k<delta.size();k++)
		{
		  double avg = 0;
		  for(size_t j=1;j<delta[k].size();j++)
		    {
		      avg += delta[k][j]*(j-1)/2.0;
		    }
		  outAvg<<k+1<<"\t"<<avg<<"\n";
		}

	      outGrom.close();
	      outAvg.close();
	    }
	}
      ////////////////////////////////////////////////////////

    }
    

  file_periph.close();
  file_collapse.close();
  file_core.close();
    
    
  return(0);
}
예제 #16
0
int main(){
	FILE *fp = fopen("graph.in", "r");
	FILE *fRand = fopen("graph2.in", "r");
	
	int y, tests ,source, count=0, cnt=0, destination;
	int distance[N] = {0}, predecesor[N] = {0};
	int distanceSimple[N], distanceMinHeap[N], distanceBruteForce[N];
	bool ok;
	clock_t beginSD,endSD,beginDMH, endDMH, beginDBF, endDBF;
	struct Graph* G = (Graph*) malloc(sizeof(Graph));
	struct MinHeap *mh = (MinHeap*) malloc(sizeof(MinHeap));
	Init(mh);
	
	do{
		puts("________________________________\n");
		puts("Choose an option: \n");
		puts("1. Load the Graph\n2. 2. Print the Graph\n3. Distance between two nodes\n4. Path between two nodes\n5. Dijkstra\n6. Dijkstra with Min Heap\n7. Brute Force Dijkstra\n8. Compare results\n9. Exit");
		puts("________________________________\n");
		scanf("%d", &y);

		switch(y){

		case 1:
			G = loadGraph(fp);
			system("cls");
			break;
		case 2:
			printGraph(G);
			system("cls");
			break;
		case 3://Get shortest distance between two nodes
			puts("Give the source node: ");
			scanf("%d", &source);
			printf("Give the destination node: ");
			scanf("%d", &destination);				
			getDistance(G, source, destination , mh, distance, predecesor);
			for(int i = 0; i <= G->V; i ++){
				predecesor[i] = 0;
				distance[i] = 0;
			}
			system("cls");
			break;
		case 4://Get shortest path between two nodes
			puts("Give the source node: ");
			scanf("%d", &source);
			printf("Give the destination node: ");
			scanf("%d", &destination);		
			if( !hasNegativeCosts(G)){//preprocessing
				puts("\nThe Graph is valid for applying Dijkstra.");
				DijkstraMH(G, source, mh, distance, predecesor);				
				getPath(G, source, destination, mh, distance, predecesor);
				for(int i = 0; i <= G->V; i ++){
					predecesor[i] = 0;
					distance[i] = 0;
				}
			}
			else
				puts("\nThe Graph is invalid for applying Dijkstra.\nOne or more of the edges has negative cost.");
			getch();
			system("cls");
			break;
		case 5://Simple Dijkstra
			puts("Give the source: ");
			scanf("%d", &source);
			if( !hasNegativeCosts(G)){//preprocessing
				puts("\nThe Graph is valid for applying Dijkstra.");
				Dijkstra(G, source, distance, predecesor);
				printResult(G, distance, source);
				for(int i = 0;i <= G->V; i ++){
					predecesor[i] = 0;
					distance[i] = 0;
				}
			}
			else
				puts("\nThe Graph is invalid for applying Dijkstra.\nOne or more of the edges has negative cost.");
			getch();
			system("cls");
			break;
		case 6://Dijkstra with Min Heap
			puts("Give the source: ");
			scanf("%d", &source);
			if( !hasNegativeCosts(G)){//preprocessing
				puts("\nThe Graph is valid for applying Dijkstra.");
				DijkstraMH(G, source, mh, distance, predecesor);	
				printResult(G, distance, source);
				for(int i = 0;i <= G->V; i ++){
					predecesor[i] = 0;
					distance[i] = 0;
				}
			}
			else
				puts("\nThe Graph is invalid for applying Dijkstra.\nOne or more of the edges has negative cost.");
			getch();
			system("cls");
			break;
		case 7://brute force Dijkstra
			puts("Give the source: ");
			scanf("%d", &source);
			if( !hasNegativeCosts(G)){//preprocessing
				puts("\nThe Graph is valid for applying Dijkstra.");
				bruteForceDijkstra(source, G, mh, 0, 0, 0, count, distance, predecesor);
				printResult(G, distance, source);
			}
			for(int i = 0; i <= G->V; i ++){
				predecesor[i] = 0;
				distance[i] = 0;
			}
			getch();
			system("cls");
			break;
		case 8://compare results
			puts("Give the source: ");
			scanf("%d", &source);
			
			assert((beginSD = clock())!=-1);
			Dijkstra(G, source, distanceSimple, predecesor);
			endSD = clock();

			beginDMH = clock();
			DijkstraMH(G, source, mh, distanceMinHeap, predecesor);	
			endDMH = clock();
			
			beginDBF = clock();
			bruteForceDijkstra(source, G, mh, 0, 0, 0, count, distanceBruteForce, predecesor);
			endDBF = clock();

			if(compare(G, distanceSimple, distanceMinHeap, distanceBruteForce)){
				puts("\nThe three algorithms provided the same results that are:");
				
				printf("\nSimple Dijkstra:\n"); 
				printResult(G, distanceSimple, source);
				printf("\nDijkstra with Min Heap:\n"); 
				printResult(G, distanceMinHeap, source);
				printf("\nBrute Force Dijkstra:\n"); 
				printResult(G, distanceBruteForce, source);
			}
			getch();

		case 9:
			return 0;
		}
	}while(y != 9);

	return (0);
}
예제 #17
0
/********************************************************************
* Other constructor
********************************************************************/
NamingGame::NamingGame(std::string filename){
     loadGraph(filename);
}
예제 #18
0
ClusterEvaluator::ClusterEvaluator(Graph* g) {
     loadGraph(g);
}
예제 #19
0
파일: scc03.c 프로젝트: isayyuhh-s/ucsc-cs
int main (int argc, char** argv)
{
   if (argc == 1)
   {
      printf("Usage: graph01 input.data\n");
      return 0;
   }

   /* CREATE ADJACENCY LISTS */
   int n = 0, m = 0, result;
   IntList* adj_list; IntList* transpose_list;
   adj_list = loadGraph(&n, &m, argc, argv);
   transpose_list = fix_graph(transposeGraph(adj_list, n), n);

   int discoverTime1[n], finishTime1[n], finishStk[n], parent1[n], counter = 1, stackspot = n;
   memset(discoverTime1, 0, n * sizeof(int));
   memset(finishTime1, 0, n * sizeof(int));
   memset(finishStk, 0, n * sizeof(int));
   memset(parent1, -1, n * sizeof(int));

   int discoverTime2[n], finishTime2[n], dfstRoot[n], parent2[n];
   memset(discoverTime2, 0, n * sizeof(int));
   memset(finishTime2, 0, n * sizeof(int));
   memset(parent2, -1, n * sizeof(int));
   memset(dfstRoot, 0, n * sizeof(int));

   for (int i = 1; i <= n; i++)
      result = dfsTrace1(adj_list, discoverTime1, finishTime1, finishStk, parent1, &counter, i, &stackspot);
   counter = 1;
   for (int i = 0; i < n; i++)
      result = dfsTrace2(transpose_list, discoverTime2, finishTime2, finishStk, parent2, &counter, finishStk[i], dfstRoot, finishStk[i]);
   result = result;


   /* ADJACENCY LIST */
   printf("\n__Adjacency List__\n");

   // print list
   print_list(adj_list, n, m);

   // display stack
   printf("stack: [");
   for (int i = 0; i < n; i++)
   {
      if (i != 0)
         printf(", ");
      printf("%d", finishStk[i]);
   }
   printf("]\n\n");

   // table
   printf("vertex |dtime |ftime |parent\n");
   printf("-------|------|------|------\n");
   for (int i = 0; i < n; i++)
      printf("%7d|%6d|%6d|%6d\n", i + 1, discoverTime1[i], finishTime1[i], parent1[i]);
   printf("\n\n");


   /* TRANSPOSE LIST */
   printf("__Transpose List__\n");

   // print transpose list
   print_list(transpose_list, n, m);
   printf("\n");

   // table
   printf("vertex |dtime |ftime |parent |root\n");
   printf("-------|------|------|-------|-----\n");
   for (int i = 0; i < n; i++)
      printf("%7d|%6d|%6d|%7d|%5d\n", i + 1, discoverTime2[i], finishTime2[i], parent2[i], dfstRoot[i]);
   printf("\n");


   /* FREE MEMORY */
   for (int i = 1; i <= n; i++)
   {
      for (IntList ptr = adj_list[i]; ptr != intNil; ptr = intRest(ptr));
      for (IntList ptr = transpose_list[i]; ptr != intNil; ptr = intRest(ptr));
   }
   free(adj_list);
   free(transpose_list);
}
int main(void) {
    int i,err;
    pthread_t threads[THREADSNUM];
    TopForumList* topForumList;
    Cpm** cpm;
    Gn **gn = NULL;

    //initialize poolList,mutex and conditionVariable
    poolList = createPoolList();
    pthread_mutex_init(&mtx,0);
    pthread_cond_init(&cond_nonempty,0);
    //create THREADSNUM threads
    for(i=0;i<THREADSNUM;i++)
        if( (err = pthread_create(&threads[i],NULL,threadFunction,NULL))){
            perror2("pthread_create",err);
            exit(1);
        }
    //load graph using files
    int bucketsNumber = 10;
    int bucketSize = 5;
    Graph* g = loadGraph(bucketsNumber, bucketSize);

	topForumList = PreperationFunction(g,NUMBER_OF_TOP_N_FORUMS);
    //printTopNForums(topForumList);
    int cliqueSize[2] = {3, 4};
    cpm =  computeCPMResults(g,cliqueSize,topForumList);
    validateCPMResults(cpm);

    double modularityMax = DBL_MAX;
    gn = computeGNResults(g,modularityMax,topForumList);
    validateGNResults(gn);

    free_memory(topForumList,cpm,gn);//free memory function

/*  Graph* g = createTempGraph();
    EdgeList* edgeList = createEdgeList();
    //find all GraphEdges
    findEdges(g,edgeList);
    //calculate communities of graph
    //printf("%d",DBL_MAX);
    double modularityMax = DBL_MAX;
    Community* communities = GirvanNewman(modularityMax,g,edgeList);
    for(int i=0;i<g->communitiesInfo->communitiesNum;i++){
        for(int j=0;j<communities[i].numberOfGeneralMembers;j++)
            printf("member:%d\n",communities[i].generalMembers[j]);
        fflush(stdout);
        printf("\n");
    }

    destroyGraph(g);
*/
     //wait until all threads are done with their jobs
    for(i=0;i<THREADSNUM;i++)
        if( (err = pthread_join(threads[i],NULL)) ){
            perror2("pthread_join",err);
            exit(1);
        }
    //destroy mutex and conditionVariable
    free(poolList);
    pthread_cond_destroy(&cond_nonempty);
    pthread_mutex_destroy(&mtx);

    return EXIT_SUCCESS;
}
예제 #21
0
int main()
{
	int i;
	double cl;
	kase = 1;

	// The final output will be written in the outFile and the initial input will be read from inFile
	std::string outFile = "output.txt";
	std::string inFile = "input.txt";

	// Create the output file
	FILE *fpout = fopen(outFile.c_str(), "wt");
	fclose(fpout);

	// Open the input file
	FILE *fpin = fopen(inFile.c_str(), "rt");

	// Reading each of the cases, There may be two types of cases, with 4 parameters, with 5 parameters
	// There may also be comments that starts with #
	while(fgets(buff, 1000, fpin))
	{
		// No data
		if(strlen(buff) == 0)
			continue;
		// Comment
		if(buff[0] == '#')
			continue;
		StringTokenizer token;

		// tokeniize using space
		token.parse(buff, " \n\r");
		std::vector<std::string> vecToken; 
		token.getTokens(vecToken);

		int totParam = vecToken.size();

		// Not enough parameters
		if(totParam < 4)
			continue;

		// First token is the graph file name
		std::string graphFile = vecToken[0];

		// 2nd and 3rd tokens are start and end node id respectively
		int startNode = atoi(vecToken[1].c_str());
		int endNode = atoi(vecToken[2].c_str());

		// 4th Token is the result file for this query
		std::string pathFile = vecToken[3];
		int ind = pathFile.length() - 1;
		while(pathFile[ind] < 32)
		{
			pathFile[ind] = '\0';
			ind--;
		}

		// Load edge information from graph file
		loadGraph(graphFile);

		// Use bidirectional AStar to get the route
		BiDirAStar gdef;
		cl = clock();
		int res = gdef.bidir_astar(edges, edge_count, maxNode, startNode, endNode, &path, &path_count, &err_msg);
		cl = clock() - cl;

		// Write the route in the result file
		write_result(pathFile, res);
		
		// There is an answer file
		if(totParam > 4)
		{
			std::string ansFile = vecToken[4];
			ind = ansFile.length() - 1;
			while(ansFile[ind] < 32)
			{
				ansFile[ind] = '\0';
				ind--;
			}
			// Match and write result in the final output file
			match(pathFile, ansFile, outFile, cl / CLOCKS_PER_SEC);
		}
		else
		{
			// Provide information that the route is generated in path file.
			fpout = fopen(outFile.c_str(), "a+");
			fprintf(fpout, "Case %d: Path Written to file %s", kase, pathFile.c_str());
			fprintf(fpout, "Query Time: %lf sec\n\n", cl / CLOCKS_PER_SEC);
			fclose(fpout);
		}
		kase++;
		free(path);
		delete [] edges;
	}
	return 0;
}
예제 #22
0
/********************************************************************
* Other constructor
********************************************************************/
Scan::Scan(uint t, std::string filename) {
    num_clusters = 0;
    type = t;
    loadGraph(filename);
}
예제 #23
0
int main_part2(void) {
    //firstly execute a test for centrality metrics on small graphs
    int m = 2;
    int c = 3;

    testBetweennessCentrality(m, c);

    testClosenessCentrality(m, c);

    //small example for trust graph estimation
    testTidalTrust(m, c);


    /*create graph from file*/
    int bucketsNumber = 5;
    int bucketSize = 10;
    Graph* g = loadGraph(bucketsNumber, bucketSize);

    //graph metrics calls

    //plot the graph degree distribution
    degreeDistribution(g, false);

    int diam = diameter(g);
    CHECKINT("Graph diameter", diam, 14);

    double avgPthLgth = averagePathLength(g);
    CHECKDOUBLE("Graph average path length", avgPthLgth, 5.0753);

    int ccNumber = numberOfCCs(g);
    CHECKINT("Graph number of components ", ccNumber, 1);

    int maximumCC = maxCC(g);
    CHECKINT("Graph maximum connected component ", maximumCC, 111);

    double dense = density(g);
    CHECKDOUBLE("Graph density ", dense, 0.073);

    /*
     * WRONG CALCULATIONS - only considering neighbors and not multi-step paths!
    int closenessIds[5] = {		1734,   38,   8899,  3501,   75};
    float closenessIdsRes[5] = {0.109, 0.090, 0.072, 0.045, 0.009};
    for (i = 0; i < 5; ++i) {
        int nodeID = closenessIds[i];
        Node* node = lookupNode(nodeID, g);
        double closCentrty = closenessCentrality(node, g);
        CHECKDOUBLE("Graph closeness centrality ", closCentrty, closenessIdsRes[i]);
    }
	*/

    int i, k;
    int betweennessIds[5] = {       1734,   38,     8899,   9900,   75};
    float betweennessIdsRes[5] = {  0.306,  0.053,  0.018,  0.005,  0.000};

    for (i = 0; i < 5; ++i) {
        int nodeID = betweennessIds[i];
        Node* node = lookupNode(nodeID, g);
        double betwCentrty = betweennessCentrality(node, g);
        CHECKDOUBLE("Graph betweenness centrality ", betwCentrty, betweennessIdsRes[i]);
    }

    //graph queries calls
    // Query 1 //
    Matches* match;
    Node *dateNode = lookupNode(3755, g);
    int commonInterests = 1, ageDiff = 30, acquaintanceHops = 3, matchesNum = 1;
    match = matchSuggestion(dateNode, commonInterests, acquaintanceHops, ageDiff, matchesNum, g);

    //match result : 7107 - work_at_organization: 1650
    //get first pair's person ids
    int id1 = getMatch(0, match);

    CHECKINT("Query 1: Date result 1st id", id1, 7107);
    delete match;

    // Query 2 //
    //estimate stalkers graph with closeness centrality
    Graph* stalkersGraphCloseCentr;
    int stalkersNum = 7, likesNumber = 1, centralityMode = 1;
    Stalkers* stalkersCloseCentr = new Stalkers(stalkersNum);
    stalkersGraphCloseCentr = getTopStalkers(stalkersNum, likesNumber, centralityMode, g, stalkersCloseCentr);

    int stalkersResultsIds[] = {347, 495, 7768, 8354, 8403, 8899, 9633};
    int stalkerResultSize = 7;
    int stalkerID;
    int counter = 0;
    for (int i = 0; i < stalkersNum; ++i) {
        stalkerID = getStalkerID(i, stalkersCloseCentr);
        if (stalkerID != -1) {
            ++counter;
        }
        for (k = 0; k < stalkerResultSize; ++k) {
            if (stalkersResultsIds[k] == stalkerID) {
                break;
            }
        }
        if (k == stalkerResultSize) {
            printf("You wrongly labeled person with id %d as Stalker\n", stalkerID);
        }
    }
    CHECKINT("Query 2: Stalker closeness results size", stalkerResultSize, counter);

    //run metrics on stalker-graph
    stalkersGraphRunMetrics(stalkersGraphCloseCentr);

    //estimate stalkers graph with betweenness centrality
    Graph* stalkersGraphBetwCentr;
    Stalkers* stalkersBetwCentr = new Stalkers(stalkersNum);
    centralityMode = 2;
    stalkersGraphBetwCentr = getTopStalkers(stalkersNum, likesNumber, centralityMode, g, stalkersBetwCentr);

    counter = 0;
    for (int i = 0; i < stalkersNum; ++i) {
        stalkerID = getStalkerID(i, stalkersBetwCentr);
        if (stalkerID != -1) {
            ++counter;
        }
        for (k = 0; k < stalkerResultSize; ++k) {
            if (stalkersResultsIds[k] == stalkerID) {
                break;
            }
        }
        if (k == stalkerResultSize) {
            printf("You wrongly labeled person with id %d as Stalker\n", stalkerID);
        }
    }

    CHECKINT("Query 2: Stalker betweenness results size", stalkerResultSize, counter);


    //run metrics on stalker-graph
    stalkersGraphRunMetrics(stalkersGraphBetwCentr);


    // Query 3 - Correct//
    int trendsNum = 4;
    //allocate result tables before calling query and pass them as parameters
    char** womenTrends;
    womenTrends = (char**) malloc(trendsNum * sizeof (char*));
    char** menTrends;
    menTrends = (char**) malloc(trendsNum * sizeof (char*));
    findTrends(trendsNum, g, &womenTrends, &menTrends);


    printf("Top Women - Men Trends\n");
    int j;
    char* menTrendsResults[4] = {"Sun_Yat-sen", "Constantine_the_Great","Sigmund_Freud", "Hussein_of_Jordan"}; //IDS: {417,11622,468,1398}
    char* womenTrendsResults[4] = {"Adolf_Hitler", "Chiang_Kai-shek", NULL, NULL}; //IDS: {138,416,null,null}

    int counterW = 0, counterM = 0;

    for (j = 0; j < 4; ++j) {
        if (menTrends[j] != NULL) {
            ++counterM;

            for (k = 0; k < 4; ++k) {

                if (strcmp(menTrends[j], menTrendsResults[k]) == 0) {
                    break;
                }
            }
            if (k == 4) {
                printf("You wrongly labeled tag with %s as top trend\n", menTrends[j]);
            }
        }
    }
    CHECKINT("Query 3: Mens Trends result size", 4, counterM);


    for (j = 0; j < 4; ++j) {
        if (womenTrends[j] != NULL) {
            ++counterW;

            for (k = 0; k < 2; ++k) {

                if (strcmp(womenTrends[j], womenTrendsResults[k]) == 0) {
                    break;
                }
            }
            if (k == 2) {
                printf("You wrongly labeled tag with %s as top trend\n", menTrends[j]);
            }
        }
    }

    CHECKINT("Query 3: Women Trends result size", 2, counterW);


    cout<<"_____________________________________"<<endl;
    // Query 4 //
//    int forumID = 34680;
    char *forumName = "Wall of Xiomara Fernandez";

    Graph *trustGraph = buildTrustGraph(forumName, g);

    int trustANodeId = 30;
    int trustBNodeId = 9805;
    int trustCNodeId = 9700;
    Node *ta = lookupNode(trustANodeId, trustGraph);
    assert(ta != NULL);
    Node *tb = lookupNode(trustBNodeId, trustGraph);
    assert(tb != NULL);
    Node *tc = lookupNode(trustCNodeId, trustGraph);
    assert(tc != NULL);

    double trustAB;
    trustAB = estimateTrust(ta, tb,  trustGraph);
    printf("Trust between nodes (%d,%d) is %f\n", trustANodeId, trustBNodeId, trustAB);
    CHECKDOUBLE("Trust: (30,9805) ", trustAB, 0.134);
    cout<<"_____________________________________"<<endl;
    double trustAC;
    trustAC = estimateTrust(ta,tc,  trustGraph);
    printf("Trust between nodes (%d,%d) is %f\n", trustANodeId, trustCNodeId, trustAC);
    CHECKDOUBLE("Trust: (30,9700) ", trustAC, 0.15);

    return EXIT_SUCCESS;
}