Пример #1
0
//-----------------------------------------------------------------------------
// read a frame from physical layer
void read_datalink(CnetEvent event, CnetTimerID timer, CnetData data) {
    int link;
    DL_FRAME frame;
    size_t len = PACKET_HEADER_SIZE+DATAGRAM_HEADER_SIZE +
            DL_FRAME_HEADER_SIZE + MAX_MESSAGE_SIZE;
    CHECK(CNET_read_physical(&link, (char *)&frame, &len));

    // compare the checksum
    size_t dtg_len = len - DL_FRAME_HEADER_SIZE;
    uint16_t checksum = frame.checksum;
    uint16_t checksum_to_compare = CNET_ccitt((unsigned char *)&frame.data, dtg_len);
    if (checksum_to_compare != checksum) {
        return;
    }

    //read a datagram to network layer
    read_network(link, dtg_len, (char*) frame.data);
}
Пример #2
0
int main(int argc, char* argv[])
{
	double time;
	int *prices, *P;
	int source, tail, nodes, arcs;
	int (*network)[2];
	arcs = atoi(argv[1]);
	nodes = atoi(argv[2]);
	network = (int (*)[2])malloc((arcs+nodes)*2*sizeof(int));		//przydzial pamieci dla tablicy z grafem
	read_network("outp", &source, &tail, &nodes, &arcs, network);
	prices = (int*)malloc(nodes*sizeof(int));
	P = (int*)malloc(nodes*sizeof(int));
	auction_search(prices, P, network, nodes, arcs, source, tail);
	time = clock()/CLOCKS_PER_SEC;
	printf("Czas wykonania programu: %f\n", time);
	//for(i = 0; i < nodes; i++) {
	//	printf("%d ", P[i]);
	//}
	//printf("\n");
	return 0;
}
Пример #3
0
void MainWindow::on_tabWidget_tabBarClicked(int index)
{
    switch (index)
    {
        case 0:
                read_omr();
        break;
        case 1:
                read_dac();
        break;
        case 2:

        break;
        case 3:
                read_network();
        break;
        case 4:

        break;
        default:
        break;
    }
}
Пример #4
0
int main()
{
   FILE *fp1,*fp2,*fp3;
   int i,j,q,numhost,count,minth,maxth,time,simtime,m,qtime,*q_time;
   int *nran,*nran2,*hostrate,**hostdrops,zero,rcount;
   char line1[100];
   double wq,avg,maxp,pa,pb,*avg_time;  
    zero=0;
    numhost=0;
    simtime=100;
    wq=0.002;
    minth=5;
    maxth=15;
    maxp=0.02;
    printf(" \n"); 
    printf("          Simple genericRED gateway simulator \n"); 
    printf("                      M. Suzen (c) 2005 -2007 \n"); 
    printf(" \n"); 
    printf(" \n"); 
    printf(" \n"); 
    printf(" \n"); 
    printf(" \n"); 
    hostrate=(int *) malloc(1000*sizeof(int));
    printf("  allocated hostrate \n"); 
    numhost=read_network(hostrate);
    printf("  read network file !\n"); 
     avg_time=(double *) malloc(simtime*sizeof(double));
     q_time=(int *) malloc(simtime*sizeof(int));
     nran=(int *) malloc((simtime+1)*(numhost+1)*sizeof(int));
     nran2=(int *) malloc((numhost+1)*sizeof(int));
     hostdrops=(int **) malloc((simtime+3)*sizeof(int));
     for(i=0;i<=simtime;i++){ 
      hostdrops[i]=(int *) malloc((numhost+3)*sizeof(int));
     }
    printf("  allocated other stuff !! !\n"); 
   for(i=0;i<numhost;i++) {
     printf("%d th hostrate = %d  packets/unit time\n",i,hostrate[i]); 
    }

     /* initilize hostdrops and avg_time */
      for(time=0; time < simtime; time++) {
           avg_time[time]=0;
         for(i=0;i<numhost;i++) {
           hostdrops[time][i]=0; 
          }
       }
     /* core RED algorithm */
          avg=0;
          count=-1;
          qtime=0;
       fp3=fopen("traffic.ntw","w");
           /* Find current queue size or hosts sending packet */
       rcount=0;
           /* randomly pick which hosts are sending packets*/
            get_bin_randoms(nran,(numhost+1)*(simtime+1)); 
	     printf("core RED Algorithm \n");
      for(time=0;time<simtime; time++) {
	     printf("core RED Algorithm time =%d \r",time); 
            q=0;
              sprintf(line1,"%d ",time);
            for(i=0;i<numhost;i++) {
                   nran2[i]=nran[rcount];
                    /* printf("count nran2=%d\n",nran2[i]); */
               if(nran[rcount] == 1) {
                  q=q+hostrate[i];
                  sprintf(line1,"%s%d ",line1,hostrate[i]);
                 } else {
                  sprintf(line1,"%s%d ",line1,zero);
               }
                rcount++;
            }
              fprintf(fp3,"%s\n",line1);
               q_time[time]=q;
               /* printf("Current time = %d QUEUE q=%d\n",time,q); */
             /* loop over each host sending packet */
            for(i=0;i<numhost;i++) {
               /* printf("here nran2=%d\n",nran2[i]); */
               if(nran2[i] == 1) {
                    for(j=0;j<hostrate[i];j++) {
                          if(q != 0) {
                             avg=(1-wq)*avg+wq*q;
                             avg_time[time]=avg;
                        /*   printf("ZERO q= %d time=%d avg_time=%f\n",q,time,avg_time[time]);  */
                            } else {
                             m=time-qtime;
                             avg=pow((1-wq),m)*avg;
                             avg_time[time]=avg;
                         /*printf("time=%d avg_time=%f\n",time,avg_time[time]); */
                           }
                          /*printf("time=%d avg_time=%f\n",time,avg_time[time]); */
                          if(minth <= avg && avg < maxth ) {
                             count++; 
                      /* printf("maxp=%f avg=%f minth=%d maxth=%d\n",maxp,avg,minth,maxth); */
                             pb=maxp*(avg-minth)/(maxth-minth);
                             pa=pb/(1-count*pb);
                                   /* printf("count=%d pb=%f pa=%f \n",count,pb,pa); */
                              if(pa >= 0.015) { 
                               hostdrops[time][i]++; 
                               /* printf("PA dropping: i %d time %d value %d \n",i,time,hostdrops[time][i]); */
                               count=0;
                              }
                           }
                           if(maxth <= avg) {
                               hostdrops[time][i]++; 
                              /* printf("dropping: i %d time %d value %d \n",i,time,hostdrops[time][i]); */
                               count=0;
                             } else {
                               count=-1;
                           } 
                           if(q ==0) {
                              qtime=time;
                           }
                     }
                }  
             }
        }
    fclose(fp3);
    /* Report Host Drops  */
    fp1=fopen("hostdrops.ntw","w");
      for(time=0; time < simtime; time++) {
           sprintf(line1,"%5d",time);
         for(i=0;i<numhost;i++) {
                /* printf("hostdrop=%d \n",hostdrops[time][i]); */
           sprintf(line1,"%s %5d",line1,hostdrops[time][i]);
          }
                /* printf("C line1=%s \n",line1); */
           fprintf(fp1,"%s\n",line1);
       } 
    fclose(fp1);
    /* Report average and current queue size */
    fp2=fopen("queues.ntw","w");
      for(time=0; time < simtime; time++) {
       fprintf(fp2,"%d  %f  %d\n",time,avg_time[time],q_time[time]);
       /* printf("time=%d avg_time=%f\n",time,avg_time[time]);  */
      }
    fclose(fp2);
    /* Free Dynamic Arrays */
   free(nran);
   free(hostrate);
   free(hostdrops);
   free(avg_time);
   free(q_time);
	     printf("\n \n  _ _ _ RED Algorithm  finished \n"); 
    exit(0);
}
Пример #5
0
int main(int argc, char *argv[])
{
  int total, workers;
  int rank, size;
  int len = 100, tag = 200;
  MPI_Request *request;

	double time;
	int *prices, *P, *cost_tab, *fpr;
	int i, j, k, source, tail=1, nodes, arcs;
	int dest, src;
	int *dest_ptr, *src_ptr;
	int (*network)[2], (*network_i)[2];
	clock_t start, end;
	char *filename;

	source = atoi(argv[1]);
	nodes = atoi(argv[1]);
	arcs = atoi(argv[2]);
	filename = argv[3];	

	Result result;
	int request_arg;
	int item, endloop = -1;
	int finalResult = -1;

	int length = 1, m, l, t, index;
	int la, maxla, argmaxla, cost, path_cost = 0;

	network = (int (*)[2])malloc((arcs+nodes)*2*sizeof(int));		//przydzial pamieci dla tablicy z grafem
	network_i = (int (*)[2])malloc((arcs+nodes)*2*sizeof(int));
	read_network(filename, &source, &tail, &nodes, &arcs, network, network_i);

	  MPI_Init(&argc, &argv);
	  MPI_Comm_rank(MPI_COMM_WORLD, &rank);		//identyfikacja procesu
	  MPI_Comm_size(MPI_COMM_WORLD, &size);		//podanie liczby procesów w komunikatorze

  /* Manager */

	  printf("RANK %d SIZE %d\n", rank, size);

  if (rank == 0) {

    /* Allocate and initialize the data */

    workers = size - 1;
	dest_ptr = (int*)malloc(sizeof(int) * workers);
	src_ptr = (int*)malloc(sizeof(int));
	prices = (int*)malloc((nodes+1)*sizeof(int));
    request = malloc(sizeof(MPI_Request) * workers);	//tyle ile workersów
	fpr = (int*)malloc((nodes+1)*sizeof(int));

	start = clock();

	for(i = 0; i <= nodes; ++i)
	{
		fpr[i] = INF;
	}
	
	prices = (int*)malloc((nodes+1)*sizeof(int));
	P = (int*)malloc((nodes+1)*sizeof(int));
	cost_tab = (int*)malloc((nodes+1)*sizeof(int));

	for(i = 0; i <= nodes; i++) {
		P[i] = INF;
		prices[i] = 0;
		cost_tab[i] = 0;
	}

	path_cost =  main_single_auction_search(prices, P, network, network_i, fpr, dest_ptr, src_ptr, request, workers, nodes, arcs, source, tail);

	
	
	end = clock();

    time = ((double) (end - start)) / CLOCKS_PER_SEC;

    printf("Czas wykonania programu: %5.1f [ms]\n", time*1000);
	printf("Dlugosc sciezki: %d\n", path_cost);

	
	
    free(prices);
    free(fpr);
    free(dest_ptr);
    free(src_ptr);
    free(request);
  }

  /* Workers */

  else {
		//printf("::WORKER %d STARTED::", rank);

		prices = (int*)malloc((nodes+1)*sizeof(int));
		P = (int*)malloc((nodes+1)*sizeof(int));
		cost_tab = (int*)malloc((nodes+1)*sizeof(int));

		for(i = 0; i <= nodes; i++) {
			P[i] = INF;
			prices[i] = 0;
			cost_tab[i] = 0;
		}

		t = 0;
		do
		{
			MPI_Recv(&request_arg, 1, MPI_INT, 0, tag + rank, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
			if (request_arg == -1) {
				printf("END MESSAGE\n");
				break;
			}
			path_cost = single_auction_search(prices, P, cost_tab, network, network_i, nodes, arcs, source, request_arg);
			//path_cost = 1;
			result.t = request_arg;
			result.path_cost = path_cost;
			MPI_Send(&result, 2, MPI_INT, 0, tag + rank, MPI_COMM_WORLD);
		} while(result.t < nodes);

    	free(prices);
    	free(P);
    	free(cost_tab);
  }

  MPI_Finalize();
  return 0;
}
Пример #6
0
int main(int argc, char* argv[]) {
    char q[512];
    MYSQL_ROW row;
    MYSQL_RES* res;

    int err = init_network();
    if (err) {
        return err;
    }

    for (int year = 1990; year <= 2011; year++) {
        std::cout << "Querying " << year << "\n";

        snprintf(q, 512, "select count(value) from entries where year=%d and inserted>(select updated from visualizations where name='GAP2' and year=%d)", year, year);
        if (mysql_query(mysql, q)) {
            std::cerr << mysql_error(mysql) << "\n";
            return -2;
        }
        res = mysql_use_result(mysql);
        if ((row = mysql_fetch_row(res)) == 0 || atoi(row[0]) == 0) {
            mysql_free_result(res);
            continue;
        }
        mysql_free_result(res);

        err = read_network(year);
        if (err) {
            return err;
        }

        std::cout << "Calculating " << year << "\n";

        Basetype* in_flow = create_array(0);
        Basetype* out_flow = create_array(0);
        int regions_size = regions.size();
        Basetype* total_output = new Basetype[regions_size];
        for (int r = 0; r < regions_size; r++) {
            total_output[r] = 0;
        }
        for (int v = 0; v < network_size; v++) {
            for (int w = 0; w < network_size; w++) {
                in_flow[v] += flows[w][v];
                out_flow[v] += flows[v][w];
            }
            total_output[get_region(v)] += out_flow[v];
        }
        int sectors_size = sectors.size();
        Basetype** in_flow_by_sector = new Basetype*[sectors_size];
        for (int i = 0; i < sectors_size; i++) {
            in_flow_by_sector[i] = create_array(0);
        }
        for (int v = 0; v < network_size; v++) {
            for (int w = 0; w < network_size; w++) {
                in_flow_by_sector[get_sector(v)][w] += flows[v][w];
            }
        }

        snprintf(q, 512, "delete from visualization_data where visualization in (select id from visualizations where (name='GAP1' or name='GAP2') and year=%d)", year);
        if (mysql_query(mysql, q)) {
            std::cerr << mysql_error(mysql) << "\n";
            return -2;
        }

        snprintf(q, 512, "select id from visualizations where name='GAP1' and year=%d", year);
        if (mysql_query(mysql, q)) {
            std::cerr << mysql_error(mysql) << "\n";
            return -2;
        }
        res = mysql_use_result(mysql);
        row = mysql_fetch_row(res);
        int id1 = atoi(row[0]);
        mysql_free_result(res);

        snprintf(q, 512, "select id from visualizations where name='GAP2' and year=%d", year);
        if (mysql_query(mysql, q)) {
            std::cerr << mysql_error(mysql) << "\n";
            return -2;
        }
        res = mysql_use_result(mysql);
        row = mysql_fetch_row(res);
        int id2 = atoi(row[0]);
        mysql_free_result(res);

        for (int r = 0; r < regions_size; r++) {
            Basetype* damage1 = create_array(0);
            Basetype* damage2 = create_array(0);
            int js;

            #pragma omp parallel default(shared) private(js)
            {
                #pragma omp for schedule(guided) nowait
                for (js = 0; js < network_size; js++) {
                    if (get_region(js) == r) {
                        damage1[js] = 1;
                    } else {
                        for (int i = 0; i < sectors_size; i++) {
                            Basetype damage = flows[get_index(i, r)][js] / in_flow_by_sector[i][js];
                            if (damage1[js] < damage) {
                                damage1[js] = damage;
                            }
                        }
                    }
                }
            }
            #pragma omp parallel default(shared) private(js)
            {
                #pragma omp for schedule(guided) nowait
                for (js = 0; js < network_size; js++) {
                    if (get_region(js) == r) {
                        damage2[js] = 1;
                    } else {
                        for (int i = 0; i < sectors_size; i++) {
                            Basetype damage = 0;
                            for (int r = 0; r < regions_size; r++) {
                                int ir = get_index(i, r);
                                damage += damage1[ir] * flows[ir][js] / in_flow_by_sector[i][js];
                            }
                            if (damage2[js] < damage) {
                                damage2[js] = damage;
                            }
                        }
                    }
                }
            }

            Basetype* region_damage1 = new Basetype[regions_size];
            Basetype* region_damage2 = new Basetype[regions_size];
            for (int r = 0; r < regions_size; r++) {
                region_damage1[r] = 0;
                region_damage2[r] = 0;
            }
            for (int js = 0; js < network_size; js++) {
                int s = get_region(js);
                if (total_output[s] > 0) {
                    region_damage1[s] += damage1[js] * out_flow[js] / total_output[s];
                    region_damage2[s] += damage2[js] * out_flow[js] / total_output[s];
                }
            }
            delete[] damage1;
            delete[] damage2;

            std::stringstream query1("insert into visualization_data (visualization, region_from, region_to, value) values ", std::ios_base::app | std::ios_base::out);
            bool first1 = true;
            std::stringstream query2("insert into visualization_data (visualization, region_from, region_to, value) values ", std::ios_base::app | std::ios_base::out);
            bool first2 = true;
            for (int s = 0; s < regions_size; s++) {
                region_damage1[s] = round(region_damage1[s] * 1000) / 1000;
                if (region_damage1[s] > 0) {
                    if (first1) {
                        first1 = false;
                    } else {
                        query1 << ",";
                    }
                    query1 << "(" << id1 << ",'" << regions[r] << "','" << regions[s] << "'," << region_damage1[s] << ")";
                }
                region_damage2[s] = round(region_damage2[s] * 1000) / 1000;
                if (region_damage2[s] > 0) {
                    if (first2) {
                        first2 = false;
                    } else {
                        query2 << ",";
                    }
                    query2 << "(" << id2 << ",'" << regions[r] << "','" << regions[s] << "'," << region_damage2[s] << ")";
                }
            }
            if (!first1) {
                if (mysql_query(mysql, query1.str().c_str())) {
                    std::cerr << mysql_error(mysql) << "\n";
                    return -2;
                }
            }
            if (!first2) {
                if (mysql_query(mysql, query2.str().c_str())) {
                    std::cerr << mysql_error(mysql) << "\n";
                    return -2;
                }
            }

            delete[] region_damage1;
            delete[] region_damage2;
        }

        delete[] in_flow;
        delete[] out_flow;
        free_double_array(flows);
        for (int i = 0; i < sectors_size; i++) {
            delete[] in_flow_by_sector[i];
        }
        delete[] in_flow_by_sector;
        delete[] total_output;

        snprintf(q, 512, "update visualizations set updated=now() where (name='GAP1' or name='GAP2') and year=%d", year);
        if (mysql_query(mysql, q)) {
            std::cerr << mysql_error(mysql) << "\n";
            return -2;
        }
    }

    return disconnect();
}
Пример #7
0
int
main (void)
{
  FILE *f;
  char chem_file[] = "network.chm";
  net_t network;
  
  int verbose = 1;

  /* Create the network.chm file */

  f = fopen ("network.chm", "w");
  fprintf (f, "# This network file was created by network test\n");
  fprintf (f, "# The reaction were extracted form the OSU 2008 network\n");
  fprintf (f, "H            + H                           -> H2                                                           4.95e-17  5.00e-01  0.00e+00  0    1\n");
  fprintf (f, "C(+)         + grain(-)                    -> C            + grain                                         4.90e-17  5.00e-01  0.00e+00  0    3\n");
  fprintf (f, "H3(+)        + grain(-)                    -> H2           + H            + grain                          1.00e-16  5.00e-01  0.00e+00  0   13\n");
  fprintf (f, "C            + cosmic-ray                  -> C(+)         + e(-)                                          1.02e+03  0.00e+00  0.00e+00  1   15\n");
  fprintf (f, "CH5N         + cosmic-ray                  -> HCN          + H2           + H            + H               1.41e+03  0.00e+00  0.00e+00  1  176\n");
  fprintf (f, "C(+)         + Fe                          -> Fe(+)        + C                                             2.60e-09  0.00e+00  0.00e+00  2  218\n");
  fprintf (f, "He(+)        + HNC                         -> C(+)         + N            + H            + He              4.43e-09 -5.00e-01  0.00e+00  2  735\n");
  fprintf (f, "C(-)         + NO                          -> CN(-)        + O                                             1.00e-09  0.00e+00  0.00e+00  3 3151\n");
  fprintf (f, "C(+)         + H                           -> CH(+)                                                        1.70e-17  0.00e+00  0.00e+00  4 3162\n");
  fprintf (f, "C(-)         + C                           -> C2           + e(-)                                          5.00e-10  0.00e+00  0.00e+00  5 3243\n");
  fprintf (f, "O            + CH                          -> HCO(+)       + e(-)                                          2.00e-11  4.40e-01  0.00e+00  6 3289\n");
  fprintf (f, "C            + CH                          -> C2           + H                                             6.59e-11  0.00e+00  0.00e+00  7 3290\n");
  fprintf (f, "C            + C                           -> C2           + photon                                        1.00e-17  0.00e+00  0.00e+00  8 3672\n");
  fprintf (f, "C2(+)        + e(-)                        -> C            + C                                             8.84e-08 -5.00e-01  0.00e+00  9 3688\n");
  fprintf (f, "C(+)         + e(-)                        -> C            + photon                                        4.40e-12 -6.10e-01  0.00e+00 10 4227\n");
  fprintf (f, "C(+)         + C(-)                        -> C            + C                                             2.30e-07 -5.00e-01  0.00e+00 11 4243\n");
  fprintf (f, "C            + e(-)                        -> C(-)                                                         3.00e-15  0.00e+00  0.00e+00 12 4279\n");
  fprintf (f, "O            + -13-CH                      -> H-13-CO(+)   + e(-)                                          2.00e-11  4.40e-01  0.00e+00  6 3289\n");
  fprintf (f, "CO                                         -> CO(ice)                                                      1.00e+00  2.80e+01  0.00e+00 20 10044\n");
  fclose (f);

  /* Read it */

  if( read_network(chem_file, &network, verbose) != EXIT_SUCCESS )
    {
      return EXIT_FAILURE;
    }

  /* Check that the values are correct */

  if ((network.n_reactions == 19) &&
      (network.n_species == 29) &&

      /* Reaction #1 */
      (network.reactions[0].reactants[0] == find_species("H", &network)) &&
      (network.reactions[0].reactants[1] ==  find_species("H", &network)) &&
      (network.reactions[0].reactants[2] == -1) &&
      (network.reactions[0].products[0] ==  find_species("H2", &network)) &&
      (network.reactions[0].products[1] == -1) &&
      (network.reactions[0].products[2] == -1) &&
      (network.reactions[0].products[3] == -1) &&
      (network.reactions[0].alpha == 4.95e-17) &&
      (network.reactions[0].beta == .5) &&
      (network.reactions[0].gamma == 0) &&
      (network.reactions[0].reaction_type == 0) &&
      (network.reactions[0].reaction_no == 1) &&

      /* Reaction #176 */
      (network.reactions[4].reactants[0] == find_species("CH5N", &network)) &&
      (network.reactions[4].reactants[1] == -1) &&
      (network.reactions[4].reactants[2] == -1) &&
      (network.reactions[4].products[0] ==  find_species("HCN", &network)) &&
      (network.reactions[4].products[1] ==  find_species("H2", &network)) &&
      (network.reactions[4].products[2] ==  find_species("H", &network)) &&
      (network.reactions[4].products[3] ==  find_species("H", &network) )&&
      (network.reactions[4].alpha == 1.41e3) &&
      (network.reactions[4].beta == 0) &&
      (network.reactions[4].gamma == 0) &&
      (network.reactions[4].reaction_type == 1) &&
      (network.reactions[4].reaction_no == 176) &&

      /* Reaction #4227 */
      (network.reactions[14].reactants[0] == find_species("C(+)", &network) )&&
      (network.reactions[14].reactants[1] == find_species("e(-)", &network) )&&
      (network.reactions[14].reactants[2] == -1) &&
      (network.reactions[14].products[0] == find_species("C", &network) )&&
      (network.reactions[14].products[1] == -1) &&
      (network.reactions[14].products[2] == -1) &&
      (network.reactions[14].products[3] == -1) &&
      (network.reactions[14].alpha == 4.40e-12) &&
      (network.reactions[14].beta == -.61) &&
      (network.reactions[14].gamma == 0) &&
      (network.reactions[14].reaction_type == 10) &&
      (network.reactions[14].reaction_no == 4227)  &&

      /* Mass and charge of a few species */

      (abs(network.species[find_species("C(+)", &network)].mass / UMA - 12) <= 0.01) &&
      (network.species[find_species("C(+)", &network)].charge == 1.0) &&
      (abs(network.species[find_species("HCO(+)", &network)].mass / UMA - 29) <= 0.01) &&
      (network.species[find_species("HCO(+)", &network)].charge == 1.0) &&
      (abs(network.species[find_species("H-13-CO(+)", &network)].mass / UMA - 30) <= 0.01) &&
      (network.species[find_species("H-13-CO(+)", &network)].charge == 1.0) &&
      (abs(network.species[find_species("CH5N", &network)].mass / UMA - 31) <= 0.01) &&
      (network.species[find_species("CH5N", &network)].charge == 0.0) &&
      (network.species[find_species("e(-)", &network)].charge == -1))
    {
      free_network (&network);
      return EXIT_SUCCESS;
    }
  else
    {
      free_network (&network);
      return EXIT_FAILURE;
    }
}
Пример #8
0
int main(int argc, char* argv[]) {
    char q[512];
    MYSQL_ROW row;
    MYSQL_RES* res;

    int err = init_network();
    if (err) {
        return err;
    }

    for (int year = 1990; year <= 2011; year++) {
        std::cout << "Querying " << year << "\n";

        snprintf(q, 512, "select count(value) from entries where year=%d and inserted>(select updated from visualizations where name='Flow Centrality' and year=%d)", year, year);
        if (mysql_query(mysql, q)) {
            std::cerr << mysql_error(mysql) << "\n";
            return -2;
        }
        res = mysql_use_result(mysql);
        if((row = mysql_fetch_row(res)) == 0 || atoi(row[0]) == 0) {
            mysql_free_result(res);
            continue;
        }
        mysql_free_result(res);

        err = read_network(year);
        if (err) {
            return err;
        }

        std::cout << "Calculating " << year << "\n";
        err = disconnect();
        if (err) {
            return err;
        }

        Basetype* betweenness = create_array(0);
        Basetype* in_flow = create_array(0);
        Basetype* out_flow = create_array(0);
        for (int v = 0; v < network_size; v++) {
            for (int w = 0; w < network_size; w++) {
                in_flow[v] += flows[w][v];
                out_flow[v] += flows[v][w];
            }
        }

        // Algorithm according to "A space-efficient parallel algorithm for computing betweenness centrality in distributed memory", p. 2
        int s;
    #pragma omp parallel default(none) shared(betweenness, flows, network_size, in_flow, std::cerr)
        {
    #pragma omp for schedule(guided) nowait
            for (s = 0; s < network_size; s++) {
                std::vector<int> S;
                std::queue<int> PQ;
                BasetypeInt* sigma;
                Basetype* delta;
                Basetype* dist;
                BasetypeInt** P;
                BasetypeInt* P_size;
                Basetype* pipe;
                sigma = create_array_int(0);
                sigma[s] = 1;
                delta = create_array(0);
                P = create_double_int_array(0);
                P_size = create_array_int(0);
                dist = create_array(-1);
                dist[s] = 0;
                pipe = create_array(0);
                pipe[s] = -1;
                PQ.push(s);
                while (!PQ.empty()) {
                    int v = PQ.front();
                    PQ.pop();
                    for (std::vector<int>::iterator it = S.begin(); it != S.end(); it++) {
                        if (*it == v) {
                            S.erase(it);
                            break;
                        }
                    }
                    S.push_back(v);
                    for (int w = 0; w < network_size; w++) {
                        if (w != v && w != s && flows[v][w] > 0) {
                            Basetype c_v_w = flows[v][w];
                            Basetype new_pipe;
                            if (pipe[v] < 0) {
                                new_pipe = c_v_w;
                            } else {
                                new_pipe = std::min(pipe[v], c_v_w);
                            }
                            if (pipe[w] < new_pipe || (pipe[w] == new_pipe && dist[w] > dist[v] + 1)) { // Better best path via v
                                PQ.push(w);
                                pipe[w] = new_pipe;
                                dist[w] = dist[v] + 1;
                                sigma[w] = 0;
                                P_size[w] = 0;
                            }
                            if (pipe[w] == new_pipe && dist[w] == dist[v] + 1 && !in_array(v,P[w],P_size[w])) { // Some best path via v
                                sigma[w] += sigma[v];
                                P[w][P_size[w]] = v;
                                P_size[w]++;
                            }
                        }
                    }
                }

                while (!S.empty()) {
                    int w = S.back();
                    S.pop_back();

                    for (int v_index = 0; v_index < P_size[w]; v_index++) {
                        int v = P[w][v_index];
                        delta[v] += ((1 + delta[w]) * (Basetype) sigma[v]) / (Basetype) sigma[w];
                    }

                    if (w != s) {
                        #pragma omp atomic
                            betweenness[w] += delta[w];
                    }
                }
                delete[] delta;
                delete[] sigma;
                delete[] dist;
                delete[] P_size;
                free_double_int_array(P);
                delete[] pipe;
            }
        }

        err = connect();
        if (err) {
            return err;
        }

        snprintf(q, 512, "delete from visualization_data where visualization in (select id from visualizations where name='Flow Centrality' and year=%d)", year);
        if (mysql_query(mysql, q)) {
            std::cerr << mysql_error(mysql) << "\n";
            return -2;
        }

        snprintf(q, 512, "select id from visualizations where name='Flow Centrality' and year=%d", year);
        if (mysql_query(mysql, q)) {
            std::cerr << mysql_error(mysql) << "\n";
            return -2;
        }
        res = mysql_use_result(mysql);
        row = mysql_fetch_row(res);
        int id = atoi(row[0]);
        mysql_free_result(res);

        std::stringstream query("insert into visualization_data (visualization, sector_from, region_from, value) values ", std::ios_base::app | std::ios_base::out);
        for (int js = 0; js < network_size; js++) {
            if (js > 0) {
                query << ",";
            }
            query << "(" << id << ",'" << sectors[get_sector(js)] << "','" << regions[get_region(js)] << "'," << betweenness[js] << ")";
        }
        if (mysql_query(mysql, query.str().c_str())) {
            std::cerr << mysql_error(mysql) << "\n";
            return -2;
        }

        snprintf(q, 512, "update visualizations set updated=now() where name='Flow Centrality' and year=%d", year);
        if (mysql_query(mysql, q)) {
            std::cerr << mysql_error(mysql) << "\n";
            return -2;
        }

        delete[] betweenness;
        free_double_array(flows);

    }

    return 0;
}
Пример #9
0
int main(int argc, char* argv[])
{
	double time;
	int *prices, *P;
	int i, task, source, tail, nodes, arcs;
	int (*network)[2], (*network_i)[2];
	int *a0, *a1, *ai0, *ai1, *Psse, *prsse;
	clock_t start, end;
	char *filename;

	printf("Hello\n");

	task = atoi(argv[1]);
	arcs = atoi(argv[2]);
	nodes = atoi(argv[3]);
	filename = argv[4];

	printf("P-1\n");

	network = (int (*)[2])malloc((arcs+nodes)*2*sizeof(int));		//przydzial pamieci dla tablicy z grafem
	network_i = (int (*)[2])malloc((arcs+nodes)*2*sizeof(int));
	read_network(filename, &source, &tail, &nodes, &arcs, network, network_i);

	printf("%d %d %d %d\n", network_i[0][0], network_i[0][1], network[0][0], network[0][1]);

	prices = (int*)malloc((nodes+1)*sizeof(int));
	P = (int*)malloc((nodes+1)*sizeof(int));
	printf("P0\n");

	if(task == SEQ) {
		start = clock();
		auction_search(prices, P, network, network_i, nodes, arcs, source, tail);
		end = clock();
	}
	else if(task == SSE) {
		a0 = _mm_malloc(arcs*sizeof(int), 16);
		a1 = _mm_malloc(arcs*sizeof(int), 16);
		ai0 = _mm_malloc(nodes*sizeof(int), 16);
		ai1 = _mm_malloc(nodes*sizeof(int), 16);
		Psse = _mm_malloc((nodes+1)*sizeof(int), 16);
		prsse = _mm_malloc((nodes+1)*sizeof(int), 16);
		for(i = 0; i < arcs; i++) {
			a0[i] = (int) network[i][0];
			a1[i] = (int) network[i][1];
		}
		for(i = 0; i < nodes; i++) {
			ai0[i] = (int) network_i[i][0];
			ai1[i] = (int) network_i[i][1];
		}
		for(i = 0; i <= nodes; i++) {
			Psse[i] = (int) INF;
			prsse[i] = 0;
		}
		start = clock();
		sse_auction_search(prsse, Psse, ai0, ai1, a0, a1, nodes, arcs, source, tail);	
		end = clock();
		_mm_free(a0);
		_mm_free(a1);
		_mm_free(ai0);
		_mm_free(ai1);
		_mm_free(Psse);
		_mm_free(prsse);
	}
	else {
		printf("Nieprawidlowy typ zadania\n");
		return 1;
	}
	
	time = ((double) (end - start)) / CLOCKS_PER_SEC;

	printf("Czas wykonania programu: %5.1f [ms]\n", time*1000);
	//for(i = 0; i < nodes; i++) {
	//	printf("%d ", P[i]);
	//}
	//printf("\n");
	free(network);
	free(network_i);
	free(prices);
	free(P);

	return 0;
}
Пример #10
0
int
main (int argc, char *argv[])
{
  inp_t input_params;
  mdl_t source_mdl;
  net_t network;
  int cell_index;

  int verbose = 1;
  char *input_file;

  /* Parse options and command line arguments. Diplay help
     message if no (or more than one) argument is given. */

    {
      int opt;

      static struct option longopts[] = {
          {"help", no_argument, NULL, 'h'},
          {"version", no_argument, NULL, 'V'},
          {"verbose", no_argument, NULL, 'v'},
          {"quiet", no_argument, NULL, 'q'},
          {0, 0, 0, 0}
      };

      while ((opt = getopt_long (argc, argv, "hVvq", longopts, NULL)) != -1)
        {
          switch (opt)
            {
            case 'h':
              usage ();
              return EXIT_SUCCESS;
              break;
            case 'V':
              version ();
              return EXIT_SUCCESS;
              break;
            case 'v':
              verbose = 2;
              break;
            case 'q':
              verbose = 0;
              break;
            default:
              usage ();
              return EXIT_FAILURE;
            }
        };
      argc -= optind;
      argv += optind;
      if (argc != 1)
        {
          usage ();
          return EXIT_FAILURE;
        }
      input_file = argv[0];
    }

  /* Read the input file */
  if( read_input_file_names (input_file, &input_params.files, verbose) != EXIT_SUCCESS )
    {
      return EXIT_FAILURE;
    }

  /* Read the chemical network file */
  if( read_network (input_params.files.chem_file, &network, verbose) != EXIT_SUCCESS )
    {
      return EXIT_FAILURE;
    }

  /* Read the input file */
  if( read_input (input_file, &input_params, &network, verbose) != EXIT_SUCCESS )
    {
      return EXIT_FAILURE;
    }

  /* Read the source model file */
  if( read_source (input_params.files.source_file, &source_mdl, &input_params,
               verbose) != EXIT_SUCCESS )
    {
      return EXIT_FAILURE;
    }

  // Hdf5 files, datatype and dataspace
  hid_t       fid, datatype, dataspace, dataset, tsDataset, tsDataspace,  speciesDataset, speciesDataspace, speciesType;
  datatype = H5Tcopy(H5T_NATIVE_DOUBLE);

  hsize_t     dimsf[ ROUTE_DATASET_RANK ]={  source_mdl.n_cells, source_mdl.ts.n_time_steps, input_params.output.n_output_species, N_OUTPUT_ROUTES };
  fid = H5Fcreate( "astrochem_output.h5", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); 
  dataspace = H5Screate_simple( ABUNDANCE_DATASET_RANK, dimsf, NULL);

  // Add Atributes
  hid_t simpleDataspace = H5Screate(H5S_SCALAR);
  hid_t attrType = H5Tcopy(H5T_C_S1);
  H5Tset_size ( attrType, MAX_CHAR_FILENAME );
  H5Tset_strpad(attrType,H5T_STR_NULLTERM);
  hid_t attrNetwork = H5Acreate( fid, "chem_file", attrType, simpleDataspace, H5P_DEFAULT, H5P_DEFAULT);
  H5Awrite( attrNetwork, attrType, realpath( input_params.files.chem_file, NULL ) );
  H5Aclose( attrNetwork );
  hid_t attrModel = H5Acreate( fid, "source_file", attrType, simpleDataspace, H5P_DEFAULT, H5P_DEFAULT);
  H5Awrite( attrModel, attrType, realpath( input_params.files.source_file, NULL ) );
  H5Aclose( attrModel );

  H5Tclose( attrType );
  H5Sclose( simpleDataspace );

  // Define chunk property
  hsize_t     chunk_dims[ ROUTE_DATASET_RANK ] = { 1, 1, input_params.output.n_output_species, N_OUTPUT_ROUTES };
  hid_t prop_id = H5Pcreate(H5P_DATASET_CREATE);
  H5Pset_chunk(prop_id, ABUNDANCE_DATASET_RANK , chunk_dims);

  // Create dataset
  dataset = H5Dcreate(fid, "Abundances", datatype, dataspace, H5P_DEFAULT, prop_id, H5P_DEFAULT);

  int i;
  hid_t dataspaceRoute, route_t_datatype, r_t_datatype, route_prop_id, routeGroup;
  hid_t routeDatasets[ input_params.output.n_output_species ];
  if (input_params.output.trace_routes)
    {

      // Create route dataspace
      dataspaceRoute = H5Screate_simple( ROUTE_DATASET_RANK, dimsf, NULL);

      // Create route datatype
      r_t_datatype = H5Tcreate (H5T_COMPOUND, sizeof(r_t));
      H5Tinsert( r_t_datatype, "reaction_number", HOFFSET(r_t, reaction_no ), H5T_NATIVE_INT);
      H5Tinsert( r_t_datatype, "reaction_rate", HOFFSET(r_t, rate), H5T_NATIVE_DOUBLE);

      route_t_datatype = H5Tcreate (H5T_COMPOUND, sizeof(rout_t));
      H5Tinsert( route_t_datatype, "formation_rate", HOFFSET(rout_t, formation ), r_t_datatype );
      H5Tinsert( route_t_datatype, "destruction_rate", HOFFSET(rout_t, destruction ), r_t_datatype );

      // Define route chunk property
      route_prop_id = H5Pcreate(H5P_DATASET_CREATE);
      H5Pset_chunk( route_prop_id, ROUTE_DATASET_RANK, chunk_dims);


      // Create each named route dataset
      routeGroup = H5Gcreate( fid, "Routes", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT );
      char routeName[6] = "route_";
      char tempName[ MAX_CHAR_SPECIES + sizeof( routeName ) ];
      for( i = 0; i < input_params.output.n_output_species ; i++ )
        {
          strcpy( tempName, routeName );
          strcat( tempName, network.species[input_params.output.output_species_idx[i]].name );
          routeDatasets[i] = H5Dcreate( routeGroup, tempName, route_t_datatype, dataspaceRoute, H5P_DEFAULT, route_prop_id, H5P_DEFAULT);
        }
    }
  // Timesteps and species
  hsize_t n_ts = source_mdl.ts.n_time_steps;
  hsize_t n_species =  input_params.output.n_output_species ;
  tsDataspace = H5Screate_simple( 1, &n_ts, NULL);
  speciesDataspace = H5Screate_simple( 1, &n_species, NULL);
  speciesType = H5Tcopy (H5T_C_S1);
  H5Tset_size (speciesType, MAX_CHAR_SPECIES );
  H5Tset_strpad(speciesType,H5T_STR_NULLTERM);

  // Create ts and species datasets
  tsDataset = H5Dcreate(fid, "TimeSteps", datatype, tsDataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
  speciesDataset = H5Dcreate(fid, "Species", speciesType, speciesDataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
  double* convTs = (double*) malloc( sizeof(double)* source_mdl.ts.n_time_steps );
  for( i=0; i< source_mdl.ts.n_time_steps; i++ )
    {
      convTs[i] = source_mdl.ts.time_steps[i] / CONST_MKSA_YEAR;
    }

  H5Dwrite( tsDataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, convTs );


  char speciesName [ input_params.output.n_output_species ][ MAX_CHAR_SPECIES ];
  for( i = 0; i < input_params.output.n_output_species ; i++ )
    {
      strcpy( speciesName[i], network.species[input_params.output.output_species_idx[i]].name );
    }

  H5Dwrite( speciesDataset, speciesType, H5S_ALL, H5S_ALL, H5P_DEFAULT, speciesName );

  free( convTs );
  H5Dclose( tsDataset );
  H5Dclose( speciesDataset );
  H5Tclose( speciesType );
  H5Sclose( tsDataspace );
  H5Sclose( speciesDataspace );


#ifdef HAVE_OPENMP
  /*Initialize lock*/
  omp_init_lock(&lock);


  /* Solve the ODE system for each cell. */
    {
#pragma omp parallel for schedule (dynamic, 1)
#endif
      for (cell_index = 0; cell_index < source_mdl.n_cells; cell_index++)
        {
          if (verbose >= 1)
            fprintf (stdout, "Computing abundances in cell %d...\n",
                     cell_index);
          if( full_solve ( fid, dataset, routeDatasets, dataspace, dataspaceRoute, datatype, route_t_datatype, cell_index, &input_params, source_mdl.mode,
                       &source_mdl.cell[cell_index], &network, &source_mdl.ts, verbose) != EXIT_SUCCESS )
            {
	      exit (EXIT_FAILURE);
            }
          if (verbose >= 1)
            fprintf (stdout, "Done with cell %d.\n", cell_index);
        }
#ifdef HAVE_OPENMP
    }


  /*Finished lock mechanism, destroy it*/
  omp_destroy_lock(&lock);
#endif

  /*
   * Close/release hdf5 resources.
   */
  if (input_params.output.trace_routes)
    {


      for( i = 0; i <  input_params.output.n_output_species ; i++ )
        {
          H5Dclose(routeDatasets[i] );
        }
      H5Sclose(dataspaceRoute);
      H5Gclose(routeGroup);
      H5Pclose(route_prop_id);
      H5Tclose(r_t_datatype);
      H5Tclose(route_t_datatype);
    }
  H5Dclose(dataset);
  H5Pclose(prop_id);
  H5Sclose(dataspace);
  H5Tclose(datatype);

  H5Fclose(fid);

  free_input (&input_params);
  free_mdl (&source_mdl);
  free_network (&network);
  return (EXIT_SUCCESS);
}
Пример #11
0
int
main (void)
{
  FILE *f;
  net_t network;
  int verbose = 0;

  /* Create the input.ini, source.mdl and network_chm files */

  f = fopen ("network.chm", "w");
  fprintf (f, "# This network file was created by full_solve_test\n");
  fprintf (f, "X -> Y    1e-9    0    0    2    1\n");
  fclose (f);

  /* Read them */
  if( read_network ("network.chm", &network, verbose) )
    {
      return EXIT_FAILURE;
    }

  phys_t phys;
  phys.cosmic = 1.3e-17;
  phys.chi = 1;
  phys.grain_size = 1e-5;
  phys.grain_abundance = 0;

  double abs_err, rel_err;
  abs_err = 1e-15;
  rel_err = 1e-6;

  const char* species[]  = { "X", "Y" };
  const double initial_abundances[] = { 1.0, 0.0 };

  double *abundances;
  alloc_abundances( &network, &abundances ); // Allocate the abundances array; it contains all species.
  set_initial_abundances(species, 2, initial_abundances, &network, abundances); // Set initial abundances

  double density = 1000;
  double av = 20;
  double temperature = 10;

  cell_t cell;
  cell.nh = density;
  cell.av = av;
  cell.tgas = temperature;
  cell.tdust = temperature; // Assume tgas = tdust in this specific case

  astrochem_mem_t astrochem_mem;

  if( solver_init( &cell, &network, &phys, abundances , density, abs_err, rel_err, &astrochem_mem ) != EXIT_SUCCESS )
    {
      return EXIT_FAILURE;
   }
  int i;
  double time = 0;
  for( i = 0; i < 1000 ; i++ )
    {

      time+= 10;
      if( solve( &astrochem_mem, &network, abundances, time, NULL,verbose) != EXIT_SUCCESS )
        {
          return EXIT_FAILURE;
        }
      double x_abundance;
      double y_abundance;
      double x_abs_err;
      double x_rel_err;
      double y_abs_err;
      double y_rel_err;

      x_abundance = 1.0 * exp (-1e-9 *  time);
      y_abundance = 1.0 - x_abundance;
      x_abs_err = fabs( abundances[0] - x_abundance);
      y_abs_err = fabs( abundances[1] - y_abundance);
      x_rel_err = x_abs_err / x_abundance;
      y_rel_err = y_abs_err / y_abundance;

      /* Errors accumulate after each time step, so the actual error
         on the abundance is somewhat larger than the solver
         relative tolerance. */
      if ((x_abs_err > abs_err) && (x_rel_err > rel_err * 5e2))
        {
          fprintf (stderr, "full_solve_test: %s:%d: incorrect abundance at t=%12.15e: expected %12.15e, got %12.15e.\n",
                   __FILE__, __LINE__, time, x_abundance, abundances[0]);
          solver_close( &astrochem_mem );
          free_abundances( abundances );
          free_network (&network);
          return EXIT_FAILURE;
        }

      if ((y_abs_err > abs_err) && (y_rel_err > rel_err * 5e2))
        {
          fprintf (stderr, "full_solve_test: %s:%d: incorrect abundance at t=%12.6e: expected %12.6e, got %12.6e.\n",
                   __FILE__, __LINE__, time, y_abundance, abundances[1]);
          solver_close( &astrochem_mem );
          free_abundances( abundances );
          free_network (&network);
          return EXIT_FAILURE;
        }
    }
  solver_close( &astrochem_mem );
  free_abundances( abundances );
  free_network (&network);
  return EXIT_SUCCESS;
}