Exemplo n.º 1
0
int main(int argc, char *argv[])
{
    int n,i;
    REAL *y_ref, *y_ompacc, *x;
    REAL a = 123.456f;

    n = VEC_LEN;
    if (argc >= 2)
        n = atoi(argv[1]);

    y_ref = (REAL *) malloc(n * sizeof(REAL));
    y_ompacc = (REAL *) malloc(n * sizeof(REAL));
    x = (REAL *) malloc(n * sizeof(REAL));

    srand48(1<<12);
    init(x, n);
    init(y_ref, n);
    memcpy(y_ompacc, y_ref, n*sizeof(REAL));

#if 0
//-------------------- begin of multi-gpu portion
    // Transformation point: obtain the number of devices to be used by default
    int GPU_N = xomp_get_num_devices();
    printf("CUDA-capable device count: %i\n", GPU_N);

    // preparation for multiple GPUs
    // Transformation point: set first level thread count to be GPU count used
    omp_set_num_threads(GPU_N);
    #pragma omp parallel shared (GPU_N,x , y_ompacc, n) private(i)
    {
        int tid = omp_get_thread_num();
        xomp_set_default_device (tid);

        long size, offset;
        XOMP_static_even_divide (0, n, GPU_N, tid, &offset, &size);
        printf("thread %d working on GPU devices %d with size %d copying data from y_ompacc with offset %d\n",tid, tid, size,offset);
        int j;
        #pragma omp target device (tid) map(tofrom: y_ompacc[offset:size]) map(to: x[offset:size],a,size, offset)
        #pragma omp parallel for shared(size, a)  private(j)
        for (j = offset; j < offset+size; ++j)
        {
            y_ompacc[j] += a * x[j];
        }
    }
//-------------------- end of multi-gpu portion
#else
    #pragma omp target device(*) map(tofrom: y_ompacc[0:n] dist_data(block)) map(to: x[0:n] dist_data(block),a,n)
    #pragma omp parallel for shared(x, y_ompacc, n, a) private(i)
    for (i = 0; i < n; ++i)
        y_ompacc[i] += a * x[i];

#endif

    int num_threads;
    #pragma omp parallel shared (num_threads)
    {
        if (omp_get_thread_num() == 0)
            num_threads = omp_get_num_threads();
    }
    // serial version
    axpy(x, y_ref, n, a);

    REAL checksum = check(y_ref, y_ompacc, n);
    printf("axpy(%d): checksum: %g\n", n, checksum);
    assert (checksum < 1.0e-10);

    free(y_ref);
    free(y_ompacc);
    free(x);
    return 0;
}
Exemplo n.º 2
0
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
    //// Initializations ---------------------------------------------
    srand48(1234); // Make sure we have reproducability
    check_args(argc);
    Time t, time; // t for global, time for local
    init_time(t);
    Feat F;
    MTL M;
   

    // Read parameters file //
    F.readInputFile(argv[1]);
    printFile(argv[1]);
    // Read Secretfile
    // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF
    Gals Secret;
    init_time_at(time,"# reading Secret file",t);

        Secret=read_Secretfile(F.Secretfile,F);
    printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str());
    print_time(time,"# ... took :");
    std::vector<int> count(10);
    count=count_galaxies(Secret);
    printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
    for(int i=0;i<8;i++){if(count[i]>0)printf (" type %d number  %d  \n",i, count[i]);}
    //read the three input fits files
    init_time_at(time,"# read target, SS, SF files",t);
    MTL Targ=read_MTLfile(F.Targfile,F,0,0);
    MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
    MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
    
    if(Targ.size() == 0) {
        std::cerr << "ERROR: No targets found in " << F.Targfile << std::endl;
        myexit(1);
    }
    
    print_time(time,"# ... took :");
    //combine the three input files
    M=Targ;
    printf(" M size %d \n",M.size());
    M.insert(M.end(),SStars.begin(),SStars.end());
    printf(" M size %d \n",M.size());
    M.insert(M.end(),SkyF.begin(),SkyF.end());
    printf(" M size %d \n",M.size());
    F.Ngal=M.size();
    F.Ntarg=Secret.size();
    
    //establish priority classes
    init_time_at(time,"# establish priority clasess",t);
    assign_priority_class(M);
    std::vector <int> count_class(M.priority_list.size(),0);
    for(int i;i<M.size();++i){
        if(!M[i].SS&&!M[i].SF){
        count_class[M[i].priority_class]+=1;
        }
    }
    for(int i;i<M.priority_list.size();++i){
        printf("  class %d  priority %d  number %d\n",i,M.priority_list[i],count_class[i]);
    }
    print_time(time,"# ... took :");
    
    // fiber positioners
    PP pp;
    pp.read_fiber_positions(F); 
    F.Nfiber = pp.fp.size()/2; 
    F.Npetal = max(pp.spectrom)+1;
    F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
    pp.get_neighbors(F);
    pp.compute_fibsofsp(F);
    printf("computed neighbors\n");
    std::cout.flush();
    //P tiles in order specified by surveyFile
    Plates P = read_plate_centers(F);
    F.Nplate=P.size();
    printf("# Read %d plates from %s and %d fibers from %s\n",F.Nplate,F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

    // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
    F.cb = create_cb(); // cb=central body
    F.fh = create_fh(); // fh=fiber holder

    //// Collect available galaxies <-> tilefibers --------------------
    // HTM Tree of galaxies
    const double MinTreeSize = 0.01;
    init_time_at(time,"# Start building HTM tree",t);

    htmTree<struct target> T(M,MinTreeSize);
    print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect galaxies at ",t);
    
    // For plates/fibers, collect available galaxies; done in parallel
    collect_galaxies_for_all(M,T,P,pp,F);
    print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect available tile-fibers at",t);
    // For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
    collect_available_tilefibers(M,P,F);
    
    //results_on_inputs("doc/figs/",G,P,F,true);

    //// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
    Assignment A(M,F);
    
    print_time(t,"# Start assignment at : ");

    // Make a plan ----------------------------------------------------
    // Plans whole survey without sky fibers, standard stars
    // assumes maximum number of observations needed for QSOs, LRGs

    simple_assign(M,P,pp,F,A);

    //check to see if there are tiles with no galaxies
    //need to keep mapping of old tile list to new tile list
    //and inverse map
    A.inv_order=initList(F.Nplate,-1);
    int inv_count=0;
    for (int j=0;j<F.Nplate ;++j){
        
        bool not_done=true;
        for(int k=0;k<F.Nfiber && not_done;++k){
            if(A.TF[j][k]!=-1){//fiber and therefore plate is used
                A.suborder.push_back(j);//suborder[jused] is jused-th used plate
                not_done=false;
                A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
                                //and otherwise the position of plate j in list of used plates
                inv_count++;
            }
        }
    }
    F.NUsedplate=A.suborder.size();
    printf(" Plates actually used %d \n",F.NUsedplate);

    if(F.diagnose)diagnostic(M,Secret,F,A);

    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
    
    // Smooth out distribution of free fibers, and increase the number of assignments
    
    for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
    for (int i=0; i<1; i++) {
        improve(M,P,pp,F,A,0);
        redistribute_tf(M,P,pp,F,A,0);
    }
    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
    //try assigning SF and SS before real time assignment
    for (int jused=0;jused<F.NUsedplate;++jused){
        int j=A.suborder[jused];
        assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
        assign_unused(j,M,P,pp,F,A);
    }
    if(F.diagnose)diagnostic(M,Secret,F,A);
    init_time_at(time,"# Begin real time assignment",t);

    //Execute plan, updating targets at intervals
    for(int i=0;i<F.pass_intervals.size();i++){
        printf(" i=%d interval %d \n",i,F.pass_intervals[i]);
    }
    std::vector <int> update_intervals=F.pass_intervals;
    update_intervals.push_back(F.NUsedplate);//to end intervals at last plate
    for(int i=0;i<update_intervals.size();++i){
        printf("i %d  update_interval %d\n",i, update_intervals[i]);
    }
    for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate
        int starter=update_intervals[i];
        printf("-- interval %d\n",i);
        for (int jused=starter; jused<update_intervals[i+1] && jused<A.suborder.size()-1; jused++) {

            if (0<=jused-F.Analysis) {
                update_plan_from_one_obs(jused,Secret,M,P,pp,F,A);
            }
            else printf("\n no update\n");
            // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else

        }
        printf("-- redistribute %d\n",i);        
        redistribute_tf(M,P,pp,F,A,starter);
        printf("-- improve %d\n",i);        
        improve(M,P,pp,F,A,starter);
        printf("-- improve again %d\n",i);        
        redistribute_tf(M,P,pp,F,A,starter);
        printf("-- diagnose %d\n",i);        
        if(F.diagnose)diagnostic(M,Secret,F,A);

    }
    // check on SS and SF

    printf("-- Checking SS/SF\n");
    List SS_hist=initList(11,0);
    List SF_hist=initList(41,0);
    for(int jused=0;jused<F.NUsedplate;++jused){
        int j=A.suborder[jused];
        for (int p=0;p<F.Npetal;++p){
            int count_SS=0;
            int count_SF=0;
            for (int k=0;k<F.Nfbp;++k){
                int kk=pp.fibers_of_sp[p][k];
                int g=A.TF[j][kk];
                if(g!=-1 && M[g].SS)count_SS++;
                if(g!=-1 && M[g].SF)count_SF++;
            }
            SS_hist[count_SS]++;
            SF_hist[count_SF]++;
        }
    }
    printf(" SS distribution \n");
    for(int i=0;i<10;i++)printf("%8d",SS_hist[i]);
    printf("\n %8d \n",SS_hist[10]);
 
    printf(" SF distribution \n");
    for(int i=0;i<10;i++)printf("%8d",SF_hist[i]);
    printf("\n");
    for(int i=10;i<20;i++)printf("%8d",SF_hist[i]);
    printf("\n");
    for(int i=20;i<30;i++)printf("%8d",SF_hist[i]);
    printf("\n");
    for(int i=30;i<40;i++)printf("%8d",SF_hist[i]);
    printf("\n %8d \n",SF_hist[40]);

    

 
    // Results -------------------------------------------------------
    if (F.PrintAscii){
        for (int jused=0; jused<F.NUsedplate; jused++){
            int j=A.suborder[jused];
            write_FAtile_ascii(A.suborder[jused],F.outDir,M,P,pp,F,A);
        }
    }
    
    if (F.PrintFits) {
        for (int jused=0; jused<F.NUsedplate; jused++){
            int j=A.suborder[jused];
            fa_write(A.suborder[jused],F.outDir,M,P,pp,F,A); // Write outpu
        }
    }
    

	display_results("doc/figs/",Secret,M,P,pp,F,A,F.Nplate,true);
	if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane


    print_time(t,"# Finished !... in");

    return(0);
  
}
Exemplo n.º 3
0
int main(void)
{
    // seed pseudorandom number generator
    srand48(time(NULL));

    // instantiate window
    GWindow window = newGWindow(WIDTH, HEIGHT);

    // instantiate bricks
    initBricks(window);

    // instantiate ball, centered in middle of window
    GOval ball = initBall(window);

    // instantiate paddle, centered at bottom of window
    GRect paddle = initPaddle(window);
    
    // instantiate scoreboard, centered in middle of window, just above ball
    GLabel label = initScoreboard(window);

    // number of bricks initially
    int bricks = COLS * ROWS;

    // number of lives initially
    int lives = LIVES;

    // number of points initially
    int points = 0;

    // keep playing until game over
    while (lives > 0 && bricks > 0)
    {
        // SCORE
        updateScoreboard(window,label,points);  
        
        // BALL
        /* BOUNCING */
        move(ball, x_velocity, y_velocity);
        pause(10);
        
        // MOUSE EVENT
        GEvent event = getNextEvent(MOUSE_EVENT);
        if (event != NULL)
        {
            /* if mouse was moved */
            if (getEventType(event) == MOUSE_MOVED)
            {
                /*move paddle were mouse goes */
                double x = getX(event) - getWidth(paddle) / 2;
                double y = 400;
                setLocation(paddle, x, y);
            }
        }
        
        /* Collision */
        /* ball touching paddle */
        GObject object = detectCollision(window, ball);
        if (object != NULL)
        {
            if (object == paddle)
            {
                y_velocity = -y_velocity;
            }
            else if (object != paddle)
            {
                if (strcmp(getType(object), "GRect") == 0)
                {
                    removeGWindow(window,object);
                    y_velocity = -y_velocity;
                    points++;
                    bricks--;
                }
            }
        }
        
        /* ball touching wall on the right */
        if (getX(ball) + getWidth(ball) >= getWidth(window))
        {
            x_velocity = -x_velocity;
        }
        /* ball touching wall on the left */
        if (getX(ball) <= 0)
        {
            x_velocity = -x_velocity;
        }
        /* ball touching wall on the top */
        if (getY(ball) <= 0)
        {
            y_velocity = -y_velocity;
        }
        /* ball touching wall on the bottom */
        if (getY(ball) + getHeight(ball) >= getHeight(window))
        {
            setLocation(ball,190,300);
            setLocation(paddle, 190, 400);
            lives--;
            waitForClick();
        }
    }
      
    //  END MESSAGE
    if (bricks > 0)
    {
        GLabel end = newGLabel("GAME OVER!");
        setFont(end,"SandSerif-50");
        setColor(end, "BLUE");
        add(window,end);
        setLocation(end,25,300);
    }
    else if (bricks == 0)
    {
        GLabel end = newGLabel("WINNER!");
        setFont(end,"SandSerif-50");
        setColor(end, "BLUE");
        add(window,end);
        setLocation(end,25,300);
    }

    // wait for click before exiting
    waitForClick();

    // game over
    closeGWindow(window);
    return 0;
}
Exemplo n.º 4
0
void
random_rdwr_mp (int fd, long long blocks, int procs, int min_xfer_size,
		int max_xfer_size, int rdwr_iterations, int rwpercent,
		int do_log, int skip_block_zero)
{
  static long long random_block;
  static long int charsread, charswrote;
  static long int rdwr_size;
  static long int elapsed_time;
  static long int start_time;
  static long int stop_time;
  static int p, j, count;
  static pid_t pid;
  static int i;
  static long int IOrate;
  static long long data_rate;

#if DEBUG
  long min, max;
#endif

  static char real_wrbuffer[MAX_TRANSFER_SIZE+512];
  char *wrbuffer;
  static char *rbuffer = NULL;
  static int rdwr_rand;
  static int rdwr_type;

  /* Align the buffer */
  wrbuffer = (char *)(((unsigned long long)real_wrbuffer+512) & ~0x1ff);
  if (rbuffer == NULL) {
	rbuffer = mmap(NULL, MAX_TRANSFER_SIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
        if (rbuffer == NULL)
		err(1, "failed to get read buffer\n");
  }
  for (i = 1; i <= (int) max_xfer_size; ++i)
    wrbuffer[i] = (char) i;
  rdwr_size = min_xfer_size;
  blocks = blocks - 1;		/*Turn # of blocks into highest block # */
  blocks = blocks - (MAX_TRANSFER_SIZE / 512);	/*stay away from the end */

#ifndef NO_BUFFER
  blocks = blocks - 3000;
#endif

#if DEBUG
  min = 10000;
  max = blocks - 10000;
#endif
#ifdef DEBUG
  printf ("blocks=%lld procs=%d min=%d max=%d iter=%d per=%d\n", blocks,
	  procs, min_xfer_size, max_xfer_size, rdwr_iterations, rwpercent);
#endif

  while (rdwr_size <= max_xfer_size) {
    start_time = MSTime ();
    pid = 1;
    /*i = 0; */
    j = 0;
    for (p = 1; p <= procs; ++p) {
/*  Seed the random number generator.  Adding "p" insures that   */
/*  each seed is different, and that each child gets a different */
/*  sequence of random numbers.  That way, two consecutive IO's  */
/*  can't go to the same random block.                           */
      srand48 ((unsigned int) time (NULL) + p);

/*  fork 'procs' number of child processes, each executing the benchmark code */
/*  if pid = 0, you're in a forked process, if pid > 0, you're in the parent   */
      pid = fork ();
      if (pid == 0)
	break;
    }

    switch (pid) {
    case -1:
      exit (EXIT_FAILURE);
    case 0:
      count = 0;
      while (count < rdwr_iterations) {
	random_block = (drand48 () * (blocks - 1) + skip_block_zero);

#if DEBUG
	if (min > random_block)
	  min = random_block;
	if (max < random_block)
	  max = random_block;
#endif
#ifdef _LARGEFILE64_SOURCE
	if ((lseek64 (fd, (off64_t) (random_block * 512), SEEK_SET)) < 0) {
	  perror ("IOtest: lseek64");
	  exit (EXIT_FAILURE);
	}
#else
	if ((lseek (fd, (long) (random_block * 512), SEEK_SET)) < 0) {
	  perror ("IOtest: lseek");
	  exit (EXIT_FAILURE);
	}
#endif
	/*  Read or Write ????????? */
	/* if rwpercent = 0, this is a write only test  */
	/* if rwpercent = 100, this is a read only test */
	/* else its read/write                          */
	switch (rwpercent) {
	case 0:
	  rdwr_type = DO_WRITE;
	  break;
	case 100:
	  rdwr_type = DO_READ;
	  break;

	  /* If we get here, it's a read/write test.    */
	  /* generate a random number between 0 and 100 */
	  /* and compare it to the requested read/write */
	  /* percentage                                 */

	default:
	  rdwr_rand = ((float) rand () / RAND_MAX) * 100;
	  rdwr_type = (rdwr_rand >= rwpercent) ? DO_WRITE : DO_READ;
	  break;
	}

	switch (rdwr_type) {
	case DO_READ:

	  if ((charsread = (long int) read (fd, rbuffer, (size_t) rdwr_size)) < 0) {
	    perror ("IOtest: read");
	    printf
	      ("Error during transfer of %ld bytes starting at block %lld\n",
	       rdwr_size, random_block);
	    exit (EXIT_FAILURE);
	  }
	  if (charsread != rdwr_size) {
	    printf
	      ("%ld of %ld bytes read starting at block %lld\n",
	       charsread, rdwr_size, random_block);
	    exit (EXIT_FAILURE);
	  }
	  break;

	case DO_WRITE:
	  if ((charswrote = (long int) write (fd, wrbuffer, (size_t) rdwr_size)) < 0) {
	    perror ("IOtest: write");
	    printf
	      ("Error during transfer of %ld bytes starting at block %lld\n",
	       rdwr_size, random_block);
	    exit (EXIT_FAILURE);
	  }
	  if (charswrote != rdwr_size) {
	    printf
	      ("%ld of %ld bytes written starting at block %lld\n",
	       charswrote, rdwr_size, random_block);
	    exit (EXIT_FAILURE);
	  }
	  break;

	default:
	  break;
	}

#if _Shared_mem_for_rbuffer
/* touch each block in rbuffer to make sure data is really there   */
	if (DO_READ) {
	  for (j = 0; j < (int) rdwr_size; j += 512)
	    /*printf(" %d",j); */
	    rbuffer[j] &= 1;
	}
	/*printf("\n"); */
#endif

	count++;
      }

#if DEBUG
      printf ("blocks = %lld min block # = %ld  max block # = %ld \n", blocks, min, max);
#endif
      exit (EXIT_SUCCESS);
    default:
#if DEBUG
      printf ("This is the parent.. pid = %d\n", (int) getpid ());
#endif
      break;
    }
    /* Wait until all the children have finished   */
    if (pid > 0) {
      /*int stat_val; */
#if DEBUG
      printf ("Waiting for child..\n");
#endif
      for (p = 1; p <= procs; ++p) {
	static pid_t child_exit_status;
	child_exit_status = wait (NULL);
#if DEBUG
	printf ("PID %d done..\n", (int) child_exit_status);
#endif
      }

      stop_time = MSTime ();
      elapsed_time = stop_time - start_time;

      data_rate =
	(((long
	   long) rdwr_size * (long long) rdwr_iterations *
	  (long long) procs) / (long long) (elapsed_time));
      IOrate = ((long long)rdwr_iterations * (long long)procs * 1000) / (int) elapsed_time;

#ifndef _NEW_OUTPUT_FORMAT

      if (rwpercent == 100) {
	sprintf (buf, "%6ld byte read   ET=%9.3f secs  \
IOs/second = %5ld  Data Rate = %6.3f MBs\n", rdwr_size, (float) elapsed_time / 1000, IOrate, (double) data_rate / 1024);
      } else if (rwpercent == 0) {
Exemplo n.º 5
0
BOOL
PALAPI
PAL_Random(
        IN BOOL bStrong,
        IN OUT LPVOID lpBuffer,
        IN DWORD dwLength)
{
    int rand_des = -1;
    BOOL bRet = FALSE;
    DWORD i;
    char buf;
    long num = 0;
    static BOOL sMissingDevRandom;
    static BOOL sMissingDevURandom;
    static BOOL sInitializedMRand;

    PERF_ENTRY(PAL_Random);
    ENTRY("PAL_Random(bStrong=%d, lpBuffer=%p, dwLength=%d)\n", 
          bStrong, lpBuffer, dwLength);

    i = 0;

    if (bStrong == TRUE && i < dwLength && !sMissingDevRandom)
    {
        // request non-blocking access to avoid hangs if the /dev/random is exhausted
        // or just simply broken
        if ((rand_des = PAL__open(RANDOM_DEVICE_NAME, O_RDONLY | O_NONBLOCK)) == -1)
        {
            if (errno == ENOENT)
            {
                sMissingDevRandom = TRUE;
            }
            else
            {
                ASSERT("PAL__open() failed, errno:%d (%s)\n", errno, strerror(errno));
            }

            // Back off and try /dev/urandom.
        }
        else
        {
            for( ; i < dwLength; i++)
            {
                if (read(rand_des, &buf, 1) < 1)
                {
                    // the /dev/random pool has been exhausted.  Fall back
                    // to /dev/urandom for the remainder of the buffer.
                    break;
                }

                *(((BYTE*)lpBuffer) + i) ^= buf;
            }

            close(rand_des);
        }
    }
 
    if (i < dwLength && !sMissingDevURandom)
    {
        if ((rand_des = PAL__open(URANDOM_DEVICE_NAME, O_RDONLY)) == -1)
        {
            if (errno == ENOENT)
            {                
                sMissingDevURandom = TRUE;                
            }
            else
            {
                ASSERT("PAL__open() failed, errno:%d (%s)\n", errno, strerror(errno));               
            }

            // Back off and try mrand48.           
        }
        else
        {
            for( ; i < dwLength; i++)
            {
                if (read(rand_des, &buf, 1) < 1)
                {
                    // Fall back to srand48 for the remainder of the buffer.
                    break;
                }

                *(((BYTE*)lpBuffer) + i) ^= buf;
            }

            close(rand_des);
        }
    }    

    if (!sInitializedMRand)
    {
        srand48(time(NULL));
        sInitializedMRand = TRUE;
    }

    // always xor srand48 over the whole buffer to get some randomness
    // in case /dev/random is not really random

    for(i = 0; i < dwLength; i++)
    {
        if (i % sizeof(long) == 0) {
            num = mrand48();
        }

        *(((BYTE*)lpBuffer) + i) ^= num;
        num >>= 8;
    }

    bRet = TRUE;

    LOGEXIT("PAL_Random returns %d\n", bRet);
    PERF_EXIT(PAL_Random);
    return bRet;
}
Exemplo n.º 6
0
int
main(int argc, char **argv)
{
  int c;
  sigset_t set;
  const char *cfgfile = NULL;
  const char *jobfile = NULL;
  const char *defconf = "doozer-agent.json";

  signal(SIGPIPE, handle_sigpipe);

  while((c = getopt(argc, argv, "c:s:j:")) != -1) {
    switch(c) {
    case 'c':
      cfgfile = optarg;
      break;
    case 's':
      enable_syslog("doozer-agent", optarg);
      break;
    case 'j':
      jobfile = optarg;
      break;
    }
  }

  sigfillset(&set);
  sigprocmask(SIG_BLOCK, &set, NULL);

  srand48(getpid() ^ time(NULL));

  if(cfg_load(cfgfile, defconf)) {
    fprintf(stderr, "Unable to load config (check -c option). Giving up\n");
    exit(1);
  }

  create_heaps();

  if(geteuid() == 0) {

    get_uid_gid();

    if(setgid(build_gid)) {
      trace(LOG_ERR, "Unable to setgid(%d) -- %s", build_gid,
            strerror(errno));
      exit(1);
    }

    if(seteuid(build_uid)) {
      trace(LOG_ERR, "Unable to seteuid(%d) -- %s", build_uid,
            strerror(errno));
    }
  }

  git_threads_init();

  artifact_init();

  agent_init(jobfile);

  running = 1;
  sigemptyset(&set);
  sigaddset(&set, SIGTERM);
  sigaddset(&set, SIGINT);
  sigaddset(&set, SIGHUP);

  signal(SIGTERM, doexit);
  signal(SIGINT, doexit);
  signal(SIGHUP, doreload);

  pthread_sigmask(SIG_UNBLOCK, &set, NULL);

  while(running) {
    if(reload) {
      reload = 0;
      if(!cfg_load(NULL, defconf)) {
      }
    }
    pause();
  }

  spawn_stop_all();
  trace(LOG_NOTICE, "Waiting for jobs to stop");
  agent_join();
  return 0;
}
Exemplo n.º 7
0
int main(int argc, char *argv[]) {
  int i;
  int row;
  int col;
  time_t start;
  time_t finish;

  if (argc != 3) {
    fprintf(stderr, "The arguments should be ./matrix_sum size_of_matrix number_of_threads\n");
    return 1;
  }

  SIZE_OF_MATRIX    = atoi(argv[1]);
  NUMBER_OF_THREADS = atoi(argv[2]);
  omp_set_num_threads(NUMBER_OF_THREADS);

  printf("Number of procs is %d\n",        omp_get_num_procs());
  printf("The number of threads is %d\n",  NUMBER_OF_THREADS);
  printf("Max number of threads is %d\n",  omp_get_max_threads());

  double **matrix            = malloc(sizeof(double) * SIZE_OF_MATRIX);
  double **matrix_copy       = malloc(sizeof(double) * SIZE_OF_MATRIX);
  double *answer_vector      = malloc(sizeof(double) * SIZE_OF_MATRIX);
  double *answer_vector_copy = malloc(sizeof(double) * SIZE_OF_MATRIX);
  double *answers            = malloc(sizeof(double) * SIZE_OF_MATRIX);


  for (i = 0; i < SIZE_OF_MATRIX; ++i) {
    matrix[i]      = malloc(sizeof(double) * SIZE_OF_MATRIX);
    matrix_copy[i] = malloc(sizeof(double) * SIZE_OF_MATRIX);
  }

  srand48(time(NULL)); // seed random number

  fill_matrix(matrix, matrix_copy);
  fill_answer(answer_vector, answer_vector_copy);

  // Start Timing
  start = time(NULL);

  // Start elimination
  row = 0;
  col = 0;
  int j;
  for (row = 0; row < SIZE_OF_MATRIX; ++row) {
    pivot_on_row(row, matrix, answer_vector);

    #pragma omp parallel for
      for (i = 0; i < SIZE_OF_MATRIX; ++i) {
        convert_to_upper_triangle(row, matrix, answer_vector);
      }
  }
  back_subsitution(matrix, answer_vector, answers);

  // Finish Timing
  finish = time(NULL);

  double seconds = (double) difftime(finish, start);

  printf("Time Taken: %f\n", seconds);

  double l2 = 0;

  double total = 0;
  for (i = 0; i < SIZE_OF_MATRIX; ++i) {
    for (j = 0; j < SIZE_OF_MATRIX; ++j) {
      total = total + matrix_copy[i][j] * answers[j];
    }
    l2 = l2 + pow( (total - answer_vector_copy[i]), 2);
    total = 0;
  }

  l2 = sqrt(l2);

  printf("L2 norm is %g\n", l2);

  free(matrix);
  free(matrix_copy);
  free(answer_vector);
  free(answer_vector_copy);
  free(answers);

  return 0;
}
Exemplo n.º 8
0
int main(int argc, char **argv) {
    srand(time(nullptr));
    srand48(time(nullptr));
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
Exemplo n.º 9
0
int main(int argc, char** argv)
{
	/* ARG PARSER *****************************************************/
	std::vector<std::string> fn_input;
	std::string fn_output;
	std::string integrandName;
	int nPts;
	
	boostPO::variables_map vm;
	boostPO::options_description desc("Allowed options");
	desc.add_options()
		("help,h",
			"produce help message")
		("input,i",
			boostPO::value(&fn_input)->composing(),
			"list of pointsets: each file must contains multiple pointsets with the same number of points")
		("integrand,I",
			boostPO::value(&integrandName),
			"integrand function: gaussian, disk or a filename (hdr image)")
		("output,o",
			boostPO::value(&fn_output)->required(),
			"output filename");
	
	boostPO::positional_options_description p;
	p.add("input", -1);
	
	try
	{	
		boostPO::store(
			boostPO::command_line_parser(argc, argv).
				options(desc).positional(p).run(), vm);
		boostPO::notify(vm);
	}
	catch(boost::program_options::error& e)
	{
		std::cerr << e.what() << std::endl;
		std::cout << desc << std::endl;
		exit(EXIT_FAILURE);
	}
	
	if(vm.count("help"))
	{
		std::cout << desc << std::endl;
		exit(EXIT_SUCCESS);
	}
	
	/* INIT ***********************************************************/
	
	srand48(time(NULL));
	
	double integrandShiftX = 0.0f;
	double integrandShiftY = 0.0f;
	
	IntegrandFunction integrandFunction;
	if(integrandName == "gaussian")
	{
		integrandFunction = gaussianFunction;
		integrandShiftX = 0.5;
		integrandShiftY = 0.5;
	}
	else if(integrandName == "disk")
	{
		integrandFunction = diskFunction;
		integrandShiftX = 0.5;
		integrandShiftY = 0.5;
	}
	else if(integrandName == "cos")
	{
		integrandFunction = cosFunction;
		integrandShiftX = 0.0;
		integrandShiftY = 0.0;
	}
	else
	{
		g_hdrFilename = integrandName;
		loadHdrImg();
		integrandFunction = hdrFunction;
		integrandShiftX = 0.0;
		integrandShiftY = 0.0;
	}

	std::ofstream file(fn_output.c_str());
	
	for(int n=0; n<fn_input.size(); ++n)
	{
		double nPts = 0;
		int iter = 0;
		double mean = 0;
		double m2 = 0;
		
		stk::io::PointSetInputStream<2, double, double> stream(fn_input[n]);
		do
		{
			//Read pointset
			stk::PointSet2dd pts;
			stream.read(pts);
			
			bool skip = false;
			
			if(!skip)
			{
				nPts += pts.size();
					
				double integration = 0.0f;
				
				stk::Vector2d shift(drand48(), drand48());
				for(int i=0; i<pts.size(); ++i)
				{
					pts[i].pos() += shift;
				}
				pts.normalize();
			
				for(int i=0; i<pts.size(); i++)
				{
					const int r=0;
					for(int y=-r; y<=r; ++y)
					{
						for(int x=-r; x<=r; ++x)
						{
							integration += integrandFunction(
								pts[i].pos()[0]-integrandShiftX+static_cast<double>(x),
								pts[i].pos()[1]-integrandShiftY+static_cast<double>(y)
							);
						}
					}
				}
				integration /= pts.size();
				
				iter++;
				
				double delta = integration - mean;
				mean += delta/iter;
				m2 += delta*(integration - mean);
			}
		}
		while(stream.next());
		
		stream.close();
		
		if(iter > 500)
		{
			nPts /= iter;
			file << nPts << "\t" << mean << "\t" << m2/(iter-1) << std::endl;
			
			std::cout << iter << " x " << nPts << "pts" << std::endl;
		}
	}
	
	file.close();
	
	exit(EXIT_SUCCESS);
}
Exemplo n.º 10
0
int main(int Argc, char *Argv[]) {
    int argc;
    char *argv[128];
    lGetAllArgs(Argc, Argv, argc, argv);

    llvm::sys::AddSignalHandler(lSignal, NULL);

    // initialize available LLVM targets
    LLVMInitializeX86TargetInfo();
    LLVMInitializeX86Target();
    LLVMInitializeX86AsmPrinter();
    LLVMInitializeX86AsmParser();
    LLVMInitializeX86Disassembler();
    LLVMInitializeX86TargetMC();

    char *file = NULL;
    const char *headerFileName = NULL;
    const char *outFileName = NULL;
    const char *includeFileName = NULL;
    const char *depsFileName = NULL;
    const char *hostStubFileName = NULL;
    const char *devStubFileName = NULL;
    // Initiailize globals early so that we can set various option values
    // as we're parsing below
    g = new Globals;

    bool debugSet = false, optSet = false;
    Module::OutputType ot = Module::Object;
    bool generatePIC = false;
    const char *arch = NULL, *cpu = NULL, *target = NULL;

    for (int i = 1; i < argc; ++i) {
        if (!strcmp(argv[i], "--help"))
            usage(0);
        if (!strcmp(argv[i], "--help-dev"))
            devUsage(0);
        else if (!strncmp(argv[i], "-D", 2))
            g->cppArgs.push_back(argv[i]);
        else if (!strncmp(argv[i], "--addressing=", 13)) {
            if (atoi(argv[i] + 13) == 64)
                g->opt.force32BitAddressing = false;
            else if (atoi(argv[i] + 13) == 32)
                g->opt.force32BitAddressing = true;
            else {
                fprintf(stderr, "Addressing width \"%s\" invalid--only 32 and "
                        "64 are allowed.\n", argv[i]+13);
                usage(1);
            }
        }
        else if (!strncmp(argv[i], "--arch=", 7))
            arch = argv[i] + 7;
        else if (!strncmp(argv[i], "--cpu=", 6))
            cpu = argv[i] + 6;
        else if (!strcmp(argv[i], "--fast-math")) {
            fprintf(stderr, "--fast-math option has been renamed to --opt=fast-math!\n");
            usage(1);
        }
        else if (!strcmp(argv[i], "--fast-masked-vload")) {
            fprintf(stderr, "--fast-masked-vload option has been renamed to "
                    "--opt=fast-masked-vload!\n");
            usage(1);
        }
        else if (!strcmp(argv[i], "--debug"))
            g->debugPrint = true;
        else if (!strcmp(argv[i], "--instrument"))
            g->emitInstrumentation = true;
        else if (!strcmp(argv[i], "-g")) {
            g->generateDebuggingSymbols = true;
            debugSet = true;
        }
        else if (!strcmp(argv[i], "--emit-asm"))
            ot = Module::Asm;
        else if (!strcmp(argv[i], "--emit-c++"))
            ot = Module::CXX;
        else if (!strcmp(argv[i], "--emit-llvm"))
            ot = Module::Bitcode;
        else if (!strcmp(argv[i], "--emit-obj"))
            ot = Module::Object;
        else if (!strcmp(argv[i], "-I")) {
            if (++i == argc) {
                fprintf(stderr, "No path specified after -I option.\n");
                usage(1);
            }
            g->includePath.push_back(argv[i]);
        }
        else if (!strncmp(argv[i], "-I", 2))
            g->includePath.push_back(argv[i]+2);
        else if (!strcmp(argv[i], "--fuzz-test"))
            g->enableFuzzTest = true;
        else if (!strncmp(argv[i], "--fuzz-seed=", 12))
            g->fuzzTestSeed = atoi(argv[i] + 12);
        else if (!strcmp(argv[i], "--target")) {
            // FIXME: should remove this way of specifying the target...
            if (++i == argc) {
                fprintf(stderr, "No target specified after --target option.\n");
                usage(1);
            }
            target = argv[i];
        }
        else if (!strncmp(argv[i], "--target=", 9))
            target = argv[i] + 9;
        else if (!strncmp(argv[i], "--math-lib=", 11)) {
            const char *lib = argv[i] + 11;
            if (!strcmp(lib, "default"))
                g->mathLib = Globals::Math_ISPC;
            else if (!strcmp(lib, "fast"))
                g->mathLib = Globals::Math_ISPCFast;
            else if (!strcmp(lib, "svml"))
                g->mathLib = Globals::Math_SVML;
            else if (!strcmp(lib, "system"))
                g->mathLib = Globals::Math_System;
            else {
                fprintf(stderr, "Unknown --math-lib= option \"%s\".\n", lib);
                usage(1);
            }
        }
        else if (!strncmp(argv[i], "--opt=", 6)) {
            const char *opt = argv[i] + 6;
            if (!strcmp(opt, "fast-math"))
                g->opt.fastMath = true;
            else if (!strcmp(opt, "fast-masked-vload"))
                g->opt.fastMaskedVload = true;
            else if (!strcmp(opt, "disable-assertions"))
                g->opt.disableAsserts = true;
            else if (!strcmp(opt, "disable-loop-unroll"))
                g->opt.unrollLoops = false;

            // These are only used for performance tests of specific
            // optimizations
            else if (!strcmp(opt, "disable-all-on-optimizations"))
                g->opt.disableMaskAllOnOptimizations = true;
            else if (!strcmp(opt, "disable-coalescing"))
                g->opt.disableCoalescing = true;
            else if (!strcmp(opt, "disable-handle-pseudo-memory-ops"))
                g->opt.disableHandlePseudoMemoryOps = true;
            else if (!strcmp(opt, "disable-blended-masked-stores"))
                g->opt.disableBlendedMaskedStores = true;
            else if (!strcmp(opt, "disable-coherent-control-flow"))
                g->opt.disableCoherentControlFlow = true;
            else if (!strcmp(opt, "disable-uniform-control-flow"))
                g->opt.disableUniformControlFlow = true;
            else if (!strcmp(opt, "disable-gather-scatter-optimizations"))
                g->opt.disableGatherScatterOptimizations = true;
            else if (!strcmp(opt, "disable-blending-removal"))
                g->opt.disableMaskedStoreToStore = true;
            else if (!strcmp(opt, "disable-gather-scatter-flattening"))
                g->opt.disableGatherScatterFlattening = true;
            else if (!strcmp(opt, "disable-uniform-memory-optimizations"))
                g->opt.disableUniformMemoryOptimizations = true;
            else {
                fprintf(stderr, "Unknown --opt= option \"%s\".\n", opt);
                usage(1);
            }
        }
        else if (!strcmp(argv[i], "--woff") || !strcmp(argv[i], "-woff")) {
            g->disableWarnings = true;
            g->emitPerfWarnings = false;
        }
        else if (!strcmp(argv[i], "--werror"))
            g->warningsAsErrors = true;
        else if (!strcmp(argv[i], "--nowrap"))
            g->disableLineWrap = true;
        else if (!strcmp(argv[i], "--wno-perf") || !strcmp(argv[i], "-wno-perf"))
            g->emitPerfWarnings = false;
        else if (!strcmp(argv[i], "-o")) {
            if (++i == argc) {
                fprintf(stderr, "No output file specified after -o option.\n");
                usage(1);
            }
            outFileName = argv[i];
        }
        else if (!strncmp(argv[i], "--outfile=", 10))
            outFileName = argv[i] + strlen("--outfile=");
        else if (!strcmp(argv[i], "-h")) {
            if (++i == argc) {
                fprintf(stderr, "No header file name specified after -h option.\n");
                usage(1);
            }
            headerFileName = argv[i];
        }
        else if (!strncmp(argv[i], "--header-outfile=", 17)) {
            headerFileName = argv[i] + strlen("--header-outfile=");
        }
        else if (!strncmp(argv[i], "--c++-include-file=", 19)) {
            includeFileName = argv[i] + strlen("--c++-include-file=");
        }
        else if (!strcmp(argv[i], "-O0")) {
            g->opt.level = 0;
            optSet = true;
        }
        else if (!strcmp(argv[i], "-O") ||  !strcmp(argv[i], "-O1") || 
                 !strcmp(argv[i], "-O2") || !strcmp(argv[i], "-O3")) {
            g->opt.level = 1;
            optSet = true;
        }
        else if (!strcmp(argv[i], "-"))
            ;
        else if (!strcmp(argv[i], "--nostdlib"))
            g->includeStdlib = false;
        else if (!strcmp(argv[i], "--nocpp"))
            g->runCPP = false;
#ifndef ISPC_IS_WINDOWS
        else if (!strcmp(argv[i], "--pic"))
            generatePIC = true;
        else if (!strcmp(argv[i], "--colored-output"))
            g->forceColoredOutput = true;
#endif // !ISPC_IS_WINDOWS
        else if (!strcmp(argv[i], "--quiet"))
            g->quiet = true;
        else if (!strcmp(argv[i], "--yydebug")) {
            extern int yydebug;
            yydebug = 1;
        }
        else if (!strcmp(argv[i], "-MMM")) {
          if (++i == argc) {
            fprintf(stderr, "No output file name specified after -MMM option.\n");
            usage(1);
          }
          depsFileName = argv[i];
        }
        else if (!strcmp(argv[i], "--dev-stub")) {
          if (++i == argc) {
            fprintf(stderr, "No output file name specified after --dev-stub option.\n");
            usage(1);
          }
          devStubFileName = argv[i];
        }
        else if (!strcmp(argv[i], "--host-stub")) {
          if (++i == argc) {
            fprintf(stderr, "No output file name specified after --host-stub option.\n");
            usage(1);
          }
          hostStubFileName = argv[i];
        }
        else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version")) {
            lPrintVersion();
            return 0;
        }
        else if (argv[i][0] == '-') {
            fprintf(stderr, "Unknown option \"%s\".\n", argv[i]);
            usage(1);
        }
        else {
            if (file != NULL) {
                fprintf(stderr, "Multiple input files specified on command "
                        "line: \"%s\" and \"%s\".\n", file, argv[i]);
                usage(1);
            }
            else
                file = argv[i];
        }
    }

    // If the user specified -g, then the default optimization level is 0.
    // If -g wasn't specified, the default optimization level is 1 (full
    // optimization).
    if (debugSet && !optSet)
        g->opt.level = 0;

    if (g->enableFuzzTest) {
        if (g->fuzzTestSeed == -1) {
#ifdef ISPC_IS_WINDOWS
            int seed = (unsigned)time(NULL);
#else
            int seed = getpid();
#endif
            g->fuzzTestSeed = seed;
            Warning(SourcePos(), "Using seed %d for fuzz testing", 
                    g->fuzzTestSeed);
        }
#ifdef ISPC_IS_WINDOWS
        srand(g->fuzzTestSeed);
#else
        srand48(g->fuzzTestSeed);
#endif
    }

    if (outFileName == NULL && 
        headerFileName == NULL &&
        depsFileName == NULL &&
        hostStubFileName == NULL &&
        devStubFileName == NULL)
      Warning(SourcePos(), "No output file or header file name specified. "
              "Program will be compiled and warnings/errors will "
              "be issued, but no output will be generated.");

    return Module::CompileAndOutput(file, arch, cpu, target, generatePIC,
                                    ot, 
                                    outFileName, 
                                    headerFileName, 
                                    includeFileName,
                                    depsFileName,
                                    hostStubFileName,
                                    devStubFileName);
}
/*==========================================
 * main
 *========================================== */
int main(int argc, char* argv[])
{
    int T; // number of topics
    int W; // number of unique words
    int D; // number of docs
    int N; // number of words in corpus

    int i, iter, seed;
    int *w, *d, *z, *order;
    double **Nwt, **Ndt, *Nt;
    double alpha, beta;

    if (argc == 1) {
        fprintf(stderr, "usage: %s T iter seed\n", argv[0]);
        exit(-1);
    }
    T    = atoi(argv[1]);
    assert(T>0);
    iter = atoi(argv[2]);
    assert(iter>0);
    seed = atoi(argv[3]);
    assert(seed>0);

    N = countN("docword.txt");
    w = ivec(N);
    d = ivec(N);
    z = ivec(N);
    read_dw("docword.txt", d, w, &D, &W);
    Nwt = dmat(W,T);
    Ndt = dmat(D,T);
    Nt  = dvec(T);

    alpha = 0.05 * N / (D * T);
    beta  = 0.01;

    printf("seed  = %d\n", seed);
    printf("N     = %d\n", N);
    printf("W     = %d\n", W);
    printf("D     = %d\n", D);
    printf("T     = %d\n", T);
    printf("iter  = %d\n", iter);
    printf("alpha = %f\n", alpha);
    printf("beta  = %f\n", beta);

    srand48(seed);
    randomassignment_d(N,T,w,d,z,Nwt,Ndt,Nt);
    order = randperm(N);

    add_smooth_d(D,T,Ndt,alpha);
    add_smooth_d(W,T,Nwt,beta);
    add_smooth1d(  T,Nt, W*beta);

    for (i = 0; i < iter; i++) {
        sample_chain_d(N,W,T,w,d,z,Nwt,Ndt,Nt,order);
        printf("iter %d \n", i);
    }

    printf("In-Sample Perplexity = %.2f\n",pplex_d(N,W,T,w,d,Nwt,Ndt));

    add_smooth_d(D,T,Ndt,-alpha);
    add_smooth_d(W,T,Nwt,-beta);
    add_smooth1d(  T,Nt, -W*beta);

    write_sparse_d(W,T,Nwt,"Nwt.txt");
    write_sparse_d(D,T,Ndt,"Ndt.txt");
    write_ivec(N,z,"z.txt");

    return 0;
}
Exemplo n.º 12
0
int defineSource(wavPar wav, srcPar src, float **src_nwav, int reverse, int verbose)
{
    FILE    *fp;
    size_t  nread;
    int optn, nfreq, i, j, k, iwmax, tracesToDo;
	int iw, n1, namp;
    float scl, d1, df, deltom, om, tshift;
	float amp1, amp2, amp3;
	float *trace, maxampl;
    complex *ctrace, tmp;
    segy hdr;
    
	n1 = wav.nt;
	if (wav.random) { /* initialize random sequence */
		srand48(wav.seed+1);
		seedCMWC4096();
		for (i=0; i<8192; i++) {
			amp1 = dcmwc4096();
		}

	}
	else {

/* read first header and last byte to get file size */

    	fp = fopen( wav.file_src, "r" );
    	assert( fp != NULL);
    	nread = fread( &hdr, 1, TRCBYTES, fp );
    	assert(nread == TRCBYTES);
	
/* read all traces */

		tracesToDo = wav.nx;
		i = 0;
		while (tracesToDo) {
			memset(&src_nwav[i][0],0,n1*sizeof(float));
        	nread = fread(&src_nwav[i][0], sizeof(float), hdr.ns, fp);
        	assert (nread == hdr.ns);
	
        	nread = fread( &hdr, 1, TRCBYTES, fp );
        	if (nread==0) break;
			tracesToDo--;
			i++;
		}
    	fclose(fp);
	}


	optn = optncr(2*n1);
	nfreq = optn/2 + 1;
	ctrace = (complex *)calloc(nfreq,sizeof(complex));
	trace = (float *)calloc(optn,sizeof(float));

	df     = 1.0/(optn*wav.dt);
    deltom = 2.*M_PI*df;
	scl    = 1.0/optn;
	maxampl=0.0;
	iwmax = nfreq;

	for (i=0; i<wav.nx; i++) {
		if (wav.random) {
			randomWavelet(wav, src, &src_nwav[i][0], src.tbeg[i], src.tend[i], verbose);
		}
		else {
			memset(&ctrace[0].r,0,nfreq*sizeof(complex));
			memset(&trace[0],0,optn*sizeof(float));
			memcpy(&trace[0],&src_nwav[i][0],n1*sizeof(float));
			rc1fft(trace,ctrace,optn,-1);
			/* Scale source from file with -j/w (=1/(jw)) for volume source injections
         	   no scaling is applied for volume source injection rates */
            if (src.injectionrate==0) {
                for (iw=1;iw<iwmax;iw++) {
                    om = 1.0/(deltom*iw);
                    tmp.r = om*ctrace[iw].i;
                    tmp.i = -om*ctrace[iw].r;
                    ctrace[iw].r = tmp.r;
                    ctrace[iw].i = tmp.i;
                }
            }
/*
*/
            if (src.type < 6) { // shift wavelet with +1/2 DeltaT due to staggered in time 
				tshift=0.5*wav.dt;
                for (iw=1;iw<iwmax;iw++) {
            		om = deltom*iw*tshift;
            		tmp.r = ctrace[iw].r*cos(-om) - ctrace[iw].i*sin(-om);
            		tmp.i = ctrace[iw].i*cos(-om) + ctrace[iw].r*sin(-om);
                    ctrace[iw].r = tmp.r;
                    ctrace[iw].i = tmp.i;
                }
			}

			/* zero frequency iw=0 set to 0 if the next sample has amplitude==0*/
			amp1 = sqrt(ctrace[1].r*ctrace[1].r+ctrace[1].i*ctrace[1].i);
			if (amp1 == 0.0) {
				ctrace[0].r = ctrace[0].i = 0.0;
			}
			else { /* stabilization for w=0: extrapolate amplitudes to 0 */
				amp2 = sqrt(ctrace[2].r*ctrace[2].r+ctrace[2].i*ctrace[2].i);
				amp3 = sqrt(ctrace[3].r*ctrace[3].r+ctrace[3].i*ctrace[3].i);
				ctrace[0].r = amp1+(2.0*(amp1-amp2)-(amp2-amp3));
				ctrace[0].i = 0.0;
				if (ctrace[1].r < 0.0) {
					ctrace[0].r *= -1.0;
				}
			}
			for (iw=iwmax;iw<nfreq;iw++) {
				ctrace[iw].r = 0.0;
				ctrace[iw].i = 0.0;
			}
			cr1fft(ctrace,trace,optn,1);
			/* avoid a (small) spike in the last sample 
			   this is done to avoid diffraction from last wavelet sample
			   which will act as a pulse */
			if (reverse) {
				for (j=0; j<n1; j++) src_nwav[i][j] = scl*(trace[n1-j-1]-trace[0]);
//				for (j=0; j<n1; j++) src_nwav[i][j] = scl*(trace[j]-trace[optn-1]);
			}
			else {
				for (j=0; j<n1; j++) src_nwav[i][j] = scl*(trace[j]-trace[optn-1]);
			}
		}

    }
    free(ctrace);
    free(trace);

/* use random amplitude gain factor for each source */
	if (src.amplitude > 0.0) {
		namp=wav.nx*10;
		trace = (float *)calloc(2*namp,sizeof(float));
		for (i=0; i<wav.nx; i++) {
			if (src.distribution) {
				scl = gaussGen()*src.amplitude;
				k = (int)MAX(MIN(namp*(scl+5*src.amplitude)/(10*src.amplitude),namp-1),0);
				d1 = 10.0*src.amplitude/(namp-1);
			}
			else {
				scl = (float)(drand48()-0.5)*src.amplitude;
				k = (int)MAX(MIN(namp*(scl+1*src.amplitude)/(2*src.amplitude),namp-1),0);
				d1 = 2.0*src.amplitude/(namp-1);
			}

			trace[k] += 1.0;
/*			trace[i] = scl; */
			if (wav.random) n1 = wav.nsamp[i];
			else n1 = wav.nt;
			for (j=0; j<n1; j++) {
				src_nwav[i][j] *= scl;
			}
    	}
		if (verbose>2) writesufile("src_ampl.su", trace, namp, 1, -5*src.amplitude, 0.0, d1, 1);
/*
		qsort(trace,wav.nx,sizeof(float), comp);
		for (i=0; i<wav.nx; i++) {
			scl = trace[i];
			trace[i] = normal(scl, 0.0, src.amplitude);
		}
		if (verbose>2) writesufile("src_ampl.su", trace, wav.nx, 1, -5*src.amplitude, 0.0, d1, 1);
*/

		free(trace);
	}

	if (verbose>3) writesufilesrcnwav("src_nwav.su", src_nwav, wav, wav.nt, wav.nx, 0.0, 0.0, wav.dt, 1);

/* set maximum amplitude in source file to 1.0 */
/*
	assert(maxampl != 0.0);
	scl = wav.dt/(maxampl);
	scl = 1.0/(maxampl);
	for (i=0; i<wav.nx; i++) {
		for (j=0; j<n1; j++) {
			src_nwav[i*n1+j] *= scl;
		}
    }
*/

    return 0;
}
Exemplo n.º 13
0
void 
client_loop(void)
{
    int pages = 0;
    int failcnt = 0;
    int termcount =0;
    int page_ceiling;
    int mode = 0;
    
    srand48( time (0) );

    page_ceiling = lrand48() % 40 * 1024 * 1024 / 4096;
    mb_register(0);

    while(1){

        if ( pages < page_ceiling && mode == 0 ){
            int ask = lrand48() % 200;
            int req;

            req = mb_request_pages ( ask );
            if ( req < 0 )
            {
                printf("transmission error\n");
                exit(0);
            } else if (req == 0 ) {
                if (failcnt > 10 ){
                    sleep(1);
                    failcnt = 0;
                    mode = 1;
                    termcount++;
                } else {
                    usleep(100);
                }
                failcnt++;
            } else {
                if (req != ask){
                    printf ("requested %d pages, got %d\n", ask, req);
                    failcnt++;
                    usleep(10);
                } else if(termcount > 0)
                    termcount--;
                pages += req;
            }
        } else if (pages > 2) {
            int ret = lrand48() % pages; 
            printf ("returning %d of %d pages\n", ret, pages);
            if( mb_return_pages ( ret ) < 0 ) {
                printf ("transmission error\n");
                exit(0);
            } else {
               pages -=ret;
            } 

        } else {
            usleep(50);
            mode = mode == 0 ? 1:0;
            termcount++;
        }

        if(termcount > 10 ){
            printf("failed to get pages 10 times.\n");
            mb_terminate();
            exit(0);
        }
    }

}
Exemplo n.º 14
0
int main(int argc, char *argv[])
{
    struct mbus	*m;
    char		 c_addr[60], *token_u[2], *token_e[2];
    int		 seed = (gethostid() << 8) | (getpid() & 0xff), final_iters;
    struct timeval	 timeout;
    int		 i, num_sessions = 0;
    char **xargv = xmalloc(argc);
    int  xargc=0;

#ifdef WIN32
    win32_create_null_window(); /* Needed to listen to messages */
#else
    signal(SIGCONT, sigchld_handler);
    signal(SIGCHLD, sigchld_handler);
    signal(SIGINT, sigint_handler);
    signal(SIGTERM, sigint_handler);
    signal(SIGHUP, sigint_handler);
#endif

    debug_msg("rat-%s started argc=%d\n", RAT_VERSION, argc);

    /* We have two modes: one for operation as a transcoder, one */
    /* when working as a normal end-system audio tool. We choose */
    /* based on the first command line argument supplied.        */
    if ((argc > 2) && (strcmp(argv[1], "-T") == 0)) {
        num_sessions = 2;
    } else {
        num_sessions = 1;
    }

    if (parse_options_early(argc, (const char**)argv) == FALSE) {
        return FALSE;
    }

    srand48(seed);
    snprintf(c_addr, 60, "(media:audio module:control app:rat id:%lu)", (unsigned long) getpid());
    debug_msg("c_addr = %s\n", c_addr);
    m = mbus_init(mbus_control_rx, mbus_err_handler, c_addr);
    if (m == NULL) {
        fatal_error("RAT v" RAT_VERSION, "Could not initialize Mbus: Is multicast enabled?");
        return FALSE;
    }

    /* pull out -X arguments */
    for(i=0; i<argc; i++) {
        if( strcmp(argv[i],"-X") == 0 ) {
            xargv[xargc] = argv[i];
            xargc++;
            i++;
            xargv[xargc] = argv[i];
            xargc++;
        }
    }


    if (ui_enabled) {
        token_u[0] = generate_token();
        fork_process(UI_NAME, c_addr, &pid_ui, 1, token_u, xargc, xargv);
        debug_msg("Controller waiting for %s from UI...\n", token_u[0]);
        if ((u_addr = mbus_rendezvous_waiting(m, "()", token_u[0], m, 20000000)) == NULL) {
            fatal_error("RAT v" RAT_VERSION, "MBUS Failed to rendezvous with UI - Likely firewall/VPN issue");
            return FALSE;
        }
        debug_msg("Controller has rendezvous'd with UI (%s)\n",u_addr);
    }

    token_e[0] = generate_token();
    token_e[1] = generate_token();
    fork_process(ENGINE_NAME, c_addr, &pid_engine, num_sessions, token_e, xargc, xargv);
    should_exit = FALSE;
    for (i = 0; i < num_sessions; i++) {
        debug_msg("Controller waiting for %s from media engine...\n", token_e[i]);
        if ((e_addr[i] = mbus_rendezvous_waiting(m, "()", token_e[i], m, 20000000)) == NULL ) {
            fatal_error("RAT v" RAT_VERSION, "Failed to rendezvous with media engine - Likely firewall/VPN issue");
            return FALSE;
        }
        debug_msg("Controller rendezvous'd with media engine (%s)\n",e_addr[i]);
    }

    if (parse_addresses(m, e_addr, argc, argv) == TRUE) {
        char	*peer;

        if (ui_enabled) {
            if ((peer = mbus_rendezvous_go(m, token_u[0], (void *) m, 20000000)) == NULL) {
                fatal_error("RAT v" RAT_VERSION, "Failed to rendezvous with UI - Likely firewall/VPN issue");
                return FALSE;
            }
            debug_msg("User interface is %s\n", peer);
        }
        for (i = 0; i < num_sessions; i++) {
            if ((peer = mbus_rendezvous_go(m, token_e[i], (void *) m, 20000000)) == NULL) {
                fatal_error("RAT v" RAT_VERSION, "Failed to rendezvous with UI - Likely firewall/VPN issue");
                return FALSE;
            }
            debug_msg("Media engine %d is %s\n", i, peer);
        }
        debug_msg("Parsing options\n");
        for (i = 0; i < num_sessions; i++) {
            parse_options_late(m, e_addr[i], argc, argv);
        }
        debug_msg("Entering main loop\n");
        final_iters = 25;
        while (final_iters > 0) {
            mbus_send(m);
            mbus_heartbeat(m, 1);
            mbus_retransmit(m);
            timeout.tv_sec  = 0;
            timeout.tv_usec = 20000;
#ifdef WIN32
            win32_check_children_running();
            win32_process_messages();
#endif
            mbus_recv(m, NULL, &timeout);
            if (should_exit) {
                final_iters--;
            }
        }
        if (ui_enabled) {
            terminate(m, u_addr, &pid_ui);
        }
        for (i = 0; i < num_sessions; i++) {
            terminate(m, e_addr[i], &pid_engine);
        }
    }

    if (ui_enabled) {
        kill_process(pid_ui);
    }
    kill_process(pid_engine);

#ifdef WIN32
    WSACleanup();
#endif
    if (ui_enabled) xfree(token_u[0]);
    xfree(token_e[0]);
    xfree(token_e[1]);
    xfree(xargv);
    debug_msg("Controller exit\n");
    return 0;
}
Exemplo n.º 15
0
void srand(unsigned int x) { srand48(x); }
Exemplo n.º 16
0
int main (int argc,char **argv )
{

  int generate = 0;
  if ( argc > 1 ) generate = 1;

  int lx = 4;
  int ly = 4;
  int lz = 4;
  int lt = 4;

  int nrow[4];
  nrow[0] = lx;
  nrow[1] = ly;
  nrow[2] = lz;
  nrow[3] = lt;

  bfmarg dwfa;
  dwfa.solver = WilsonFermion;
  dwfa.threads = NTHREAD;

  dwfa.node_latt[0]  = lx;
  dwfa.node_latt[1]  = ly;
  dwfa.node_latt[2]  = lz;
  dwfa.node_latt[3]  = lt;

  dwfa.local_comm[0]  = 1;
  dwfa.local_comm[1]  = 1;
  dwfa.local_comm[2]  = 1;
  dwfa.local_comm[3]  = 1;

  dwfa.Ls = 1;
  dwfa.mass = 0.0;
  dwfa.Csw  = 0.0;

  printf("Initialising bfm operator\n");
  printf("drand48 seed = 0\n");
  srand48(0);

  dwf.init(dwfa);

  psi_h = dwf.allocFermion();
  chi_h = dwf.allocFermion();
  check = dwf.allocFermion();
  diff  = dwf.allocFermion();
  dwf.randFermion(psi_h);
  dwf.unitGauge();

  printf("cb0dag0 is %lx\n",(unsigned long)cb0dag0);
  printf("cb0dag1 is %lx\n",(unsigned long)cb0dag1);
  printf("cb1dag0 is %lx\n",(unsigned long)cb1dag0);
  printf("cb1dag1 is %lx\n",(unsigned long)cb1dag1);
  // Naive Dslash

  // cb is cb of result, 1-cb is cb of input field

  int idx=0;
  for(cb=0;cb<2;cb++){
    
    /*Import this checkerboard of QDP fields to bagel*/

    // Fill the other checkerboard.
    for(dag=0;dag<2;dag++){

      
      printf("Checking cb=%d dag=%d %lx \n",cb,dag,
	     (unsigned long)arrays[idx]);

      dwf.importFermion(arrays[idx],check,0);

      pthread_t threads[NTHREAD];

      for(int t=0;t<NTHREAD;t++){
	pthread_create(&threads[t],NULL,thr_main,NULL);
      }
      for(int t=0;t<NTHREAD;t++){
	pthread_join(threads[t],NULL);
      }

#ifdef GENERATE
      dwf.dump(chi_h,files[idx],array_names[idx]);
#else
      printf("Norm of difference is %le\n",delta);
      //printf("Norm result %le\n",n2);
      //printf("Norm check  %le\n",n1);
#endif
      idx++;
    }
  }
  printf("Done\n"); 
}
Exemplo n.º 17
0
void
child_main(void)
{

	setbuf(stdout, NULL);
	setbuf(stderr, NULL);
	printf("Child starts\n");

	cache_param = heritage.param;

	AZ(pthread_key_create(&req_key, NULL));
	AZ(pthread_key_create(&bo_key, NULL));
	AZ(pthread_key_create(&name_key, NULL));

	THR_SetName("cache-main");

	VSM_Init();	/* First, LCK needs it. */

	LCK_Init();	/* Second, locking */

	Lck_New(&vxid_lock, lck_vxid);

	WAIT_Init();
	PAN_Init();
	CLI_Init();
	VBF_Init();

	VCL_Init();

	HTTP_Init();

	VDI_Init();
	VBO_Init();
	VBE_InitCfg();
	VBP_Init();
	WRK_Init();
	Pool_Init();

	EXP_Init();
	HSH_Init(heritage.hash);
	BAN_Init();

	VCA_Init();

	SMS_Init();
	SMP_Init();
	STV_open();

	VMOD_Init();

	BAN_Compile();

	srandomdev();
	srand48(random());
	CLI_AddFuncs(debug_cmds);

	/* Wait for persistent storage to load if asked to */
	if (FEATURE(FEATURE_WAIT_SILO))
		SMP_Ready();

	Pool_Accept();

	CLI_Run();

	BAN_Shutdown();
	STV_close();

	printf("Child dies\n");
}
Exemplo n.º 18
0
static void  bic_seq_resample(double *tumor, int n_tumor, double *normal, int n_nml, SRM_binning args)
{	SEG_PERMUTE segs = NULL;
	int *tumor_bin, *normal_bin, nbins;
	int n_tumor_sample, n_normal_sample,i,k, total,start,end, kmin;
	double tmp, freq, N_tumor, N_normal;
        struct timeval tv;
        int seed;

        gettimeofday(&tv, NULL);
        seed = tv.tv_sec * 1000000 + tv.tv_usec;
        seed_set(seed);
	srand48(seed);
	
	segs = SEG_PERMUTE_create(args.B);

	tmp = tumor[n_tumor-1] > normal[n_nml-1] ? tumor[n_tumor-1]:normal[n_nml-1];
	nbins = floor(tmp/args.bin_size)+10;
	nbins = nbins>10?nbins:10;
	tumor_bin = (int *) malloc(sizeof(int)*nbins);
	normal_bin = (int *)malloc(sizeof(int)*nbins);
	if(tumor_bin==NULL||normal_bin==NULL){
		fprintf(stderr,"Error in bic_seq_resample: memory allocation failed\n");
		exit(1);
		}

        tmp = tumor[0] < normal[0] ? tumor[0]:normal[0];
        kmin = (int) floor(tmp/args.bin_size)-1;
        kmin = (kmin>0? kmin:0);

	for(i=0;i<segs->size;i++){
		n_tumor_sample = rbinom(args.tumor_freq,n_tumor+n_nml);
		n_normal_sample = rbinom(1-args.tumor_freq,n_tumor+n_nml);
		random_sample(tumor, n_tumor, normal, n_nml, n_tumor_sample,  args.bin_size ,tumor_bin, nbins, args.paired, args.insert, args.sd);
		random_sample(tumor, n_tumor, normal, n_nml, n_normal_sample, args.bin_size ,normal_bin,nbins, args.paired, args.insert, args.sd);


		N_tumor=0.0; N_normal = 0.0;
		for(k=kmin;k<nbins;k++){
			start = k*args.bin_size+1;
			end = start+args.bin_size;
			total = tumor_bin[k] + normal_bin[k];
			freq = ((double) tumor_bin[k])/((double) total);
			if(total>0) ll_append(segs->bins_perm[i], bin_new(tumor_bin[k], total, freq, start, end));
			N_tumor += tumor_bin[k];
			N_normal += normal_bin[k];
			}
		set_BinList(segs->bins_perm[i]);
		set_totalreadcount(N_tumor,N_normal);

                if(args.autoselect_lambda!=1){
                        bic_seq(args.paired);
			//bic_seq(0);
                        }else{
                        bic_seq_auto(ll_length(segs->bins_perm[i]),args.FP,args.paired);
			//bic_seq_auto(ll_length(segs->bins_perm[i]),args.FP,0);
                        }
		segs->bins_perm[i] = get_BinList();
		}

	print_SEG_PERMUTE(segs,args.output);
	SEG_PERMUTE_destroy(segs); segs = NULL;
	free(tumor_bin); tumor_bin = NULL;
	free(normal_bin);normal_bin = NULL;

	return;
}
int main(int argc, const char *argv[])
{
    // Seed the random number generator using time
    srand48((unsigned int) time(NULL));

    // Dimension of the operation with defaul value
    int N = PROBSIZE;

    // Specify operation: 0 MatMult; 1 MatVecMult
    int opr = 0;

    // Whether to verify the result or not
    int verif = 0;

    // Whether to display the result or not
    int disp = 0;

    // Whether to call the naive implementation
    int execNaive = 1;

    // Whether to call the optimized implementation
    int execOPT = 1;

    // Parse command line
    {
        int arg_index = 1;
        int print_usage = 0;

        while (arg_index < argc)
        {
            if ( strcmp(argv[arg_index], "-N") == 0 )
            {
                arg_index++;
                N = atoi(argv[arg_index++]);
            }
            else if ( strcmp(argv[arg_index], "-operation") == 0 )
            {
                arg_index++;
                opr = atoi(argv[arg_index++]);
            }
            else if ( strcmp(argv[arg_index], "-help") == 0 )
            {
                print_usage = 1;
                break;
            }
            else if( strcmp(argv[arg_index], "-verif") == 0 )
            {
                arg_index++;
                verif = 1;
                if(execNaive==0 || execOPT==0) {
                  printf("***Must call both naive and optimized when running verification\n");
                  print_usage = 1;
                  break;
                }
            }
            else if( strcmp(argv[arg_index], "-disp") == 0 )
            {
                arg_index++;
                disp = 1;
            }
            else if( strcmp(argv[arg_index], "-naive") == 0 )
            {
                arg_index++;
                execNaive = 1;
                execOPT   = 0;
                if(verif==1) {
                  printf("***Must call both naive and optimized when running verification\n");
                  print_usage = 1;
                  break;                  
                }
            }
            else if( strcmp(argv[arg_index], "-OPT") == 0 )
            {
                arg_index++;
                execOPT   = 1;
                execNaive = 0;
                if(verif==1) {
                  printf("***Must call both naive and optimized when running verification\n");
                  print_usage = 1;
                  break;                  
                }
            }
            else
            {
                printf("***Invalid argument: %s\n", argv[arg_index]);
                print_usage = 1;
                break;
            }
        }

        if (print_usage)
        {
            printf("\n");
            printf("Usage: %s [<options>]\n", argv[0]);
            printf("\n");
            printf("  -N <N>          : problem size (default: %d)\n", PROBSIZE);
            printf("  -operation <ID> : Operation ID = 0 for MatMult or ID = 1 for MatVecMult\n");
            printf("  -verif          : Activate verification\n");
            printf("  -disp           : Display result (use only for small N!)\n");
            printf("  -naive          : Run only naive implementation\n");
            printf("  -OPT            : Run only optimized implementation\n");
            printf("  -help           : Display this message\n");
            printf("\n");
        }

        if (print_usage)
            return 0;
    }

    // Perform operation
    switch(opr)
    {
        case 0: /* Matrix-matrix multiply */
            {
                printf("Performing matrix-matrix multiply operation\n");
                double *matA, *matB, *matC1, *matC2;

                // Allocate memory
                matA = (double *) malloc(N*N * sizeof(double));
                matB = (double *) malloc(N*N * sizeof(double));
                if(execNaive) matC1 = (double *) malloc(N*N * sizeof(double));
                if(execOPT)   matC2 = (double *) malloc(N*N * sizeof(double));

                // Initialize matrix values
                randInitialize(N*N,matA);
                randInitialize(N*N,matB);

                clock_t tic, toc;
                double tm;

                if(execNaive) {
                  // Perform naive matA x matB = matC1
                  tic = clock();
                  matMult(N,matA,matB,matC1);
                  toc = clock();
                  tm = (double)(toc - tic) / CLOCKS_PER_SEC;
                  printf("Elapsed time for naive mat-mat mult.: %f seconds\n",tm);
                }

                if(execOPT) {
                  // Perform optimized matA x matB = matC2
                  tic = clock();
                  //matMult_opt(N,matA,matB,matC2);
                  toc = clock();
                  tm = (double)(toc - tic) / CLOCKS_PER_SEC;
                  printf("Elapsed time for optimized mat-mat mult.: %f seconds\n",tm);
                }

                // Verify results (compare the two matrices)
                if(verif)
                    compareVecs(N*N,matC2,matC1);

                // Display results (don't use for large matrices)
                if(disp)
                {
                    displayMat(N,N,matA);
                    printf("\n");
                    displayMat(N,N,matB);
                    printf("\n");
                    displayMat(N,N,matC1);
                    printf("\n");
		    displayMat(N,N,matC2);
                }

                // Free memory
                free(matA);
                free(matB);
                if(execNaive) free(matC1);
                if(execOPT)   free(matC2);
            }
            break;

        case 1: /* Matrix-vector multiply */
            {
                printf("Performing matrix-vector multiply operation\n");
                double *matA, *vecB, *vecC1,*vecC2;

                // Allocate memory
                matA = (double *) malloc(N*N * sizeof(double));
                vecB = (double *) malloc(N*N * sizeof(double));
                if(execNaive) vecC1 = (double *) malloc(N*N * sizeof(double));
                if(execOPT)   vecC2 = (double *) malloc(N*N * sizeof(double));

                // Initialize values
                randInitialize(N*N,matA);
                randInitialize(N,vecB);

                clock_t tic, toc;
                double tm;

                if(execNaive) {
                  // Perform naive matA x vecB = vecC1
                  tic = clock();
                  matVecMult(N,matA,vecB,vecC1);
                  toc = clock();
                  tm = (double)(toc - tic) / CLOCKS_PER_SEC;
                  printf("Elapsed time for naive mat-vec mult.: %f seconds\n",tm);
                }

                if(execOPT) {
                  // Perform optimized matA x vecB = vecC2
                  tic = clock();
                  matVecMult_opt(N,matA,vecB,vecC2);
                  toc = clock();
                  tm = (double)(toc - tic) / CLOCKS_PER_SEC;
                  printf("Elapsed time for optimized mat-vec mult.: %f seconds\n",tm);
                }

                // Verify results
                if(verif)
                    compareVecs(N,vecC2,vecC1);

                // Display results (don't use for large matrices)
                if(disp)
                {
                    displayMat(N,N,matA);
                    printf("\n");
                    displayVec(N,vecB);
                    printf("\n");
                    displayVec(N,vecC1);
                    printf("\n");
                }

                // Free memory
                free(matA);
                free(vecB);
                if(execNaive) free(vecC1);
                if(execOPT)   free(vecC2);
            }
            break;

        default:
            printf(" Invalid operation ID\n");
            return 0;
    }


    return 0;
}
Exemplo n.º 20
0
int main(int argc, char *argv [ ])
{
	long int ppp=1111990911;
	
	
	time_t seconds;
	time( & seconds ) ;
	srand ( seconds ) ;
	srand48 ( seconds ) ; //srand generates a sequence of random numbers depending upon the seed value
	FILE *p1;

	//p1 = fopen ( argv [ 1 ],"w" ) ;
	int NoIteration = atoi ( argv [ 1 ] ) ;
        //TAM_WIDTH_MAX = atoi ( argv [ 3 ] ) ;
        int iteration;

	long int t,mint;
	
	FILE *tamread;
	tamread = fopen("tam_testtime.txt","r");
	for(int ii = 0; ii< SIZE; ii++)
		tam_testtime[ii].no_of_tam =  TAM_INFO[ii];
	for(int ii = 0; ii< SIZE; ii++)
	{
		for(int jj = 0; jj< tam_testtime[ii].no_of_tam; jj++)
		{
			fscanf(tamread,"%d\t%ld", &tam_testtime[ii].tam_list[jj], &tam_testtime[ii].testtime_list[jj]); 
		}
	}
	fclose (tamread);
	/*temp_tam_index[0] = TAM_INFO[0];
	for(int i = 1; i< SIZE; i++)
	{
		temp_tam_index[i] = temp_tam_index[i-1]+TAM_INFO[i];
	}
	*/

	if(HARD_DIE_TEST)
	{
		initialiseparticle(&(partarray[0]));
		partarray[0].time_fitness = bin_packing(partarray[0].info,0,0);
		// printf("%ld \n", partarray[0].time_fitness);
		for ( int i = 0 ; i < SIZE ; i ++ ) {
		        //printf ("{ %d, %d, %ld, %ld, %d }\n", scheduler[0][i].corenum, scheduler[0][i].tam_width, scheduler[0][i]. starttime, scheduler[0][i]. endtime,  scheduler[0][i]. tsv);
		}
		print_csv(partarray[0].time_fitness, scheduler[0]);
		return 0;
	}
	
	for(iteration=0;iteration < NoIteration;iteration++)
	{
		globalbestIndx  = 0;
		
		mint=particle_swarm_optimization();
		//printf ("Globalbestindx: %d\n",globalbestIndx);
		/*fo/r ( int pp = 0 ; pp < SIZE ; pp ++ ){
                 	       BestParticle [ pp ] .tam_width = scheduler [globalbestIndx][pp]. tam_width;
                        BestParticle [ pp ] .corenum = scheduler [globalbestIndx][pp]. corenum;
                        BestParticle [ pp ] .starttime = scheduler [globalbestIndx][pp]. starttime;
                        BestParticle [ pp ] .endtime = scheduler [globalbestIndx][pp]. endtime;
                }*/
		for(int i=1;i<3;i++)
		{
    			   //printf("RunForrestRun: %d\n",i);
    				globalbestIndx = 0;
    			
    			t=particle_swarm_optimization();
    			/*for ( int ii = 0 ; ii < SIZE ; ii ++ ) {
                printf ("{ %d, %d, %ld, %ld }\n", scheduler [globalbestIndx][ii].corenum, scheduler [globalbestIndx][ii].tam_width, scheduler [globalbestIndx][ii]. starttime, scheduler [globalbestIndx][ii]. endtime);
        }*/

			if ( t < mint ) {
				mint = t ;
				/*for ( int pp = 0 ; pp < SIZE ; pp ++ ){
                                        BestParticle [ pp ] .corenum = scheduler [globalbestIndx][pp]. corenum;
                                        BestParticle [ pp ] .tam_width = scheduler [globalbestIndx][pp]. tam_width;
                                        BestParticle [ pp ] .starttime = scheduler [globalbestIndx][pp]. starttime;
                                        BestParticle [ pp ] .endtime = scheduler [globalbestIndx][pp]. endtime;
                                }*/
			}
			
			//printf("%ld \n",t);
		}
	
		//fprintf(p1,"%ld\n",mint);
		 //printf("%ld\n",mint);
		
	}
        for ( int i = 0 ; i < SIZE ; i ++ ) {
                //printf ("{ %d, %d, %ld, %ld, %d }\n", BestParticle[i].corenum, BestParticle[i].tam_width, BestParticle[i]. starttime, BestParticle[i]. endtime,  BestParticle[i]. tsv);
        }

    print_csv(mint, BestParticle);
	

    return 0;
}
Exemplo n.º 21
0
int main(int argc, char **argv)
{
  float *Hydrograph = NULL;
  float ***MM5Input = NULL;
  float **PrecipLapseMap = NULL;
  float **PrismMap = NULL;
  unsigned char ***ShadowMap = NULL;
  float **SkyViewMap = NULL;
  float ***WindModel = NULL;
  int MaxStreamID, MaxRoadID;
  float SedDiams[NSEDSIZES];     /* Sediment particle diameters (mm) */
  float roadarea;
  time_t tloc;
  int flag;
  int i;
  int j;
  int x;			/* row counter */
  int y;			/* column counter */
  int shade_offset;		/* a fast way of handling arraay position
				   given the number of mm5 input options */
  int NStats;			/* Number of meteorological stations */
  uchar ***MetWeights = NULL;	/* 3D array with weights for interpolating 
				   meteorological variables between the 
				   stations */

  int NGraphics;		/* number of graphics for X11 */
  int *which_graphics;		/* which graphics for X11 */
  char buffer[32];

  AGGREGATED Total = {		/* Total or average value of a 
				   variable over the entire basin */
    {0.0, NULL, NULL, NULL, NULL, 0.0},	/* EVAPPIX */
    {0.0, 0.0, 0.0, 0.0, NULL, NULL, 0.0, 0, 0.0},	/* PRECIPPIX */
    {{0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, 0.0, 0.0, 0.0},	/* PIXRAD */
    {0.0, 0.0},		/* RADCLASSPIX */
    {0.0, 0.0, 0.0, NULL, NULL, 0.0, 0, 0.0, 0.0, 0.0, 0.0, 
     NULL, NULL, NULL},		/* ROADSTRUCT*/
    {0, 0, 0, 0.0, 0.0, 0.0, 0.0, 0.0,
     0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},	/* SNOWPIX */
    {0, 0.0, NULL, NULL, NULL, 0.0, 0.0, 0.0, 0.0,
     0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 
    0.0, 0.0, 0.0},	/*SOILPIX */
    { 0.0, 0.0, 0.0, 0.0}, /*SEDPIX */
    { 0.0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, /*FINEPIX */
    0.0, 0.0, 0.0, 0.0, 0.0, 0l, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 
    0.0, 0.0, 0.0, 0.0
  };
  CHANNEL ChannelData = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
  DUMPSTRUCT Dump;
  EVAPPIX **EvapMap = NULL;
  INPUTFILES InFiles;
  LAYER Soil;
  LAYER Veg;
  LISTPTR Input = NULL;		/* Linked list with input strings */
  MAPSIZE Map;			/* Size and location of model area */
  MAPSIZE Radar;		/* Size and location of area covered by 
				   precipitation radar */
  MAPSIZE MM5Map;		/* Size and location of area covered by MM5 
				   input files */
  METLOCATION *Stat = NULL;
  OPTIONSTRUCT Options;		/* Structure with information which program
				   options to follow */
  PIXMET LocalMet;		/* Meteorological conditions for current pixel
			 */
  FINEPIX ***FineMap = NULL;
  PRECIPPIX **PrecipMap = NULL;
  RADARPIX **RadarMap = NULL;
  RADCLASSPIX **RadMap = NULL;
  ROADSTRUCT **Network = NULL;	/* 2D Array with channel information for each
				   pixel */
  SNOWPIX **SnowMap = NULL;
  MET_MAP_PIX **MetMap = NULL;
  SNOWTABLE *SnowAlbedo = NULL;
  SOILPIX **SoilMap = NULL;
  SEDPIX **SedMap = NULL;
  SOILTABLE *SType = NULL;
  SEDTABLE *SedType = NULL;
  SOLARGEOMETRY SolarGeo;	/* Geometry of Sun-Earth system (needed for
				   INLINE radiation calculations */
  TIMESTRUCT Time;
  TOPOPIX **TopoMap = NULL;
  UNITHYDR **UnitHydrograph = NULL;
  UNITHYDRINFO HydrographInfo;	/* Information about unit hydrograph */
  VEGPIX **VegMap = NULL;
  VEGTABLE *VType = NULL;
  WATERBALANCE Mass =		/* parameter for mass balance calculations */
    { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,  
      0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };

/*****************************************************************************
  Initialization Procedures 
*****************************************************************************/
  if (argc != 2) {
    fprintf(stderr, "\nUsage: %s inputfile\n\n", argv[0]);
    fprintf(stderr, "DHSVM uses two output streams: \n");
    fprintf(stderr, "Standard Out, for the majority of output \n");
    fprintf(stderr, "Standard Error, for the final mass balance \n");
    fprintf(stderr, "\nTo pipe output correctly to files: \n");
    fprintf(stderr, "(cmd > f1) >& f2 \n");
    fprintf(stderr, "where f1 is stdout_file and f2 is stderror_file\n");
    exit(EXIT_FAILURE);
  }

  sprintf(commandline, "%s %s", argv[0], argv[1]);
  printf("%s \n", commandline);
  fprintf(stderr, "%s \n", commandline);
  strcpy(InFiles.Const, argv[1]);

  printf("\nRunning DHSVM %s\n", version);
  printf("\nSTARTING INITIALIZATION PROCEDURES\n\n");

  ReadInitFile(InFiles.Const, &Input);

  InitConstants(Input, &Options, &Map, &SolarGeo, &Time);

  InitFileIO(Options.FileFormat);
  InitTables(Time.NDaySteps, Input, &Options, &SType, &Soil, &VType, &Veg,
	     &SnowAlbedo);

  InitTerrainMaps(Input, &Options, &Map, &Soil, &TopoMap, &SoilMap, &VegMap);

  CheckOut(Options.CanopyRadAtt, Veg, Soil, VType, SType, &Map, TopoMap, 
	   VegMap, SoilMap);

  if (Options.HasNetwork)
    InitChannel(Input, &Map, Time.Dt, &ChannelData, SoilMap, &MaxStreamID, &MaxRoadID, &Options);
  else if (Options.Extent != POINT)
    InitUnitHydrograph(Input, &Map, TopoMap, &UnitHydrograph,
		       &Hydrograph, &HydrographInfo);
 
  InitNetwork(Map.NY, Map.NX, Map.DX, Map.DY, TopoMap, SoilMap, 
	      VegMap, VType, &Network, &ChannelData, Veg, &Options);

  InitMetSources(Input, &Options, &Map, Soil.MaxLayers, &Time,
		 &InFiles, &NStats, &Stat, &Radar, &MM5Map);

  /* the following piece of code is for the UW PRISM project */
  /* for real-time verification of SWE at Snotel sites */
  /* Other users, set OPTION.SNOTEL to FALSE, or use TRUE with caution */

  if (Options.Snotel == TRUE && Options.Outside == FALSE) {
    printf
      ("Warning: All met stations locations are being set to the vegetation class GLACIER\n");
    printf
      ("Warning: This requires that you have such a vegetation class in your vegetation table\n");
    printf("To disable this feature set Snotel OPTION to FALSE\n");
    for (i = 0; i < NStats; i++) {
      printf("veg type for station %d is %d ", i,
	     VegMap[Stat[i].Loc.N][Stat[i].Loc.E].Veg);
      for (j = 0; j < Veg.NTypes; j++) {
	if (VType[j].Index == GLACIER) {
	  VegMap[Stat[i].Loc.N][Stat[i].Loc.E].Veg = j;
	  break;
	}
      }
      if (j == Veg.NTypes) {	/* glacier class not found */
	ReportError("MainDHSVM", 62);
      }
      printf("setting to glacier type (assumed bare class): %d\n", j);
    }
  }

  InitMetMaps(Time.NDaySteps, &Map, &Radar, &Options, InFiles.WindMapPath,
	      InFiles.PrecipLapseFile, &PrecipLapseMap, &PrismMap,
	      &ShadowMap, &SkyViewMap, &EvapMap, &PrecipMap,
	      &RadarMap, &RadMap, SoilMap, &Soil, VegMap, &Veg, TopoMap,
	      &MM5Input, &WindModel);



  InitInterpolationWeights(&Map, &Options, TopoMap, &MetWeights, Stat, NStats);

  InitDump(Input, &Options, &Map, Soil.MaxLayers, Veg.MaxLayers, Time.Dt,
	   TopoMap, &Dump, &NGraphics, &which_graphics);

  if (Options.HasNetwork == TRUE) {
    InitChannelDump(&ChannelData, Dump.Path);
    ReadChannelState(Dump.InitStatePath, &(Time.Start), ChannelData.streams);
  }

  InitSnowMap(&Map, &SnowMap);
  InitAggregated(Veg.MaxLayers, Soil.MaxLayers, &Total);

  InitModelState(&(Time.Start), &Map, &Options, PrecipMap, SnowMap, SoilMap,
		 Soil, SType, VegMap, Veg, VType, Dump.InitStatePath,
		 SnowAlbedo, TopoMap, Network, &HydrographInfo, Hydrograph);

  InitNewMonth(&Time, &Options, &Map, TopoMap, PrismMap, ShadowMap,
	       RadMap, &InFiles, Veg.NTypes, VType, NStats, Stat, 
	       Dump.InitStatePath);

  InitNewDay(Time.Current.JDay, &SolarGeo);

  if (NGraphics > 0) {
    printf("Initialzing X11 display and graphics \n");
    InitXGraphics(argc, argv, Map.NY, Map.NX, NGraphics, &MetMap);
  }

  shade_offset = FALSE;
  if (Options.Shading == TRUE)
    shade_offset = TRUE;

  /* Done with initialization, delete the list with input strings */
  DeleteList(Input);

  /*****************************************************************************
  Sediment Initialization Procedures 
  *****************************************************************************/
  if(Options.Sediment) {
     time (&tloc);
     srand48 (tloc);
  /* Randomize Random Generator */
 
  /* Commenting the line above and uncommenting the line below 
     allows for the comparison of scenarios. */
  /*  srand48 (0);  */
 

    printf("\nSTARTING SEDIMENT INITIALIZATION PROCEDURES\n\n");

    ReadInitFile(Options.SedFile, &Input);

    InitParameters(Input, &Options, &Map, &Network, &ChannelData, TopoMap,
		   &Time, SedDiams);

    InitSedimentTables(Time.NDaySteps, Input, &SedType, &SType, &VType, &Soil, &Veg);

    InitFineMaps(Input, &Options, &Map, &Soil, &TopoMap, &SoilMap, 
		  &FineMap);

    if (Options.HasNetwork){ 
      printf("Initializing channel sediment\n\n");
      InitChannelSedimentDump(&ChannelData, Dump.Path, Options.ChannelRouting); 
      InitChannelSediment(ChannelData.streams, &Total);
      InitChannelSediment(ChannelData.roads, &Total);
    }

    InitSedMap( &Map, &SedMap);

    /* Done with initialization, delete the list with input strings */
    DeleteList(Input);
  }

  

  /* setup for mass balance calculations */
  Aggregate(&Map, &Options, TopoMap, &Soil, &Veg, VegMap, EvapMap, PrecipMap,
	    RadMap, SnowMap, SoilMap,  &Total, VType, Network, SedMap, FineMap,
	    &ChannelData, &roadarea); 

  Mass.StartWaterStorage =
    Total.Soil.IExcess + Total.CanopyWater + Total.SoilWater + Total.Snow.Swq +
    Total.Soil.SatFlow;
  Mass.OldWaterStorage = Mass.StartWaterStorage;

  if (Options.Sediment) {
    Mass.StartChannelSedimentStorage = Total.ChannelSedimentStorage;
    Mass.LastChannelSedimentStorage = Mass.StartChannelSedimentStorage;
  }

/*****************************************************************************
  Perform Calculations 
*****************************************************************************/

  while (Before(&(Time.Current), &(Time.End)) ||
	 IsEqualTime(&(Time.Current), &(Time.End))) {
    ResetAggregate(&Soil, &Veg, &Total, &Options);

    if (IsNewMonth(&(Time.Current), Time.Dt))
      InitNewMonth(&Time, &Options, &Map, TopoMap, PrismMap, ShadowMap,
		   RadMap, &InFiles, Veg.NTypes, VType, NStats, Stat, 
		   Dump.InitStatePath);



    if (IsNewDay(Time.DayStep)) {
      InitNewDay(Time.Current.JDay, &SolarGeo);
      PrintDate(&(Time.Current), stdout);
      printf("\n");
    }

/*     PrintDate(&(Time.Current),stdout); */
/*     printf("\n"); */
/*     uncomment the above lines to print the time at every step */

    /* determine surface erosion and routing scheme */
    SedimentFlag(&Options, &Time); 

    InitNewStep(&InFiles, &Map, &Time, Soil.MaxLayers, &Options, NStats, Stat,
		InFiles.RadarFile, &Radar, RadarMap, &SolarGeo, TopoMap, RadMap,
                SoilMap, MM5Input, WindModel, &MM5Map);

    /* initialize channel/road networks for time step */

    if (Options.HasNetwork) {
      channel_step_initialize_network(ChannelData.streams);
      channel_step_initialize_network(ChannelData.roads);
    }

    for (y = 0; y < Map.NY; y++) {
      for (x = 0; x < Map.NX; x++) {
	if (INBASIN(TopoMap[y][x].Mask)) {

	  if (Options.Shading)
	    LocalMet =
	      MakeLocalMetData(y, x, &Map, Time.DayStep, &Options, NStats,
			       Stat, MetWeights[y][x], TopoMap[y][x].Dem,
			       &(RadMap[y][x]), &(PrecipMap[y][x]), &Radar,
			       RadarMap, PrismMap, &(SnowMap[y][x]),
			       SnowAlbedo, MM5Input, WindModel, PrecipLapseMap,
			       &MetMap, NGraphics, Time.Current.Month,
			       SkyViewMap[y][x], ShadowMap[Time.DayStep][y][x],
			       SolarGeo.SunMax, SolarGeo.SineSolarAltitude);
	  else
	    LocalMet =
	      MakeLocalMetData(y, x, &Map, Time.DayStep, &Options, NStats,
			       Stat, MetWeights[y][x], TopoMap[y][x].Dem,
			       &(RadMap[y][x]), &(PrecipMap[y][x]), &Radar,
			       RadarMap, PrismMap, &(SnowMap[y][x]),
			       SnowAlbedo, MM5Input, WindModel, PrecipLapseMap,
			       &MetMap, NGraphics, Time.Current.Month, 0.0,
			       0.0, SolarGeo.SunMax,
			       SolarGeo.SineSolarAltitude);

	  for (i = 0; i < Soil.MaxLayers; i++) {
	    if (Options.HeatFlux == TRUE) {
	      if (Options.MM5 == TRUE)
		SoilMap[y][x].Temp[i] =
		  MM5Input[shade_offset + i + N_MM5_MAPS][y][x];
	      else
		SoilMap[y][x].Temp[i] = Stat[0].Data.Tsoil[i];
	    }
	    else
	      SoilMap[y][x].Temp[i] = LocalMet.Tair;
	  }
	  
	  MassEnergyBalance(y, x, SolarGeo.SineSolarAltitude, Map.DX, Map.DY, 
			    Time.Dt, Options.HeatFlux, Options.CanopyRadAtt, 
			    Options.RoadRouting, Options.Infiltration,
			    Veg.MaxLayers, &LocalMet, 
			    &(Network[y][x]), &(PrecipMap[y][x]), 
			    &(VType[VegMap[y][x].Veg-1]), &(VegMap[y][x]),
			    &(SType[SoilMap[y][x].Soil-1]), &(SoilMap[y][x]), 
			    &(SnowMap[y][x]), &(EvapMap[y][x]), &(Total.Rad),
			    &ChannelData);
	}
      }
    }

#ifndef SNOW_ONLY

    /* set sediment inflows to zero - they are incremented elsewhere */
  if ((Options.HasNetwork) && (Options.Sediment)){ 
    InitChannelSedInflow(ChannelData.streams);
    InitChannelSedInflow(ChannelData.roads);
  }
    
    RouteSubSurface(Time.Dt, &Map, TopoMap, VType, VegMap, Network,
		    SType, SoilMap, &ChannelData, &Time, &Options, Dump.Path,
		    SedMap, FineMap, SedType, MaxStreamID, SnowMap);

    if (Options.HasNetwork)
      RouteChannel(&ChannelData, &Time, &Map, TopoMap, SoilMap, &Total, 
		   &Options, Network, SType, PrecipMap, SedMap,
		   LocalMet.Tair, LocalMet.Rh, SedDiams);

    /* Sediment Routing in Channel and output to sediment files */
    if ((Options.HasNetwork) && (Options.Sediment)){
      SPrintDate(&(Time.Current), buffer);
      flag = IsEqualTime(&(Time.Current), &(Time.Start));
      if(Options.ChannelRouting){
	if (ChannelData.roads != NULL) {
	  RouteChannelSediment(ChannelData.roads, Time, &Dump, &Total, SedDiams);
	  channel_save_sed_outflow_text(buffer, ChannelData.roads,
					ChannelData.sedroadout,
					ChannelData.sedroadflowout, flag);
	  RouteCulvertSediment(&ChannelData, &Map, TopoMap, SedMap, 
			       &Total, SedDiams);
	}
	RouteChannelSediment(ChannelData.streams, Time, &Dump, &Total, SedDiams);
	channel_save_sed_outflow_text(buffer, ChannelData.streams,
				      ChannelData.sedstreamout,
				      ChannelData.sedstreamflowout, flag);
      }
      else{
	if (ChannelData.roads != NULL) {
	  channel_save_sed_inflow_text(buffer, ChannelData.roads,
				     ChannelData.sedroadinflow, SedDiams,
				     flag);
	}
	channel_save_sed_inflow_text(buffer, ChannelData.streams,
				     ChannelData.sedstreaminflow, SedDiams,
				     flag);
      }
      SaveChannelSedInflow(ChannelData.roads, &Total);
      SaveChannelSedInflow(ChannelData.streams, &Total);
    }
    
    if (Options.Extent == BASIN)
      RouteSurface(&Map, &Time, TopoMap, SoilMap, &Options,
		   UnitHydrograph, &HydrographInfo, Hydrograph,
		   &Dump, VegMap, VType, SType, &ChannelData, SedMap,
		   PrecipMap, SedType, LocalMet.Tair, LocalMet.Rh, SedDiams);

#endif

    if (NGraphics > 0)
      draw(&(Time.Current), IsEqualTime(&(Time.Current), &(Time.Start)),
	   Time.DayStep, &Map, NGraphics, which_graphics, VType,
	   SType, SnowMap, SoilMap, SedMap, FineMap, VegMap, TopoMap, PrecipMap,
	   PrismMap, SkyViewMap, ShadowMap, EvapMap, RadMap, MetMap, Network,
	   &Options);
    
    Aggregate(&Map, &Options, TopoMap, &Soil, &Veg, VegMap, EvapMap, PrecipMap,
	      RadMap, SnowMap, SoilMap, &Total, VType, Network, SedMap, FineMap,
	      &ChannelData, &roadarea);
    
    MassBalance(&(Time.Current), &(Dump.Balance), &(Dump.SedBalance), &Total, 
		&Mass, &Options);
    
    ExecDump(&Map, &(Time.Current), &(Time.Start), &Options, &Dump, TopoMap,
	     EvapMap, PrecipMap, RadMap, SnowMap, MetMap, VegMap, &Veg, SoilMap,
	     SedMap, Network, &ChannelData, FineMap, &Soil, &Total, &HydrographInfo,
	     Hydrograph);
    
    IncreaseTime(&Time);

  }

  ExecDump(&Map, &(Time.Current), &(Time.Start), &Options, &Dump, TopoMap,
	   EvapMap, PrecipMap, RadMap, SnowMap, MetMap, VegMap, &Veg, SoilMap,
	   SedMap, Network, &ChannelData, FineMap, &Soil, &Total, &HydrographInfo,
	   Hydrograph);

  FinalMassBalance(&(Dump.Balance), &Total, &Mass, &Options, roadarea);

/*****************************************************************************
  Cleanup
*****************************************************************************/

  printf("\nSTARTING CLEANUP\n\n");

  printf("\nEND OF MODEL RUN\n\n");

  return EXIT_SUCCESS;

}
Exemplo n.º 22
0
//*****************************************************************
void PVFSProjector::projectPVFS(BaseProgress * progress)
  throw(ProjectorException)
{
  MPI_Status status;
  int msize(0), membersize(0), position(0); 
  long int buffersize(0);
  unsigned char * buffer(0);                     //the bufer for sending

  Stitcher * mystitch(0);                        //stitcher pointer
  long int beginofchunk(0), endofchunk(0);       //for passing to the slave
  long int chunkcounter(0);                      //for output
  long int ycounter(1);
  int chunkdif(maxchunk-minchunk);


  try
  {
                                                 //init the status progress
    if (progress)
    {
      std::strstream tempstream;
      
      tempstream << "Reprojecting " << newheight << " lines." << std::ends;
      tempstream.freeze(0);
      progress->init(tempstream.str(),
                     NULL,
                     "Done.",
                     newheight, 
                     29);
      progress->start();                         //start the progress
    }
  
    if (stitcher)                                //see if we want a stitcher  
    {
                                                 //creates the stitcher thread
      if (!(mystitch = new (std::nothrow) Stitcher(out)))
        
        throw std::bad_alloc();
    }
    
     //figure out the maximum buffer size based on the system;
    MPI_Pack_size(2, MPI_LONG, MPI_COMM_WORLD, &membersize);
    buffersize+=membersize;
    MPI_Pack_size(maxchunk*newwidth*spp, MPI_UNSIGNED_CHAR, MPI_COMM_WORLD,
                  &membersize);
    buffersize+=membersize;

    //ask for the buffer
    if (!(buffer = new unsigned char[buffersize]))
      throw std::bad_alloc();
    

                               
    if (sequencemethod == 2)                     //init the random number
      srand48(time(NULL));
    
    while (chunkcounter < newheight)
    {
      //do a blocking wait for any message.
      MPI_Recv(buffer, buffersize, MPI_PACKED, MPI_ANY_SOURCE,
               MPI_ANY_TAG, MPI_COMM_WORLD, &status);
      
      //get the starting scanline
      beginofchunk = mcounters[membership[status.MPI_SOURCE]]; 
     
     
      //check termination
      if (beginofchunk < 0)
      {
        //terminate the slave
        chunkcounter += terminateSlave(status, 
                                       mystitch, buffer, buffersize);
      }
      else
      {
        //check the sequence method
        switch(sequencemethod)
        {
        case 0:
          endofchunk = beginofchunk + maxchunk-1;
          break;
        case 1:
          ++ycounter;
          if (ycounter >= sequencesize)
            ycounter = 0;
          endofchunk = beginofchunk + sequence[ycounter]-1;
          break;
        case 2:
          endofchunk = beginofchunk + static_cast<int>(drand48()*chunkdif
                                                       + minchunk) -1;
          break;
        }
        
        //check to see if this is the last chunk in the partition
        if (endofchunk >= mstop[membership[status.MPI_SOURCE]]-1)
        {
          endofchunk = mstop[membership[status.MPI_SOURCE]]-1;
          //reset the counter
          mcounters[membership[status.MPI_SOURCE]] = -1;
        }
        else
        {
          //update the counter
          mcounters[membership[status.MPI_SOURCE]]+=
            (endofchunk-beginofchunk)+1;
        }

        switch(status.MPI_TAG)
        {
        case SETUP_MSG:
          //pack the info in
          sendSlaveSetup(status.MPI_SOURCE);
         
           //add the first bit of work
          position = 0;
          MPI_Pack(&(beginofchunk), 1, MPI_LONG, buffer, buffersize,
                   &position, MPI_COMM_WORLD);
          MPI_Pack(&(endofchunk), 1, MPI_LONG, buffer, buffersize,
                   &position, MPI_COMM_WORLD);
          //send to the slave
          MPI_Send(buffer, position, MPI_PACKED, status.MPI_SOURCE,
                   WORK_MSG, MPI_COMM_WORLD);
          break;
        case WORK_MSG:
          
          MPI_Get_count(&status, MPI_PACKED, &msize);
          //unpack the scanline
          if (stitcher)
          {
            chunkcounter += sendStitcher(mystitch, buffer, msize);
          }
          else
            chunkcounter += unpackScanline(buffer, msize);
         
            //pack the next work
          position = 0;
          MPI_Pack(&(beginofchunk), 1, MPI_LONG, buffer, buffersize,
                   &position, MPI_COMM_WORLD);
          MPI_Pack(&(endofchunk), 1, MPI_LONG, buffer, buffersize,
                   &position, MPI_COMM_WORLD);
          //send to the slave
          MPI_Send(buffer, position, MPI_PACKED, status.MPI_SOURCE,
                   WORK_MSG, MPI_COMM_WORLD);
          break;
        case ERROR_MSG:
        default:
          throw ProjectorException(PROJECTOR_ERROR_BADINPUT);
        }
      }
      
      //update the output
      if (progress && !((chunkcounter) % 11))
        progress->update(chunkcounter);

    }

    if (progress)
      progress->done();
    
    if (stitcher)
    {
      mystitch->wait();
      //remove the stitcher
      delete mystitch;
    }
    
    writer.removeImage(0);                      //flush the output image

    out = NULL;
  }
  catch(...)
  {
    if (stitcher)
    {
      delete mystitch;                          //should stop the stitcher
      mystitch = NULL;
    }
    writer.removeImage(0);
  }
  
}
int main(int argc, char* argv[])
{
	int niter = 100000;					//number of iterations per FOR loop
	int myid;						//hold's process's rank id
	double x,y;						//x,y value for the random coordinate
	int i;							//loop counter
        int count=0;						//Count holds all the number of how many good coordinates
	double z;						//Used to check if x^2+y^2<=1
	double pi;						//holds approx value of pi
	int reducedcount;					//total number of "good" points from all nodes
	int reducedniter;					//total number of ALL points from all nodes
	int ranknum = 0;					//total number of nodes available
	int numthreads = 16					//edit this number to change the number of OpenMP threads launched per MPI task
	MPI_Init(&argc, &argv);					//Start MPI
	MPI_Comm_rank(MPI_COMM_WORLD, &myid);			//get rank of node's process
	MPI_Comm_size(MPI_COMM_WORLD, &ranknum);		//Gets number of nodes availible to process

	if(myid != 0)						//Do the following on all except the master node
	{
		//Start OpenMP code: 16 threads/node
		#pragma omp parallel firstprivate(x, y, z, i) reduction(+:count) num_threads(numthreads)
		{
			srand48((int)time(NULL) ^ omp_get_thread_num());	//Give drand48() a seed value
			for (i=0; i<niter; ++i)				//main loop
			{
				x = (double)drand48();//RAND_MAX;		//gets a random x coordinate
				y = (double)drand48();//RAND_MAX;		//gets a random y coordinate
				z = ((x*x)+(y*y));			//Checks to see if number is inside unit square
				if (z<=1)
				{
					++count;			//if it is, consider it a valid random point	
				}	
			}
		
			//print the value of each thread/rank
		} 
	}
	MPI_Barrier(MPI_COMM_WORLD);
	/*Use MPI_Reduce() to get all the values of count and add them together (MPI_SUM) and return it to
	 * reducedcount
	 * The reason MPI_Reduce is used here is because its a more streamlined way of gathering together all count data
	 * into one variable and performing an operation on it. Its also possible to use MPI_Send() and MPI_Recv(), but
	 * it tends to make the code less readable in my opinion, though it could possibly make it faster since its not
	 * an all-to-one communication like MPI_Reduce() is; while MPI_Send() and MPI_Recv() is a one to one 
	 * comm	unication */
	MPI_Reduce(&count, &reducedcount, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
	/*Since, from the point of view of the code, you know the number of iterations per loop/thread/node is, you can
	 * calculate it without using an MPI routine like above. 
	 * 16 threads with niter iterations each on (the number of nodes - the master node) nodes */

	reducedniter = numthreads*niter*(ranknum-1);					
	MPI_Barrier(MPI_COMM_WORLD);
	if (myid == 0)						//if root process/master node
	{
	    	//p = 4(m/n) | Compute the ratio of good hits to bad hits (monte carlo)
		pi = ((double)reducedcount/(double)reducedniter)*4.0;
		//Print the calculated value of pi
		printf("Pi: %f\n", pi);			
	}
	MPI_Finalize();						//Close the MPI instance
	return 0;
}
Exemplo n.º 24
0
void init_rand_seed( long int seed )
{
   if( seed == 0 ) seed = (long)time(NULL)+(long)getpid() ;
   srand48(seed) ;
}
Exemplo n.º 25
0
int main(int argc, char **argv)
{
    if (argc < 2) {
        printf("Usage:\n");
        printf("    %s port_no [loss_rate]\n", argv[0]);
        exit(1);
    }

    // Seed the RNG from is_lost()
    srand48(12345);

    // Parse/validate args
    char *port = argv[1];
    printf("port = %s\n", port);
    long int x = strtol(argv[1], NULL, 10);
    if (x < 0 || x > USHRT_MAX) {
        fprintf(stderr, "[error]: port %ld is invalid\n", x);
        exit(1);
    }
    double loss_rate = 0.0;
    if (argc == 3) {
        loss_rate = strtof(argv[2], NULL);
        if (loss_rate < 0.0 || loss_rate > 1.0) {
            fprintf(stderr, "[error]: loss_rate must be between 0 and 1\n");
            exit(1);
        }
    }

    // Get a socket to connect to
    int sock;
    struct sockaddr their_addr;
    if (get_addr_sock(&their_addr, &sock, NULL, port) == -1) {
        fprintf(stderr, "[error]: unable to get socket\n");
        exit(1);
    }

    // Len of connecting address
    socklen_t addrlen = (socklen_t) sizeof(their_addr);

    // Last packet received
    int packet_received = -1;

    // Buffer to store data in
    char *buf = malloc((strlen(g_buffer) + 1) * sizeof(char));
    char *bufstart = buf;

    // Main loop of execution - runs until we get an error or tear-down msg
    while (true) {
        // Receive a packet
        struct packet_t pkt;
        if (recv_packet(&pkt, sock, &their_addr, &addrlen, loss_rate) == -1) {
            fprintf(stderr, "[receiver]: couldn't receive packet\n");
            exit(1);
        }

        // Check if this is the tear-down message. If so, get out of loop.
        if (pkt.type == 4) {
            printf("RECEIVED TEAR-DOWN PACKET\n");
            break;
        }

        // Check if this is the next packet in the sequence. If so, adjust
        // packet_received appropriately and copy data to the buffer
        else if (pkt.seq_no == (packet_received + 1)) {
            packet_received++;
            strcpy(bufstart, pkt.data);
            bufstart += pkt.len;
        }

        printf("RECEIVED PACKET %d\n", pkt.seq_no);

        // Send ACK
        struct ack_t ack;
        if (make_ack(&ack, 2, packet_received) == -1) {
            fprintf(stderr, "[receiver]: couldn't construct ACK\n");
            exit(1);
        }
        if (send_ack(&ack, sock, &their_addr) == -1) {
            fprintf(stderr, "[receiver]: couldn't send ACK %d\n", ack.ack_no);
            exit(1);
        }
        printf("--------SEND ACK %d\n", ack.ack_no + 1);
        printf("\n");
    }

    // Construct ACK to tear-down message and send
    struct ack_t tear_down_ack;
    if (make_ack(&tear_down_ack, 8, 0) == -1) {
        fprintf(stderr, "[receiver]: couldn't construct tear-down ACK\n");
        exit(1);
    }
    if (send_ack(&tear_down_ack, sock, &their_addr) == -1) {
        fprintf(stderr, "[receiver]: couldn't send tear-down ACK\n");
        exit(1);
    }
    printf("--------SEND TEAR-DOWN ACK\n");

    // Timer for 7 seconds. Additionally, set a timeout on the socket so that
    // we don't exceed the timeout by not receiving any packets
    if (set_timeout(sock, 7) == -1) {
        fprintf(stderr, "[receiver]: unable to set timeout\n");
        exit(1);
    }
    clock_t start = clock();
    int msec = (clock() - start) * 1000 / CLOCKS_PER_SEC;
    while (msec < 7000) {
        struct packet_t pkt;
        if (recv_packet(&pkt, sock, &their_addr, &addrlen, loss_rate) == -1) {
            break;
        }
        print_packet(pkt);
        if (pkt.type == 4) {
            printf("RECEIVED TEAR-DOWN PACKET\n");
        } else {
            printf("RECEIVED PACKET %d\n", pkt.seq_no);
        }
        
        // Only ACK if it's a tear-down packet
        if (pkt.type == 4) {
            if (send_ack(&tear_down_ack, sock, &their_addr) == -1) {
                fprintf(stderr, "[receiver]: couldn't send tear-down ACK\n");
                break;
            }
            printf("--------SEND TEAR-DOWN ACK\n");
        }
    }

    free(buf);
    return 0;
}
Exemplo n.º 26
0
int main(int argc, char* argv[])
{
    // seed pseudorandom number generator
    srand48(time(NULL));

    // instantiate window
    GWindow window = newGWindow(WIDTH, HEIGHT);

    // instantiate bricks
    initBricks(window);

    // instantiate ball, centered in middle of window
    GOval ball = initBall(window);

    // instantiate paddle, centered at bottom of window
    GRect paddle = initPaddle(window);

    // instantiate scoreboard, centered in middle of window, just above ball
    GLabel label = initScoreboard(window);
    
    // instantiate LivesBoard, centered in middle of window, above Scoreboard.
    GLabel liveslabel = initLivesBoard(window);

    // number of bricks initially
    int bricks = COLS * ROWS;

    // number of lives initially
    int lives = LIVES;

    // number of points initially
    int points = 0;
    
    // ball movement 
    double ball_vertical = 2.0;   
    double ball_horizontal = 2 * drand48();
    
    bool godmode = false;
    if (argc > 2)
    {
        return 1;
    }
    // detect god mode    
    if ((argc == 2) && (strcmp(argv[1], "GOD") == 0))
    {
        godmode = true;
    }
    
    waitForClick();

    // keep playing until game over
    while (lives > 0 && bricks > 0)
    {
        // call detectCollision func to check for collisions
        GObject object = detectCollision(window, ball);
        
        // ball collision with paddle
        if (object == paddle)
        {
            ball_vertical = -ball_vertical;
        }
        
        // detect collision with bricks
        if (object != NULL)
        {
        
            if (strcmp(getType(object), "GRect") == 0 && object != paddle)
            {
                removeGWindow(window, object);
                ball_vertical = -ball_vertical;
                points++;
                bricks--;
                updateScoreboard(window, label, points);
                if (bricks == 0)
                {
                    printf("YOU WON! :)\n");
                }
            }
        }
        
        // ball collision with bottom edge
        if (getY(ball) >= getHeight(window))
        {
            lives--;
            updateLivesboard(window, liveslabel, lives);
            setLocation(ball, BALL_X, BALL_Y);
            setLocation(paddle, PADDLE_X, PADDLE_Y);
            waitForClick();
            
            if (lives == 0)
            {
                printf("GAME OVER :(\n");
            }
        }
        // if godmode is on, set paddle-x equal to ball-x
        if (godmode == true)
        {
            setLocation(paddle, getX(ball) + (BALL_WIDTH / 2) - (PADDLE_WIDTH / 2), PADDLE_Y);
        }
        else
        {       
            // check for mouse event
            GEvent event = getNextEvent(MOUSE_EVENT);
            // if we heard one
            if (event != NULL)
            {
                // if the event was movement
                if (getEventType(event) == MOUSE_MOVED)
                {
                    // ensure circle follows cursor on x-axis
                    double x = getX(event) - getWidth(paddle) / 2;
                    setLocation(paddle, x, PADDLE_Y);
                }
            }
        }   
        
        move(ball, ball_horizontal, ball_vertical);
        
        // bounce off left and right
        if (getX(ball) + getWidth(ball) >= getWidth(window) || getX(ball) <= 0)
        {
            ball_horizontal = -ball_horizontal;
        }
        // bounce off top
        else if (getY(ball) <= 0)
        {
            ball_vertical = -ball_vertical;
        }
        
        pause(7);
    }

    // wait for click before exiting
    waitForClick();

    // game over
    closeGWindow(window);
    return 0;
}
Exemplo n.º 27
0
int main ( int argc ,
	   char **argv )
{
  int i, j, m1, m2, bw, n ;
  int loops, m ;
  long int seed ;
  double *coeffs, *signal, *newcoeffs;
  double *wigners, *wignersTrans ;
  double *workspace, *scratch ;
  double *weights ;
  double *sinPts, *cosPts ;
  double *sinPts2, *cosPts2 ;
  double tmp_error, sum_error;
  double tmp_relerror, sum_relerror;
  double tstartA, tstopA, runtimeA ;
  double tstartB, tstopB, runtimeB ;
  double *relerror, *curmax;
  double ave_error, ave_relerror, stddev_error, stddev_relerror ;
  FILE *fp ;

  
  if (argc < 5)
    {
      fprintf(stdout,"Usage: test_Wigner_Naive m1 m2 bw loops [output_file]\n");
      exit(0);
    }

  m1 = atoi( argv[1] );
  m2 = atoi( argv[2] );
  bw = atoi( argv[3] );
  loops = atoi( argv[4] ) ;
  m = MAX( ABS( m1 ) , ABS( m2 ) ) ;
  n = 2 * bw ;
  runtimeA = 0.0 ;
  runtimeB = 0.0 ;

  weights = ( double * ) malloc(sizeof( double ) * (2*bw) ) ;
  coeffs = ( double * ) malloc(sizeof( double ) * (bw - m) ) ;
  newcoeffs = ( double * ) malloc(sizeof( double ) * (bw - m) ) ;
  signal = ( double * ) malloc(sizeof( double ) * n ) ;
  wigners = ( double * ) malloc( sizeof( double ) * ( bw - m ) * n ) ;
  wignersTrans = ( double * ) malloc( sizeof( double ) * ( bw - m ) * n ) ;
  workspace = (double *) malloc(sizeof( double ) * (4 + 6) * n ) ;
  sinPts = workspace ;
  cosPts = sinPts + n ;
  sinPts2 = cosPts + n ;
  cosPts2 = sinPts2 + n ;
  scratch = cosPts2 + n ; /* scratch needs to be of size 6*n */

  /* note that the definition of wigSpec requires that instead of
     evaluating at beta, I need to evaluate at beta/2; ergo I call
     SinEvalPts2 instead of SinEvalPts, etc etc
  */


  /* generate seed for random number generator */
  time ( &seed ) ;
  srand48( seed ) ;

  /* precompute sines and cosines appropriate for making the
     wigners */

  SinEvalPts( n, sinPts ) ;
  CosEvalPts( n, cosPts ) ;
  SinEvalPts2( n, sinPts2 ) ;
  CosEvalPts2( n, cosPts2 ) ;

  /* make quadrature weights */
  makeweights2( bw, weights );

  /* make the wigners */
  genWig_L2( m1, m2, bw,
	     sinPts, cosPts,
	     sinPts2, cosPts2,
	     wigners, scratch ) ;

  /* now make the wigners - transpose version! */
  genWigTrans_L2( m1, m2, bw,
		  sinPts, cosPts,
		  sinPts2, cosPts2,
		  wignersTrans, scratch ) ;

  /** space for errors **/
  relerror = (double *) malloc(sizeof(double) * loops);
  curmax = (double *) malloc(sizeof(double) * loops);

  sum_error = 0.0 ;
  sum_relerror = 0.0 ;

  for ( i = 0 ; i < loops ; i ++ )
    {
      /* generate random coeffs */
      for( j = 0 ; j < (bw - m) ; j++ )
	coeffs[ j ] = drand48() ;
      
      /* turn on stop watch */
      tstartA = csecond () ;

      /* now synthesize */
      wigNaiveSynthesis( m1, m2, bw, coeffs,
			 wignersTrans, signal,
			 scratch ) ;
      tstopA = csecond () ;

      runtimeA += (tstopA - tstartA);

      tstartB = csecond () ;

      /* now analyze */
      wigNaiveAnalysis( m1, m2, bw, signal,
			wigners, weights,
			newcoeffs,
			scratch ) ;

      /* turn off stop watch */
      tstopB = csecond () ;

      runtimeB += (tstopB - tstartB);

      relerror[ i ] = 0.0 ;
      curmax[ i ] = 0.0 ;
      /* now figure out errors */
      for( j = 0 ; j < bw - m ; j ++ )
	{
	  tmp_error = fabs( coeffs[j] - newcoeffs[j] );
	  tmp_relerror = tmp_error / ( fabs( coeffs[j] ) +
				       pow( 10.0, -50.0 ) );
	  curmax[ i ] = MAX( curmax[ i ], tmp_error );
	  relerror[ i ] = MAX( relerror[ i ], tmp_relerror );
	}
      sum_error += curmax[ i ] ;
      sum_relerror += relerror[ i ] ;
    }


  ave_error = sum_error / ( (double) loops );
  ave_relerror = sum_relerror / ( (double) loops );
  stddev_error = 0.0 ; stddev_relerror = 0.0;
  for( i = 0 ; i < loops ; i ++ )
    {
      stddev_error += pow( ave_error - curmax[ i ] , 2.0 );
      stddev_relerror += pow( ave_relerror - relerror[ i ] , 2.0 );
    }
  /*** this won't work if loops == 1 ***/
  if( loops != 1 )
    {
      stddev_error = sqrt(stddev_error / ( (double) (loops - 1) ) );
      stddev_relerror = sqrt(stddev_relerror / ( (double) (loops - 1) ) );
    }


  fprintf(stderr,"bw = %d\tm1 = %d\tm2 = %d\n",bw, m1, m2);
  fprintf(stderr,"total runtime: %.4e seconds\n", runtimeA+runtimeB);

  fprintf(stderr,"average forward runtime: %.4e seconds per iteration\n",
	  runtimeB/((double) loops));
  fprintf(stderr,"average inverse runtime: %.4e seconds per iteration\n",
	  runtimeA/((double) loops));


  fprintf(stderr,"Average r-o error:\t\t %.4e\t",
	  sum_error/((double) loops));
  fprintf(stderr,"std dev: %.4e\n",stddev_error);
  fprintf(stderr,"Average (r-o)/o error:\t\t %.4e\t",
	  sum_relerror/((double) loops));
  fprintf(stderr,"std dev: %.4e\n\n",stddev_relerror);



  if ( argc == 6 )
    {
      fp = fopen(argv[5], "w");
      for ( i = 0 ; i < bw - m ; i ++ )
	fprintf(fp,"%.16f\n", coeffs[i] - newcoeffs[i]);
    }


  free( curmax ) ;
  free( relerror ) ;
  free( workspace ) ;
  free( wignersTrans ) ;
  free( wigners ) ;
  free( signal ) ;
  free( newcoeffs ) ;
  free( coeffs ) ;
  free( weights ) ;

  return 0 ;
}
Exemplo n.º 28
0
int main(int argc, char **argv)
{
	long int i, N;
	bool already_invaded;

	N = atoi(argv[1]);
	threshold = atof(argv[2]);
	srand48(atoi(argv[3]));

    Site start;
    start.loc = std::make_pair(0, 0);
    start.weight = 0;
    invadedSites.insert(start);
    for (int neigh=0;neigh<4; neigh++)
    {
    	Bond newBond;
    	double newStrength = drand48();
    	newBond = std::make_pair(newStrength, std::make_pair(start, get_neighbor(start, neigh)));
    	accessibleBonds.insert(std::make_pair(newStrength, newBond));
    }

    while(!accessibleBonds.empty())
    {
    	BondMap::iterator weakest;
    	weakest = accessibleBonds.begin();
    	accessibleBonds.erase(weakest);
    	invade_bond(weakest->second);
    	i++;
    	if(i == N)
    	{
    		accessibleBonds.clear();
    	}
    }

    std::stringstream fileName;
    fileName << "fractures" << argv[3] << ".txt";
	std::ofstream toFile1(fileName.str().c_str(), std::ios::trunc);
//	std::ofstream toFile2("trapped.txt", std::ios::trunc);
	toFile1 << growth.size() << "\n";
//	toFile2 << trapped.size() << "\n";
//	toFile1 << "Invasion for: temp" << "\n";
//	toFile2 << "Trapping for: temp" << "\n";
//	toFile1.precision(17);
//	toFile2.precision(17);
//
//	Bond current_Line;
//	while (!growth.empty())
//	{
//		current_Line = growth.front();
//		growth.pop_front();
//		toFile1 <<  current_Line.first << "\t";
//		toFile1 <<  current_Line.second.first.loc.first << "\t";
//		toFile1 <<  current_Line.second.first.loc.second << "\t";
//		toFile1 <<  current_Line.second.second.loc.first << "\t";
//		toFile1 <<  current_Line.second.second.loc.second << "\n";
//	}
//
//
//	while (!trapped.empty())
//	{
//		current_Line = trapped.front();
//		trapped.pop_front();
//		toFile2 <<  current_Line.first << "\t";
//		toFile2 <<  current_Line.second.first.loc.first << "\t";
//		toFile2 <<  current_Line.second.first.loc.second << "\t";
//		toFile2 <<  current_Line.second.second.loc.first << "\t";
//		toFile2 <<  current_Line.second.second.loc.second << "\n";
//	}
//
//	  toFile1.close();
//	  toFile2.close();

    return 0;
}
Exemplo n.º 29
0
int bwa_bwtsw2(int argc, char *argv[])
{
	bsw2opt_t *opt;
	bwt_t *target[2];
	char buf[1024];
	bntseq_t *bns;
	int c;

	opt = bsw2_init_opt();
	srand48(11);
	while ((c = getopt(argc, argv, "q:r:a:b:t:T:w:d:z:m:y:s:c:N:Hf:")) >= 0) {
		switch (c) {
		case 'q': opt->q = atoi(optarg); break;
		case 'r': opt->r = atoi(optarg); break;
		case 'a': opt->a = atoi(optarg); break;
		case 'b': opt->b = atoi(optarg); break;
		case 'w': opt->bw = atoi(optarg); break;
		case 'T': opt->t = atoi(optarg); break;
		case 't': opt->n_threads = atoi(optarg); break;
		case 'z': opt->z = atoi(optarg); break;
		case 'y': opt->yita = atof(optarg); break;
		case 's': opt->is = atoi(optarg); break;
		case 'm': opt->mask_level = atof(optarg); break;
		case 'c': opt->coef = atof(optarg); break;
		case 'N': opt->t_seeds = atoi(optarg); break;
		case 'H': opt->hard_clip = 1; break;
        case 'f': freopen(optarg, "w", stdout);
		}
	}
	opt->qr = opt->q + opt->r;

	if (optind + 2 > argc) {
		fprintf(stderr, "\n");
		fprintf(stderr, "Usage:   bwa bwasw [options] <target.prefix> <query.fa>\n\n");
		fprintf(stderr, "Options: -a INT   score for a match [%d]\n", opt->a);
		fprintf(stderr, "         -b INT   mismatch penalty [%d]\n", opt->b);
		fprintf(stderr, "         -q INT   gap open penalty [%d]\n", opt->q);
		fprintf(stderr, "         -r INT   gap extension penalty [%d]\n", opt->r);
//		fprintf(stderr, "         -y FLOAT error recurrence coef. (4..16) [%.1f]\n", opt->yita);
		fprintf(stderr, "\n");
		fprintf(stderr, "         -t INT   nmber of threads [%d]\n", opt->n_threads);
		fprintf(stderr, "         -s INT   size of a chunk of reads [%d]\n", opt->chunk_size);
		fprintf(stderr, "\n");
		fprintf(stderr, "         -w INT   band width [%d]\n", opt->bw);
		fprintf(stderr, "         -m FLOAT mask level [%.2f]\n", opt->mask_level);
		fprintf(stderr, "\n");
		fprintf(stderr, "         -T INT   score threshold divided by a [%d]\n", opt->t);
		fprintf(stderr, "         -s INT   maximum seeding interval size [%d]\n", opt->is);
		fprintf(stderr, "         -z INT   Z-best [%d]\n", opt->z);
		fprintf(stderr, "         -N INT   # seeds to trigger reverse alignment [%d]\n", opt->t_seeds);
		fprintf(stderr, "         -c FLOAT coefficient of length-threshold adjustment [%.1f]\n", opt->coef);
		fprintf(stderr, "         -H       in SAM output, use hard clipping rather than soft\n");
        fprintf(stderr, "         -f FILE  file to output results to instead of stdout\n");
		fprintf(stderr, "\n");

		{
			double c, theta, eps, delta;
			c = opt->a / log(opt->yita);
			theta = exp(-opt->b / c) / opt->yita;
			eps = exp(-opt->q / c);
			delta = exp(-opt->r / c);
			fprintf(stderr, "mismatch: %lf, gap_open: %lf, gap_ext: %lf\n\n",
					theta, eps, delta);
		}
		return 1;
	}

	// adjust opt for opt->a
	opt->t *= opt->a;
	opt->coef *= opt->a;

	strcpy(buf, argv[optind]); target[0] = bwt_restore_bwt(strcat(buf, ".bwt"));
	strcpy(buf, argv[optind]); bwt_restore_sa(strcat(buf, ".sa"), target[0]);
	strcpy(buf, argv[optind]); target[1] = bwt_restore_bwt(strcat(buf, ".rbwt"));
	strcpy(buf, argv[optind]); bwt_restore_sa(strcat(buf, ".rsa"), target[1]);
	bns = bns_restore(argv[optind]);

	bsw2_aln(opt, bns, target, argv[optind+1]);

	bns_destroy(bns);
	bwt_destroy(target[0]); bwt_destroy(target[1]);
	free(opt);
	
	return 0;
}
Exemplo n.º 30
0
int main(int argc, char *argv[])
{
	char *progname;
	int fd;
	int c;
	extern char *optarg;
	unsigned nprocs = 0;
	unsigned procno;
	pid_t *pidarray = NULL;
	pid_t pid;
	pid_t wr_pid = 0;
	uchar_t *buf = NULL;
	unsigned int seed;
	int pagesize = sysconf(_SC_PAGE_SIZE);
	float alarmtime = 0;
	struct sigaction sa;
	unsigned i;
	int write_cnt;
	uchar_t data;
	int no_prob = 0;
	int wait_stat;
	time_t t;
#ifdef LARGE_FILE
	off64_t bytes_left;
#else /* LARGE_FILE */
	off_t bytes_left;
#endif /* LARGE_FILE */

	progname = *argv;
	tst_tmpdir();
	if (argc < 2) {
		(void)fprintf(stderr, "usage: %s %s\n", progname, usage);
		exit(1);
	}

	while ((c = getopt(argc, argv, "S:omdlrf:p:t:w:s:")) != -1) {
		switch (c) {
		case 'd':
			debug = 1;
			break;
		case 't':
			alarmtime = atof(optarg) * 60;
			break;
		case 'p':
			nprocs = atoi(optarg);
			break;
		case 'l':
			leavefile = 1;
			break;
		case 's':
			sleeptime = atoi(optarg);
			if (sleeptime < 0) {
				(void)fprintf(stderr, "error: negative "
					      "sleeptime\n");
				anyfail();
			}
			break;
		case 'w':
			growsize = atoi(optarg);
			if (growsize < 0) {
				(void)fprintf(stderr, "error: negative write "
					      "size\n");
				anyfail();
			}
			break;
		case 'f':
#if defined(__linux__)
#ifdef LARGE_FILE
			filesize = atoll(optarg);
#else /* LARGE_FILE */
			filesize = atoi(optarg);
#endif /* LARGE_FILE */
#elif defined(__FreeBSD__)
#else
			filesize = atol(optarg);
#endif
			if (filesize < 0) {
				(void)fprintf(stderr, "error: negative "
					      "filesize\n");
				anyfail();
			}
			break;
		case 'r':
			randloops = 1;
			break;
		case 'm':
			dosync = 1;
			break;
		case 'o':
			do_offset = 1;
			break;
		case 'S':
#if defined(__linux__)
#ifdef LARGE_FILE
			sparseoffset = atoll(optarg);
#else /* LARGE_FILE */
			sparseoffset = atoi(optarg);
#endif /* LARGE_FILE */
#elif defined(__FreeBSD__)
#else
			sparseoffset = atol(optarg);
#endif
			if (sparseoffset % pagesize != 0) {
				fprintf(stderr,
					"sparseoffset must be pagesize multiple\n");
				anyfail();
			}
			break;
		default:
			(void)fprintf(stderr, "usage: %s %s\n", progname,
				      usage);
			anyfail();
		}
	}

	if (nprocs > 255) {
		(void)fprintf(stderr, "invalid nprocs %d - (range 0-255)\n",
			      nprocs);
		anyfail();
	}
	(void)time(&t);
	//(void)printf("%s: Started %s", argv[0], ctime(&t)); LTP Port

	(void)sprintf(filename, "%sout.%d", progname, getpid());
	seed = initrand();
	pattern = seed & 0xff;

	if (debug) {
#ifdef LARGE_FILE
		(void)printf("creating file <%s> with %Ld bytes, pattern %d\n",
			     filename, filesize, pattern);
#else /* LARGE_FILE */
		(void)printf("creating file <%s> with %ld bytes, pattern %d\n",
			     filename, filesize, pattern);
#endif /* LARGE_FILE */
		if (alarmtime)
			(void)printf("running for %f minutes\n",
				     alarmtime / 60);
		else
			(void)printf("running with no time limit\n");
	}

	/*
	 *  Plan for death by signal.  User may have specified
	 *  a time limit, in which case set an alarm and catch SIGALRM.
	 *  Also catch and cleanup with SIGINT, SIGQUIT, and SIGTERM.
	 */
	sa.sa_handler = finish;
	sa.sa_flags = 0;
	if (sigemptyset(&sa.sa_mask)) {
		perror("sigempty error");
		goto cleanup;
	}

	if (sigaction(SIGINT, &sa, 0) == -1) {
		perror("sigaction error SIGINT");
		goto cleanup;
	}
	if (alarmtime) {
		if (sigaction(SIGALRM, &sa, 0) == -1) {
			perror("sigaction error");
			goto cleanup;
		}
		(void)alarm(alarmtime);
	}
	/* If we get a SIGQUIT or SIGTERM, clean up and exit immediately. */
	sa.sa_handler = clean_up_file;
	if (sigaction(SIGQUIT, &sa, 0) == -1) {
		perror("sigaction error SIGQUIT");
		goto cleanup;
	}
	if (sigaction(SIGTERM, &sa, 0) == -1) {
		perror("sigaction error SIGTERM");
		goto cleanup;
	}
#ifdef LARGE_FILE
	if ((fd = open64(filename, O_CREAT | O_TRUNC | O_RDWR, 0664)) == -1) {
#else /* LARGE_FILE */
	if ((fd = open(filename, O_CREAT | O_TRUNC | O_RDWR, 0664)) == -1) {
#endif /* LARGE_FILE */
		perror("open error");
		anyfail();
	}

	if ((buf = (uchar_t *) malloc(pagesize + growsize)) == NULL
	    || (pidarray = (pid_t *) malloc(nprocs * sizeof(pid_t))) == NULL) {
		perror("malloc error");
		anyfail();
	}

	for (i = 0; i < nprocs; i++)
		*(pidarray + i) = 0;

	for (i = 0, data = 0; i < pagesize; i++) {
		*(buf + i) = (data + pattern) & 0xff;
		if (++data == nprocs)
			data = 0;
	}
	for (data = 0; i < pagesize + growsize; i++) {
		*(buf + i) = (data + pattern) & 0xff;
		if (++data == nprocs)
			data = 0;
	}

#ifdef LARGE_FILE
	if (lseek64(fd, sparseoffset, SEEK_SET) < 0) {
#else /* LARGE_FILE */
	if (lseek(fd, sparseoffset, SEEK_SET) < 0) {
#endif /* LARGE_FILE */
		perror("lseek");
		anyfail();
	}

	for (bytes_left = filesize; bytes_left; bytes_left -= c) {
		write_cnt = min(pagesize, bytes_left);
		if ((c = write(fd, (char *)buf, write_cnt)) != write_cnt) {
			if (c == -1) {
				perror("write error");
			} else {
				(void)fprintf(stderr, "write: wrote %d of %d "
					      "bytes\n", c, write_cnt);
			}
			(void)close(fd);
			(void)unlink(filename);
			anyfail();
		}
	}

	(void)close(fd);

	/*
	 *  Fork off mmap children.
	 */
	for (procno = 0; procno < nprocs; procno++) {
		switch (pid = fork()) {

		case -1:
			perror("fork error");
			goto cleanup;

		case 0:
			child_mapper(filename, procno, nprocs);
			exit(0);

		default:
			pidarray[procno] = pid;
		}
	}

	/*
	 *  Now fork off an additional process to continually
	 *  write to (and grow) the file.
	 */
	if ((wr_pid = fork()) == -1) {
		perror("fork error");
		goto cleanup;
	} else if (wr_pid == 0) {	/* child */
		child_writer(filename, buf);
		exit(0);
	}

	/*
	 *  Now wait for children and refork them as needed.
	 */

	while (!finished) {
		pid = wait(&wait_stat);
		/*
		 *  Block signals while processing child exit.
		 */

		if (sighold(SIGALRM) || sighold(SIGINT)) {
			perror("sighold error");
			goto cleanup;
		}

		if (pid != -1) {
			/*
			 *  Check exit status, then refork with the
			 *  appropriate procno.
			 */
			if (!WIFEXITED(wait_stat)
			    || WEXITSTATUS(wait_stat) != 0) {
				(void)fprintf(stderr, "child exit with err "
					      "<x%x>\n", wait_stat);
				goto cleanup;
			}
			for (i = 0; i < nprocs; i++)
				if (pid == pidarray[i])
					break;
			if (i == nprocs) {
				if (pid == wr_pid) {
					(void)fprintf(stderr,
						      "writer child unexpected exit <x%x>\n",
						      wait_stat);
					wr_pid = 0;
				} else
					(void)fprintf(stderr, "unknown child "
						      "pid %d, <x%x>\n",
						      pid, wait_stat);
				goto cleanup;
			}

			if ((pid = fork()) == -1) {
				perror("fork error");
				pidarray[i] = 0;
				goto cleanup;
			} else if (pid == 0) {	/* child */
				child_mapper(filename, i, nprocs);
				exit(0);
			} else
				pidarray[i] = pid;
		} else {
			/*
			 *  wait returned an error.  If EINTR, then
			 *  normal finish, else it's an unexpected
			 *  error...
			 */
			if (errno != EINTR || !finished) {
				perror("unexpected wait error");
				goto cleanup;
			}
		}
		if (sigrelse(SIGALRM) || sigrelse(SIGINT)) {
			perror("sigrelse error");
			goto cleanup;
		}
	}

	/*
	 *  Finished!  Check the file for sanity, then kill all
	 *  the children and done!.
	 */

	(void)alarm(0);
	no_prob = 1;

cleanup:
	for (i = 0; i < nprocs; i++)
		(void)kill(pidarray[i], SIGUSR1);
	(void)kill(wr_pid, SIGUSR1);

	while (wait(&wait_stat) != -1 || errno != ECHILD)
		continue;

	if (no_prob) {		/* only check file if no errors */
		if (!fileokay(filename, buf)) {
			(void)fprintf(stderr, "file data incorrect!\n");
			(void)printf("  leaving file <%s>\n", filename);
			anyfail();

		} else {
			(void)printf("file data okay\n");
			if (!leavefile)
				(void)unlink(filename);
		}
	} else
		(void)printf("  leaving file <%s>\n", filename);

	(void)time(&t);
//      (void)printf("%s: Finished %s", argv[0], ctime(&t)); LTP Port
	ok_exit();
	tst_exit();
}

/*
 *  Child process that reads/writes map.  The child stats the file
 *  to determine the size, maps the size of the file, then reads/writes
 *  its own locations on random pages of the map (its locations being
 *  determined based on nprocs & procno).  After a specific number of
 *  iterations, it exits.
 */
void child_mapper(char *file, unsigned procno, unsigned nprocs)
{
#ifdef LARGE_FILE
	struct stat64 statbuf;
	off64_t filesize;
	off64_t offset;
#else /* LARGE_FILE */
	struct stat statbuf;
	off_t filesize;
	off_t offset;
#endif /* LARGE_FILE */
	size_t validsize;
	caddr_t paddr;
	int pagesize = sysconf(_SC_PAGE_SIZE);
	unsigned randpage;
	unsigned int seed;
	unsigned loopcnt;
	unsigned nloops;
	unsigned mappages;
	unsigned mapflags;
	unsigned i;
	struct sigaction sa_mapper;

	mapflags = MAP_SHARED;

	seed = initrand();	/* initialize random seed */

	sa_mapper.sa_handler = clean_mapper;
	sa_mapper.sa_flags = 0;
	if (sigemptyset(&sa_mapper.sa_mask)) {
		perror("sigempty error");
		anyfail();
	}

	if (sigaction(SIGUSR1, &sa_mapper, 0) == -1) {
		perror("sigaction error SIGUSR1");
		anyfail();
	}
#ifdef LARGE_FILE
	if ((fd_mapper = open64(file, O_RDWR)) == -1) {
#else /* LARGE_FILE */
	if ((fd_mapper = open(file, O_RDWR)) == -1) {
#endif /* LARGE_FILE */
		perror("open error");
		anyfail();
	}
#ifdef LARGE_FILE
	if (fstat64(fd_mapper, &statbuf) == -1) {
#else /* LARGE_FILE */
	if (fstat(fd_mapper, &statbuf) == -1) {
#endif /* LARGE_FILE */
		perror("stat error");
		anyfail();
	}
	filesize = statbuf.st_size;

	if (statbuf.st_size - sparseoffset > SIZE_MAX) {
		fprintf(stderr, "size_t overflow when setting up map\n");
		anyfail();
	}
	mapsize_mapper = (size_t) (statbuf.st_size - sparseoffset);
	mappages = roundup(mapsize_mapper, pagesize) / pagesize;
	offset = sparseoffset;
	if (do_offset) {
		int pageoffset = lrand48() % mappages;
		int byteoffset = pageoffset * pagesize;
		offset += byteoffset;
		mapsize_mapper -= byteoffset;
		mappages -= pageoffset;
	}
#ifdef LARGE_FILE
	if ((maddr_mapper = mmap64(0, mapsize_mapper, PROT_READ | PROT_WRITE,
				   mapflags, fd_mapper,
				   offset)) == (caddr_t) - 1) {
#else /* LARGE_FILE */
	if ((maddr_mapper = mmap(0, mapsize_mapper, PROT_READ | PROT_WRITE,
				 mapflags, fd_mapper,
				 offset)) == (caddr_t) - 1) {
#endif /* LARGE_FILE */
		perror("mmap error");
		anyfail();
	}

	(void)close(fd_mapper);

	nloops = (randloops) ? (lrand48() % MAXLOOPS) : MAXLOOPS;

	if (debug) {
#ifdef LARGE_FILE
		(void)printf("child %d (pid %ld): seed %d, fsize %Ld, "
			     "mapsize %d, off %Ld, loop %d\n",
			     procno, getpid(), seed, filesize, mapsize_mapper,
			     offset / pagesize, nloops);
#else /* LARGE_FILE */
		(void)printf("child %d (pid %d): seed %d, fsize %ld, "
			     "mapsize %ld, off %ld, loop %d\n",
			     procno, getpid(), seed, filesize,
			     (long)mapsize_mapper, offset / pagesize, nloops);
#endif /* LARGE_FILE */
	}

	/*
	 *  Now loop read/writing random pages.
	 */
	for (loopcnt = 0; loopcnt < nloops; loopcnt++) {
		randpage = lrand48() % mappages;
		paddr = maddr_mapper + (randpage * pagesize);	/* page address */

		if (randpage < mappages - 1 || !(mapsize_mapper % pagesize))
			validsize = pagesize;
		else
			validsize = mapsize_mapper % pagesize;

		/*
		 * Because one child is mapping file in extend mode,
		 * it may be padded with zeros at end.  So we can't
		 * do an exact check -- accept known pattern OR zeros.
		 */
		for (i = procno; i < validsize; i += nprocs) {
			if (*((unsigned char *)(paddr + i))
			    != ((procno + pattern) & 0xff)
			    && *((unsigned char *)(paddr + i)) != 0) {
				(void)fprintf(stderr, "child %d: invalid data "
					      "<x%x>", procno,
					      *((unsigned char *)(paddr + i)));
				(void)fprintf(stderr,
					      " at pg %d off %d, exp "
					      "<x%x>\n", randpage, i,
					      (procno + pattern) & 0xff);
				anyfail();
			}
			/*
			 *  Now write it.
			 */

			*(paddr + i) = (procno + pattern) & 0xff;
		}
	}
	if (dosync) {
		/*
		 * Exercise msync() as well!
		 */
		randpage = lrand48() % mappages;
		paddr = maddr_mapper + (randpage * pagesize);	/* page address */
		if (msync(paddr, (mappages - randpage) * pagesize,
			  MS_SYNC) == -1) {
			perror("msync error");
			anyfail();
		}
	}
	if (munmap(maddr_mapper, mapsize_mapper) == -1) {
		perror("munmap failed");
		anyfail();
	}
	exit(0);
}

/*
 *  child_writer
 * 	The child process that continually (and slowly!!) grows
 *	the file.  The purpose of this is to exercise the code
 *	supporting mapping of fragments.  The map children are
 *	constantly reforking and will pick up the map changes, etc.
 *	This process executes until signalled (i.e. has no exit!)
 *	unless error.
 */
void child_writer(char *file, uchar_t * buf)
{				/* buf already set up in main */
	struct sigaction sa_writer;

	sa_writer.sa_handler = clean_writer;
	sa_writer.sa_flags = 0;
	if (sigemptyset(&sa_writer.sa_mask)) {
		perror("sigempty error");
		anyfail();
	}

	if (sigaction(SIGUSR1, &sa_writer, 0) == -1) {
		perror("sigaction error SIGUSR1");
		anyfail();
	}
#ifdef LARGE_FILE
	struct stat64 statbuf;
	off64_t off;
#else /* LARGE_FILE */
	struct stat statbuf;
	off_t off;
#endif /* LARGE_FILE */
	int pagesize = sysconf(_SC_PAGE_SIZE);
	uchar_t *p;
	int cnt;

#ifdef LARGE_FILE
	if ((fd_writer = open64(file, O_RDWR)) == -1) {
#else /* LARGE_FILE */
	if ((fd_writer = open(file, O_RDWR)) == -1) {
#endif /* LARGE_FILE */
		perror("open error");
		anyfail();
	}
#ifdef LARGE_FILE
	if ((off = lseek64(fd_writer, 0, SEEK_END)) == -1) {
#else /* LARGE_FILE */
	if ((off = lseek(fd_writer, 0, SEEK_END)) == -1) {
#endif /* LARGE_FILE */
		perror("lseek error");
		anyfail();
	}

	for (;;) {
#ifdef LARGE_FILE
		if (fstat64(fd_writer, &statbuf) == -1) {
#else /* LARGE_FILE */
		if (fstat(fd_writer, &statbuf) == -1) {
#endif /* LARGE_FILE */
			perror("fstat error");
			anyfail();
		}
#ifdef LARGE_FILE
		if (debug)
			(void)printf("writer %d bytes at off %Ld, size %Ld\n",
				     growsize, off, statbuf.st_size);
#else /* LARGE_FILE */
		if (debug)
			(void)printf("writer %d bytes at off %ld, size %ld\n",
				     growsize, off, statbuf.st_size);
#endif /* LARGE_FILE */

		/*
		 *  Write some number of bytes, then sleep some
		 *  number of seconds...
		 *  Need to keep track of our offset so write the
		 *  right bytes.
		 */

		p = buf + (off % pagesize);

		if ((cnt = write(fd_writer, p, growsize)) != growsize) {
			if (cnt == -1)
				perror("write error");
			else
				(void)fprintf(stderr, "wrote %d of %d bytes\n",
					      cnt, growsize);
			anyfail();
		}

		off += growsize;

		(void)sleep(sleeptime);
		if (dosync) {
			if (fsync(fd_writer) == -1) {
				perror("fsync error");
				anyfail();
			}
		}
	}
	close(fd_writer);
}

/*
 *  Make sure file has all the correct data.

 */
int fileokay(char *file, uchar_t * expbuf)
{
#ifdef LARGE_FILE
	struct stat64 statbuf;
#else /* LARGE_FILE */
	struct stat statbuf;
#endif /* LARGE_FILE */
	size_t mapsize;
	uchar_t *readbuf;
	unsigned mappages;
	unsigned pagesize = sysconf(_SC_PAGE_SIZE);
	int fd;
	int cnt;
	unsigned i, j;

#ifdef LARGE_FILE
	if ((fd = open64(file, O_RDONLY)) == -1) {
#else /* LARGE_FILE */
	if ((fd = open(file, O_RDONLY)) == -1) {
#endif /* LARGE_FILE */
		perror("open error");
		anyfail();
	}
#ifdef LARGE_FILE
	if (fstat64(fd, &statbuf) == -1) {
#else /* LARGE_FILE */
	if (fstat(fd, &statbuf) == -1) {
#endif /* LARGE_FILE */
		perror("stat error");
		anyfail();
	}
#ifdef LARGE_FILE
	if (lseek64(fd, sparseoffset, SEEK_SET) < 0) {
#else /* LARGE_FILE */
	if (lseek(fd, sparseoffset, SEEK_SET) < 0) {
#endif /* LARGE_FILE */
		perror("lseek");
		exit(1);
	}

	readbuf = (uchar_t *) malloc(pagesize);

	if (statbuf.st_size - sparseoffset > SIZE_MAX) {
		fprintf(stderr, "size_t overflow when setting up map\n");
		exit(1);
	}
	mapsize = (size_t) (statbuf.st_size - sparseoffset);
	mappages = roundup(mapsize, pagesize) / pagesize;

	for (i = 0; i < mappages; i++) {
		cnt = read(fd, (char *)readbuf, pagesize);
		if (cnt == -1) {
			perror("read error");
			close(fd);
			return 0;
		} else if (cnt != pagesize) {
			/*
			 *  Okay if at last page in file...
			 */
			if ((i * pagesize) + cnt != mapsize) {
				(void)fprintf(stderr, "read %d of %ld bytes\n",
					      (i * pagesize) + cnt,
					      (long)mapsize);
				close(fd);
				return 0;
			}
		}
		/*
		 *  Compare read bytes of data.
		 *  May have zeros from map extend...
		 */
		for (j = 0; j < cnt; j++) {
			if (expbuf[j] != readbuf[j] && readbuf[j] != 0) {
				(void)fprintf(stderr,
					      "read bad data: exp %c got %c",
					      expbuf[j], readbuf[j]);
#ifdef LARGE_FILE
				(void)fprintf(stderr, ", pg %d off %d, "
					      "(fsize %Ld)\n", i, j,
					      statbuf.st_size);
#else /* LARGE_FILE */
				(void)fprintf(stderr, ", pg %d off %d, "
					      "(fsize %ld)\n", i, j,
					      statbuf.st_size);
#endif /* LARGE_FILE */
				close(fd);
				return 0;
			}
		}
	}

	close(fd);
	return 1;
}

 /*ARGSUSED*/ void finish(int sig)
{
	finished++;
	/* finish nicely and check the file contents */
}

 /*ARGSUSED*/ void clean_up_file(int sig)
{
	if (!leavefile)
		(void)unlink(filename);
	exit(1);
}

void clean_mapper(int sig)
{
	if (fd_mapper)
		close(fd_mapper);
	munmap(maddr_mapper, mapsize_mapper);
	exit(0);
}

void clean_writer(int sig)
{
	if (fd_writer)
		close(fd_writer);
	exit(0);
}

unsigned int initrand(void)
{
	unsigned int seed;

	/*
	 *  Initialize random seed...  Got this from a test written
	 *  by scooter:
	 *      Use srand/rand to diffuse the information from the
	 *      time and pid.  If you start several processes, then
	 *      the time and pid information don't provide much
	 *      variation.
	 */
	srand((unsigned int)getpid());
	seed = rand();
	srand((unsigned int)time((time_t *) 0));
	seed = (seed ^ rand()) % 100000;
	srand48((long int)seed);
	return (seed);
}

/*****  LTP Port        *****/
void ok_exit()
{
	tst_resm(TPASS, "Test passed\n");
	tst_rmdir();
	tst_exit();
}

int anyfail()
{
	tst_resm(TFAIL, "Test failed\n");
	tst_rmdir();
	tst_exit();
	return 0;
}