示例#1
0
 FileDataVector& FileDataVector::load (const std::string& filename)
 {
   base_t temp = MR::load_vector<float> (filename);
   base_t::operator= (temp);
   name = Path::basename (filename).c_str();
   calc_stats();
   return *this;
 }
示例#2
0
文件: cov_scope.C 项目: ggcov/ggcov
const cov_stats_t *
cov_scope_t::get_stats()
{
    if (dirty_)
    {
	stats_.clear();
	status_ = calc_stats(&stats_);
	dirty_ = FALSE;
    }
    return &stats_;
}
示例#3
0
 FileDataVector::FileDataVector (const std::string& file) :
     base_t (),
     name (Path::basename (file).c_str()),
     min (NAN),
     mean (NAN),
     max (NAN)
 {
   base_t temp = MR::load_vector<float> (file);
   base_t::operator= (temp);
   calc_stats();
 }
static void *spi_thread(void *arg)
{
	spi_connection_t *sc = (spi_connection_t *)arg;
	spi_data_t *data;
	int res, data_read;
	uint64_t start, end;

	data_read = 0;
	while (1) {
		lock(sc);
		data = __get_free(sc);
		while (data == NULL) {
			pthread_cond_wait(&sc->cond, &sc->lock);
			data = __get_free(sc);
		}
		unlock(sc);
		/* reading always blocks until at least the packet header is ready.
		 */
		start = get_utime();
again:
		res = read(sc->fd, data->rx_buf + data_read, COMM_BUF_SIZE - data_read);
		if (res <= 0) {
			printf("res %d, data_read %d, COMM_BUF_SIZE %d\n", res, data_read, COMM_BUF_SIZE);
			perror("read spi device");
			put_free(sc, data);
		} else {
			data_read += res;
			if (data_read < data->rx_buf[3] + 6 && data_read < COMM_BUF_SIZE)
				goto again;

			end = get_utime();
			calc_stats(end-start, STAT_READ);
			data->data_ready = data_read;
			data->r_idx = 0;
			data_read = 0;
			//print_data(data);
			put_pending_delete(sc, data);
		}
	}
	return NULL;
}
示例#5
0
int main(int argc, char *argv[])
{
   float minval = SMALLNUM, maxval = LARGENUM, inx = 0, iny = 0;
   int centern, offsetn;
   int zoomlevel, maxzoom = 0, minzoom, xid, psid;
   char *rootfilenm, inchar;
   datapart *lodp;
   dataview *dv;
   basicstats *statvals;

   if (argc == 1) {
      printf("\nusage:  exploredat datafilename\n\n");
      exit(0);
   }

   printf("\n\n");
   printf("      Interactive Data Explorer\n");
   printf("         by Scott M. Ransom\n");
   printf("            November, 2001\n");
   print_help();

   {
      int hassuffix = 0;
      char *suffix;

      hassuffix = split_root_suffix(argv[1], &rootfilenm, &suffix);
      if (hassuffix) {
         if (strcmp(suffix, "dat") != 0) {
            printf
                ("\nInput file ('%s') must be a single PRESTO data file ('.dat')!\n\n",
                 argv[1]);
            free(suffix);
            exit(0);
         }
         free(suffix);
      } else {
         printf("\nInput file ('%s') must be a PRESTO data file ('.dat')!\n\n",
                argv[1]);
         exit(0);
      }
   }

   /* Read the info file */

   readinf(&idata, rootfilenm);
   if (idata.object) {
      printf("Examining %s data from '%s'.\n\n",
             remove_whitespace(idata.object), argv[1]);
   } else {
      printf("Examining data from '%s'.\n\n", argv[1]);
   }
#ifdef USEMMAP
   mmap_file = open(argv[1], O_RDONLY);
   {
      int rt;
      struct stat buf;

      rt = fstat(mmap_file, &buf);
      if (rt == -1) {
         perror("\nError in fstat() in exploredat.c");
         printf("\n");
         exit(-1);
      }
      Ndat = buf.st_size / sizeof(float);
   }
   lodp = get_datapart(0, Ndat);
#else
   {
      int numsamp;

      datfile = chkfopen(argv[1], "rb");
      Ndat = chkfilelen(datfile, sizeof(float));
      numsamp = (Ndat > MAXPTS) ? (int) MAXPTS : (int) Ndat;
      lodp = get_datapart(0, numsamp);
   }
#endif

   /* Plot the initial data */

   centern = 0.5 * INITIALNUMPTS;
   if (centern > lodp->nn)
      centern = lodp->nn / 2;
   zoomlevel = LOGMAXDISPNUM - LOGINITIALNUMPTS;
   minzoom = LOGMAXDISPNUM - LOGMAXPTS;
   maxzoom = LOGMAXDISPNUM - LOGMINDISPNUM;
   dv = get_dataview(centern, zoomlevel, lodp);

   /* Prep the XWIN device for PGPLOT */

   xid = cpgopen("/XWIN");
   if (xid <= 0) {
      free_datapart(lodp);
#ifdef USEMMAP
      close(mmap_file);
#else
      fclose(datfile);
#endif
      free(dv);
      exit(EXIT_FAILURE);
   }
   cpgask(0);
   cpgpage();
   offsetn = plot_dataview(dv, minval, maxval, 1.0);

   do {
      cpgcurs(&inx, &iny, &inchar);
      if (DEBUGOUT)
         printf("You pressed '%c'\n", inchar);

      switch (inchar) {
      case ' ':                /* Toggle stats and sample plotting on/off */
         /* 0 = both, 1 = stats only, 2 = data only */
         plotstats++;
         plotstats = plotstats % 3;
         cpgpage();
         offsetn = plot_dataview(dv, minval, maxval, 1.0);
         break;
      case 'M':                /* Toggle between median and average */
      case 'm':
         usemedian = (usemedian) ? 0 : 1;
         free(dv);
         dv = get_dataview(centern, zoomlevel, lodp);
         cpgpage();
         offsetn = plot_dataview(dv, minval, maxval, 1.0);
         break;
      case 'A':                /* Zoom in */
      case 'a':
         centern = inx + offsetn;
      case 'I':
      case 'i':
         if (DEBUGOUT)
            printf("  Zooming in  (zoomlevel = %d)...\n", zoomlevel);
         if (zoomlevel < maxzoom) {
            zoomlevel++;
            free(dv);
            dv = get_dataview(centern, zoomlevel, lodp);
            cpgpage();
            offsetn = plot_dataview(dv, minval, maxval, 1.0);
         } else
            printf("  Already at maximum zoom level (%d).\n", zoomlevel);
         break;
      case 'X':                /* Zoom out */
      case 'x':
      case 'O':
      case 'o':
         if (DEBUGOUT)
            printf("  Zooming out  (zoomlevel = %d)...\n", zoomlevel);
         if (zoomlevel > minzoom) {
            zoomlevel--;
            free(dv);
            dv = get_dataview(centern, zoomlevel, lodp);
            cpgpage();
            offsetn = plot_dataview(dv, minval, maxval, 1.0);
         } else
            printf("  Already at minimum zoom level (%d).\n", zoomlevel);
         break;
      case '<':                /* Shift left 1 full screen */
         centern -= dv->numsamps + dv->numsamps / 8;
      case ',':                /* Shift left 1/8 screen */
         if (DEBUGOUT)
            printf("  Shifting left...\n");
         centern -= dv->numsamps / 8;
         {                      /* Should probably get the previous chunk from the datfile... */
            double lowestr;

            lowestr = 0.5 * dv->numsamps;
            if (centern < lowestr)
               centern = lowestr;
         }
         free(dv);
         dv = get_dataview(centern, zoomlevel, lodp);
         cpgpage();
         offsetn = plot_dataview(dv, minval, maxval, 1.0);
         break;
      case '>':                /* Shift right 1 full screen */
         centern += dv->numsamps - dv->numsamps / 8;
      case '.':                /* Shift right 1/8 screen */
         centern += dv->numsamps / 8;
         if (DEBUGOUT)
            printf("  Shifting right...\n");
         {                      /* Should probably get the next chunk from the datfile... */
            double highestr;

            highestr = lodp->nlo + lodp->nn - 0.5 * dv->numsamps;
            if (centern > highestr)
               centern = highestr;
         }
         free(dv);
         dv = get_dataview(centern, zoomlevel, lodp);
         cpgpage();
         offsetn = plot_dataview(dv, minval, maxval, 1.0);
         break;
      case '+':                /* Increase height of top edge */
         {
            float dy;

            if (maxval > 0.5 * LARGENUM) {
               printf("  Auto-scaling of top edge is off.\n");
               if (minval < 0.5 * SMALLNUM)
                  dy = dv->maxval - dv->minval;
               else
                  dy = dv->maxval - minval;
               maxval = dv->maxval + 0.1 * dy;
            } else {
               if (minval < 0.5 * SMALLNUM)
                  dy = maxval - dv->minval;
               else
                  dy = maxval - minval;
               maxval += 0.1 * dy;
            }
            cpgpage();
            offsetn = plot_dataview(dv, minval, maxval, 1.0);
            break;
         }
      case '_':                /* Decrease height of top edge */
         {
            float dy;

            if (maxval > 0.5 * LARGENUM) {
               printf("  Auto-scaling of top edge is off.\n");
               if (minval < 0.5 * SMALLNUM)
                  dy = dv->maxval - dv->minval;
               else
                  dy = dv->maxval - minval;
               maxval = dv->maxval - 0.1 * dy;
            } else {
               if (minval < 0.5 * SMALLNUM)
                  dy = maxval - dv->minval;
               else
                  dy = maxval - minval;
               maxval -= 0.1 * dy;
            }
            cpgpage();
            offsetn = plot_dataview(dv, minval, maxval, 1.0);
            break;
         }
      case '=':                /* Increase height of bottom edge */
         {
            float dy;

            if (minval < 0.5 * SMALLNUM) {
               printf("  Auto-scaling of bottom edge is off.\n");
               if (maxval > 0.5 * LARGENUM)
                  dy = dv->maxval - dv->minval;
               else
                  dy = maxval - dv->minval;
               minval = dv->minval + 0.1 * dy;
            } else {
               if (maxval > 0.5 * LARGENUM)
                  dy = dv->maxval - minval;
               else
                  dy = maxval - minval;
               minval += 0.1 * dy;
            }
            cpgpage();
            offsetn = plot_dataview(dv, minval, maxval, 1.0);
            break;
         }
      case '-':                /* Decrease height of bottom edge */
         {
            float dy;

            if (minval < 0.5 * SMALLNUM) {
               printf("  Auto-scaling of bottom edge is off.\n");
               if (maxval > 0.5 * LARGENUM)
                  dy = dv->maxval - dv->minval;
               else
                  dy = maxval - dv->minval;
               minval = dv->minval - 0.1 * dy;
            } else {
               if (maxval > 0.5 * LARGENUM)
                  dy = dv->maxval - minval;
               else
                  dy = maxval - minval;
               minval -= 0.1 * dy;
            }
            cpgpage();
            offsetn = plot_dataview(dv, minval, maxval, 1.0);
            break;
         }
      case 'S':                /* Auto-scale */
      case 's':
         printf("  Auto-scaling is on.\n");
         minval = SMALLNUM;
         maxval = LARGENUM;
         cpgpage();
         offsetn = plot_dataview(dv, minval, maxval, 1.0);
         break;
      case 'G':                /* Goto a time */
      case 'g':
         {
            char timestr[50];
            double time = -1.0;

            while (time < 0.0) {
               printf
                   ("  Enter the time (s) from the beginning of the file to go to:\n");
               fgets(timestr, 50, stdin);
               timestr[strlen(timestr) - 1] = '\0';
               time = atof(timestr);
            }
            offsetn = 0.0;
            centern = (int) (time / idata.dt + 0.5);
            printf("  Moving to time %.15g (data point %d).\n", time, centern);
            free(dv);
            dv = get_dataview(centern, zoomlevel, lodp);
            cpgpage();
            offsetn = plot_dataview(dv, minval, maxval, 1.0);
         }
         break;
      case '?':                /* Print help screen */
         print_help();
         break;
      case 'P':                /* Print the current plot */
      case 'p':
         {
            int len;
            char filename[200];

            printf("  Enter the filename to save the plot as:\n");
            fgets(filename, 195, stdin);
            len = strlen(filename) - 1;
            filename[len + 0] = '/';
            filename[len + 1] = 'C';
            filename[len + 2] = 'P';
            filename[len + 3] = 'S';
            filename[len + 4] = '\0';
            psid = cpgopen(filename);
            cpgslct(psid);
            cpgpap(10.25, 8.5 / 11.0);
            cpgiden();
            offsetn = plot_dataview(dv, minval, maxval, 1.0);
            cpgclos();
            cpgslct(xid);
            filename[len] = '\0';
            printf("  Wrote the plot to the file '%s'.\n", filename);
         }
         break;
      case 'V':                /* Show the basic statistics for the current dataview */
      case 'v':
         statvals = calc_stats(dv, lodp);
         printf("\n  Statistics:\n"
                "    Low sample               %d\n"
                "    Number of samples        %d\n"
                "    Low time (s)             %.7g\n"
                "    Duration of samples (s)  %.7g\n"
                "    Maximum value            %.7g\n"
                "    Minimum value            %.7g\n"
                "    Average value            %.7g\n"
                "    Median value             %.7g\n"
                "    Standard Deviation       %.7g\n"
                "    Skewness                 %.7g\n"
                "    Kurtosis                 %.7g\n\n",
                dv->lon, dv->numsamps, dv->lon * idata.dt, dv->numsamps * idata.dt,
                statvals->max, statvals->min, statvals->average,
                statvals->median, statvals->stdev,
                statvals->skewness, statvals->kurtosis);
         free(statvals);
         break;
      case 'Q':                /* Quit */
      case 'q':
         printf("  Quitting...\n");
         free(dv);
         cpgclos();
         break;
      default:
         printf("  Unrecognized option '%c'.\n", inchar);
         break;
      }
   } while (inchar != 'Q' && inchar != 'q');

   free_datapart(lodp);
#ifdef USEMMAP
   close(mmap_file);
#else
   fclose(datfile);
#endif
   printf("Done\n\n");
   return 0;
}
示例#6
0
unsigned char *my_floats_to_bytes (float *data, long long pixel_count, float mask,
				scale_t scaling,float inmin, float inmax)
{
  long long ii;
  double imin=99999, imax=-99999, imean=0, isdev=0;
  double diff_min, diff_max, omin, omax, slope, offset;
  unsigned char *pixels = malloc (pixel_count * sizeof (unsigned char));

  switch (scaling) 
    {
    case TRUNCATE:
      /* Compute all the output pixels truncating the input values */
      for (ii=0; ii<pixel_count; ii++) 
	if (data[ii] < 0) {
	  pixels[ii] = 0;
	}
	else if (data[ii] > 255) {
	  pixels[ii] = 255;
	}
	else
	  pixels[ii] = data[ii] + 0.5;
      break;

    case MINMAX:
      /* Determine the minimum and maximum values for the image. Exclude the 
       * mask value for this calculation */
      printf("USING MINMAX MAPPING...\n");
/*
      for (ii=0; ii<pixel_count; ii++) {
        if (!ISNAN(mask)) {  
	  if (data[ii] < imin && !FLOAT_EQUIVALENT(data[ii], mask)) 
	    imin = data[ii];
	  if (data[ii] > imax && !FLOAT_EQUIVALENT(data[ii], mask)) 
	    imax = data[ii];
	}
	else {
	  if (data[ii] < imin) imin = data[ii];
	  if (data[ii] > imax) imax = data[ii];
	} 
      }
      printf("Calculated min/max as %lf/%lf\n",imin,imax);
*/

      imin = inmin;
      imax = inmax;
    
      omin = imin;
      omax = imax;

      /* Compute all the output pixels stretching the minimum and maximum value
       * into the byte range */
      slope = 255 / (omax-omin);
      offset = -slope * omin;
      printf("slope = %lf, offset %lf\n",slope,offset);
      for (ii=0; ii<pixel_count; ii++) {
        if (data[ii] == mask)
          pixels[ii] = mask;
	else if ((slope * data[ii] + offset) < 1)
	  pixels[ii] = 1;
	else if ((slope * data[ii] + offset) > 255)
	  pixels[ii] = 255;
	else
	  pixels[ii] = slope * data[ii] + offset;
      }
      break;

    case SIGMA:
      /* Determine the minimum, maximum, mean, and standard deviation for the
       * image. Exclude the mask value from the calculation */
      calc_stats(data, pixel_count, 0.0, &imin, &imax, &imean, &isdev);
      printf("imin = %f; imax = %f; imean = %f; isdev = %f\n",imin,imax,imean,isdev);

      /* Apply 2 sigma to calculate new minimum and maximum */
      diff_min = imean - 2*isdev;
      diff_max = imean + 2*isdev;

      omin = diff_min;
      omax = diff_max;
      
      if (diff_min < imin) omin = imin;
      if (diff_max > imax) omax = imax;
      
      /* Computing output pixels applying the sigma mapping */
      slope = 255 / (omax-omin);
      offset = -slope * omin;
      for (ii=0; ii<pixel_count; ii++) {
        if (data[ii] == mask) {
  	  pixels[ii] = mask;
        } else {
	  if ((slope * data[ii] + offset) < 0)
  	    pixels[ii] = 0;
	  else if ((slope * data[ii] + offset) > 255)
	    pixels[ii] = 255;
	  else 
	    pixels[ii] = slope * data[ii] + offset;
        }
      }
      break;

    case SIGMA3:
      /* Determine the minimum, maximum, mean, and standard deviation for the
       * image. Exclude the mask value from the calculation */
      calc_stats(data, pixel_count, 0.0, &imin, &imax, &imean, &isdev);
      printf("imin = %f; imax = %f; imean = %f; isdev = %f\n",imin,imax,imean,isdev);

      /* Apply 3 sigma to calculate new minimum and maximum */
      diff_min = imean - 3*isdev;
      diff_max = imean + 3*isdev;

      omin = diff_min;
      omax = diff_max;
      
      if (diff_min < imin) omin = imin;
      if (diff_max > imax) omax = imax;
      
      /* Computing output pixels applying the sigma mapping */
      slope = 255 / (omax-omin);
      offset = -slope * omin;
      for (ii=0; ii<pixel_count; ii++) {
        if (data[ii] == mask) {
  	  pixels[ii] = mask;
        } else {
	  if ((slope * data[ii] + offset) < 0)
  	    pixels[ii] = 0;
	  else if ((slope * data[ii] + offset) > 255)
	    pixels[ii] = 255;
	  else 
	    pixels[ii] = slope * data[ii] + offset;
        }
      }
      break;


    default:
      asfPrintError("Undefined scaling mechanism!");
      break;
      
    }
  
  return pixels;
}
示例#7
0
文件: rated.c 项目: mprovost/rated
/* Main rated */
int main(int argc, char *argv[]) {
    crew_t crew;
    pthread_t sig_thread;
    sigset_t signal_set;
    struct timeval begin_time, end_time;
    unsigned long sleep_time;
    unsigned long poll_time;
    unsigned long long polls;
    unsigned long long last_poll;
    double rate;
    char *conf_file = NULL;
    char *table;
    char errstr[BUFSIZE];
    int ch, i, freed;
    struct timespec ts;

    dfp = stderr;

    /* Check argument count */
    if (argc < 3)
	usage(argv[0]);

    /* Set default environment */
    config_defaults(set);

    /* Parse the command-line. */
    while ((ch = getopt(argc, argv, "c:p:dhmDt:vz")) != EOF)
	switch ((char) ch) {
	case 'c':
	    conf_file = optarg;
	    break;
	case 'd':
	    set->dbon = FALSE;
	    break;
	case 'D':
	    set->daemon = FALSE;
	    break;
	case 'h':
	    usage(argv[0]);
	    break;
	case 'm':
	    set->multiple++;
	    break;
	case 'p':
	    pid_file = optarg;
	    break;
	case 't':
	    target_file = optarg;
	    break;
	case 'v':
	    set->verbose++;
	    break;
	case 'z':
	    set->withzeros = TRUE;
	    break;
	}

    debug(LOW, "rated version %s starting.\n", VERSION);

    if (set->daemon) {
        if (daemon_init() < 0)
            fatal("Could not fork daemon!\n");
        debug(LOW, "Daemon detached\n");
    }

    pthread_mutex_init(&stats.mutex, NULL);

    /* Initialize signal handler */
    sigemptyset(&signal_set);
    sigaddset(&signal_set, SIGHUP);
    sigaddset(&signal_set, SIGUSR1);
    sigaddset(&signal_set, SIGUSR2);
    sigaddset(&signal_set, SIGTERM);
    sigaddset(&signal_set, SIGINT);
    sigaddset(&signal_set, SIGQUIT);
    if (!set->multiple) 
        checkPID(pid_file, set);

    if (pthread_sigmask(SIG_BLOCK, &signal_set, NULL) != 0)
        fatal("pthread_sigmask error\n");

    /* start a thread to catch signals */
    if (pthread_create(&sig_thread, NULL, sig_handler, (void *) &(signal_set)) != 0)
	fatal("pthread_create error\n");

    /* Read configuration file to establish local environment */
    if (conf_file) {
        if ((read_rated_config(conf_file, set)) < 0) 
            fatal("Could not read config file: %s\n", conf_file);
    } else {
        conf_file = malloc(BUFSIZE);
        if (!conf_file) 
            fatal("Fatal malloc error!\n");
        for(i=0;i<CONFIG_PATHS;i++) {
            snprintf(conf_file, BUFSIZE, "%s%s", config_paths[i], DEFAULT_CONF_FILE); 
            if (read_rated_config(conf_file, set) >= 0)
                break;
            if (i == CONFIG_PATHS-1) {
                snprintf(conf_file, BUFSIZE, "%s%s", config_paths[0], DEFAULT_CONF_FILE); 
                if ((write_rated_config(conf_file, set)) < 0) 
                    fatal("Couldn't write config file.\n");
            }
        }
    }

    /* these probably aren't thread safe*/
    init_snmp("rated");
    /* TODO only do this if we're debugging or not daemonised? */
    snmp_enable_stderrlog();
    /* output oids numerically - this is equivalent to -On in the snmp tools */
    netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_NUMERIC);

    if (set->dbon) {
        /* load the database driver */
        /* we need a db connection before we parse the targets file so we can check and create tables */
        if (!(db_init(set) && db_connect(set)))
            fatal("** Database error - check configuration.\n");

        /* create our own internal tables */
        table = db_check_and_create_data_table(RATED);
        if (table == NULL)
            fatal("** Database error - couldn't create rated table.\n");
        else
            free(table);
        if (!db_check_and_create_oids_table(OIDS))
            fatal("** Database error - couldn't create oids table.\n");
    }

    /* build list of hosts to be polled */
    head = hash_target_file(target_file);
    if (head == NULL)
        fatal("Error updating target list.");

    if (hosts < set->threads) {
        debug(LOW, "Number of hosts is less than configured number of threads, defaulting to %i.\n", hosts);
        set->threads = hosts;
    }

    debug(LOW, "Initializing threads (%d).\n", set->threads);
    pthread_mutex_init(&(crew.mutex), NULL);
    pthread_cond_init(&(crew.done), NULL);
    pthread_cond_init(&(crew.go), NULL);
    crew.current = NULL;

    debug(HIGH, "Starting threads...");
    crew.running = set->threads;
    for (i = 0; i < set->threads; i++) {
        crew.member[i].index = i;
        crew.member[i].crew = &crew;
        if (pthread_create(&(crew.member[i].thread), NULL, poller, (void *) &(crew.member[i])) != 0)
	    fatal("pthread_create error\n");
	debug(HIGH, " %i", i);
	}
    debug(HIGH, " done\n");

    /* spin waiting for all threads to start up */
    debug(HIGH, "Waiting for thread startup.\n");
    ts.tv_sec = 0;
    ts.tv_nsec = 10000000; /* 10 ms */
    gettimeofday(&begin_time, NULL);
    while (crew.running > 0 ) {
	nanosleep(&ts, NULL);
    }
    gettimeofday(&end_time, NULL);
    debug(HIGH, "Waited %lu milliseconds for thread startup.\n", timediff(end_time, begin_time));

    debug(LOW, "rated ready.\n");

    /* Loop Forever Polling Target List */
    while (1) {
	/* check if we've been signalled */
	if (quitting) {
            debug(LOW, "Quitting: received signal %i.\n", quit_signal);
            if (set->dbon)
                db_disconnect();
            /* one final stat output */
            print_stats(stats, set);
            unlink(pid_file);
            exit(1);
	} else if (waiting) {
            debug(HIGH, "Processing pending SIGHUP.\n");
            /* this just rebuilds the target list
             * so all of the targets will reset to a first poll */
            /* none of the threads should be running at this point so we shouldn't need a lock */
            freed = free_host_list(head);
            debug(HIGH, "Freed %i hosts\n", freed);
            head = hash_target_file(target_file);
            waiting = FALSE;
	}

        last_poll = stats.polls;

	gettimeofday(&begin_time, NULL);

	PT_MUTEX_LOCK(&(crew.mutex));
        crew.current = head;

	debug(LOW, "Queue ready, broadcasting thread go condition.\n");

	PT_COND_BROAD(&(crew.go));
	PT_MUTEX_UNLOCK(&(crew.mutex));

        /*
         * wait for signals from threads finishing
         * we have to use a do loop because when this starts up the running count will be zero
         * so wait at least once until we get a signal that some thread is done before checking for zero
         */
	PT_MUTEX_LOCK(&(crew.mutex));
        do {
            PT_COND_WAIT(&(crew.done), &(crew.mutex));
        } while (crew.running > 0);
	PT_MUTEX_UNLOCK(&(crew.mutex));

        if (quitting_now)
            continue;

	gettimeofday(&end_time, NULL);
	poll_time = timediff(end_time, begin_time);
        polls = stats.polls - last_poll;
        rate = ((double) polls / poll_time) * 1000;
        /* don't underflow */
        if (poll_time < set->interval) {
	    sleep_time = set->interval - poll_time;
        } else {
            sleep_time = 0;
            stats.slow++;
        }

        /* have to call this before we increment the round counter */
        calc_stats(&stats, poll_time);

        stats.round++;
	debug(LOW, "Poll round %d completed %llu getnexts in %lu ms (%.0f/s).\n", stats.round, polls, poll_time, rate);
        /* insert the internal poll data for this round into the rated table */
        if (set->dbon)
            db_insert(RATED, 0, end_time, stats.polls - last_poll, rate);

	if (set->verbose >= LOW) {
            print_stats(stats, set);
        }

        if (sleep_time > 0) {
            sleepy(sleep_time, set);
        } else {
            debug(LOW, "Slow poll, not sleeping\n");
        }
    } /* while(1) */
    exit(0);
}
示例#8
0
int main(int argc, char *argv[]) 
{
  int i;//-- counters

  HashTable*   BT_Node_Ptr; 
  HashTable*   BT_Elem_Ptr; 

  //-- MPI
  int   myid, master, numprocs;
  int   namelen;
  char  processor_name[MPI_MAX_PROCESSOR_NAME]; 
  MPI_Status status;

  MPI_Init(&argc,&argv);

  //PetscInitializeNoArguments();
  PetscInitialize(&argc,&argv,PETSC_NULL,PETSC_NULL);

  MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
  MPI_Comm_rank(MPI_COMM_WORLD, &myid);
  MPI_Get_processor_name(processor_name, &namelen);

  char debugfilename[256];
  sprintf(debugfilename,"hpfem%04d.debug",myid);

  double start, end;

  start = MPI_Wtime();

  /* create new MPI datastructures for class objects */
  MPI_New_Datatype();

  char filename[50];
  sprintf(filename,"debug.main.%04d",myid);


  /* read original data from serial preprocessing
     code and then initialize element 
     stiffness routines info */
  int material_count=0, output_flag;
  double epsilon = 1., intfrictang = 1, *bedfrictang = NULL, gamma = 1; 
  double frict_tiny = 0.1, mu = 1.0e-03, rho = 1600, rhof = 1000, porosity = 1;
  char **matnames=NULL;
  int xdmerr;

  StatProps statprops;
  MatProps matprops(material_count, matnames, 
		    intfrictang, bedfrictang, porosity, mu, 
		    rho, rhof, epsilon, gamma, frict_tiny,  1.0, 1.0, 1.0);
  TimeProps timeprops;
  timeprops.starttime=time(NULL);

  MapNames mapnames;
  PileProps pileprops;
  FluxProps fluxprops;
  OutLine outline;
  DISCHARGE discharge;

  int adaptflag;  
  double end_time = 10000.0;  
  /*
   * viz_flag is used to determine which viz output to use
   * nonzero 1st bit of viz_flag means output tecplotxxxx.plt
   * nonzero 2nd bit of viz_flag means output mshplotxxxx.plt
   * nonzero 4th bit of viz_flag means output xdmfxxxxx.xmf
   * nonzero 5th bit of viz_flag means output grass_sites files

   order_flag == 1 means use first order method
   order_flag == 2 means use second order method
  */
  int viz_flag = 0, order_flag, savefileflag=1; //savefileflag will be flipped so first savefile will end in 0
  int Init_Node_Num, Init_Elem_Num, srctype;
  double v_star; // v/v_slump
  double nz_star; /* temporary... used for negligible velocity as stopping 
		     criteria paper... plan to include in v_star implicitly 
		     later */

  Read_data(myid, &matprops, &pileprops, &statprops, &timeprops, 
	    &fluxprops, &adaptflag, &viz_flag, &order_flag,
	    &mapnames, &discharge, &outline, &srctype );

  if(!loadrun(myid, numprocs, &BT_Node_Ptr, &BT_Elem_Ptr, 
	      &matprops,  &timeprops, &mapnames, 
	      &adaptflag, &order_flag, &statprops, &discharge, &outline)) 
    {
      Read_grid(myid, numprocs, &BT_Node_Ptr, &BT_Elem_Ptr, 
		&matprops, &outline);

      setup_geoflow(BT_Elem_Ptr, BT_Node_Ptr, myid, numprocs, &matprops,&timeprops);

      move_data(numprocs, myid, BT_Elem_Ptr, BT_Node_Ptr,&timeprops);

      AssertMeshErrorFree(BT_Elem_Ptr,BT_Node_Ptr,numprocs,myid,-1.0);


      //initialize pile height and if appropriate perform initial adaptation
      init_piles(BT_Elem_Ptr, BT_Node_Ptr, myid, numprocs, adaptflag,
		 &matprops, &timeprops, &mapnames, &pileprops, &fluxprops,
		 &statprops);
    }


  if (myid==0)
    {
      for(int imat=1; imat<=matprops.material_count; imat++)
	printf("bed friction angle for \"%s\" is %g\n",matprops.matnames[imat],
	       matprops.bedfrict[imat]*180.0/PI);

      printf("internal friction angle is %g, epsilon is %g \n method order = %i\n",
	     matprops.intfrict*180.0/PI, matprops.epsilon, order_flag );
      printf("REFINE_LEVEL=%d\n",REFINE_LEVEL);
    }

  //printdate(BT_Elem_Ptr, BT_Node_Ptr,&matprops, &fluxprops,&timeprops);


  MPI_Barrier(MPI_COMM_WORLD);
  calc_stats(BT_Elem_Ptr, BT_Node_Ptr, myid, &matprops, 
	     &timeprops, &statprops, &discharge, 0.0);
  output_discharge(&matprops, &timeprops, &discharge, myid);

  move_data(numprocs, myid, BT_Elem_Ptr, BT_Node_Ptr,&timeprops);
  // int jiter;
  // for( jiter=0; jiter <3; jiter++){

  //   LaplacianData  Laplacian (BT_Elem_Ptr, BT_Node_Ptr ,1 ,.001);

  //   implicit_solver(&Laplacian);
  // }

  // HashEntryPtr      *buck = BT_Elem_Ptr->getbucketptr();

  // for(jiter=0; jiter<BT_Elem_Ptr->get_no_of_buckets(); jiter++){
  //   if(*(buck+jiter))
  //     {
  // 	HashEntryPtr currentPtr = *(buck+jiter);
  // 	while(currentPtr)
  // 	  {
  // 	    Element* Curr_El=(Element*)(currentPtr->value);
  // 	    if(Curr_El->get_adapted_flag()>0)//||(timeprops_ptr->iter%5==2)))
  // 	      { //if this is a refined element don't involve!!!
  // 		double phi = *(Curr_El->get_state_vars()+4);
  // 		if(phi>1) phi=1;
  // 		if(phi<0) phi=0;
  // 		Curr_El->update_phase2(phi);
  // 		Curr_El->update_phase1(phi);

  // 	      }
  // 	    currentPtr=currentPtr->next;
  // 	  }
  //     }
  // }
  //=============================================================================================================

  // int num_buck=BT_Elem_Ptr->get_no_of_buckets();
  // HashEntryPtr* buck = BT_Elem_Ptr->getbucketptr();
  // int num_nonzero_elem=0, *all_num_nonzero_elem;
  // for(i=0; i<num_buck; i++)
  //   if(*(buck+i)){

  //     HashEntryPtr currentPtr = *(buck+i);
  //     while(currentPtr){

  // 	Element* Curr_El=(Element*)(currentPtr->value);
  // 	if((Curr_El->get_adapted_flag()>0)&&
  // 	   (myid==Curr_El->get_myprocess()))
  // 	  if(*(Curr_El->pass_key())==3842346279 && *(Curr_El->pass_key()+1)==2368179492)
  // 	    {
  // 	      int xp=Curr_El->get_positive_x_side();
  // 	      int yp=(xp+1)%4, xm=(xp+2)%4, ym=(xp+3)%4;
  // 	      Node* nym = (Node*) BT_Node_Ptr->lookup(Curr_El->getNode()+(ym+4)*2);
  // 	      assert(nym->flux[1]);
  // 	    }

  // 	currentPtr=currentPtr->next;
  //     }
  //   }

  //=====================================================================================================


  if(myid==0) output_summary(&timeprops, &statprops, savefileflag);

  if(viz_flag&1)
    tecplotter(BT_Elem_Ptr, BT_Node_Ptr, &matprops, &timeprops, &mapnames, 
	       statprops.vstar );

  if(viz_flag&2)
    meshplotter(BT_Elem_Ptr, BT_Node_Ptr, &matprops, &timeprops, &mapnames, statprops.vstar);


  //printdate(BT_Elem_Ptr, BT_Node_Ptr,&matprops, &fluxprops,&timeprops);

#ifdef HAVE_HDF5
  if(viz_flag&8) 
    xdmerr=write_xdmf(BT_Elem_Ptr,BT_Node_Ptr,&timeprops,&matprops,&mapnames,XDMF_NEW);
#endif

  if(viz_flag&16){
    if(myid==0) grass_sites_header_output(&timeprops);
    grass_sites_proc_output(BT_Elem_Ptr, BT_Node_Ptr, myid, &matprops, 
			    &timeprops);}

  /*
    cccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
    cccccccccccccccccccccccccccccccccccccccccccccccccccccccccc

    Time Stepping Loop

    cccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
    cccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
  */
  long element_counter=0; // for performance count elements/timestep/proc 
  int ifstop=0;
  double max_momentum=100;  //nondimensional

  /* ifend(0.5*statprops.vmean) is a hack, the original intent (when we were 
     intending to use vstar as a stopping criteria) whas to have the 
     calculation when vstar dropped back down below 1, instead we're 
     using the ifend() function to stop the simulation when the volume 
     averaged velocity falls back down below 2 meters... this hack is only
     for the colima hazard map runs, otherwise pass ifend() a constant 
     valued */

  while(!(timeprops.ifend(0)) && !ifstop)//(timeprops.ifend(0.5*statprops.vmean)) && !ifstop)
    {

      /*  
       *  mesh adaption routines 
       */
      double TARGET = .05;
      //double UNREFINE_TARGET = .005;
      double UNREFINE_TARGET = .01;
      int h_count = 0;
      if (timeprops.iter < 50)
	matprops.frict_tiny=0.1;
      else 
	matprops.frict_tiny=0.000000001;


      //check for changes in topography and update if necessary
      //may want to put an "if(timeprops.iter %20==0)" (20 is arbitrary) here
      if(timeprops.iter==200){
	update_topo(BT_Elem_Ptr, BT_Node_Ptr, myid, numprocs, &matprops, 
		    &timeprops,&mapnames);
      }

      if((adaptflag!=0)&&(timeprops.iter%5==4))
	{
	  AssertMeshErrorFree(BT_Elem_Ptr,BT_Node_Ptr,numprocs,myid,-2.0);

	  H_adapt(BT_Elem_Ptr, BT_Node_Ptr, h_count, TARGET, &matprops, 
		  &fluxprops, &timeprops, 5);

	  move_data(numprocs, myid, BT_Elem_Ptr, BT_Node_Ptr,&timeprops);

	  unrefine(BT_Elem_Ptr, BT_Node_Ptr, UNREFINE_TARGET, myid, numprocs, &timeprops, &matprops);

	  MPI_Barrier(MPI_COMM_WORLD);//for debug

	  move_data(numprocs, myid, BT_Elem_Ptr, BT_Node_Ptr,&timeprops); //this move_data() here for debug... to make AssertMeshErrorFree() Work

	  if((numprocs>1)&&(timeprops.iter%10==9)) 
	    {

	      repartition2(BT_Elem_Ptr, BT_Node_Ptr, &timeprops);

	      move_data(numprocs, myid, BT_Elem_Ptr, BT_Node_Ptr,&timeprops); //this move_data() here for debug... to make AssertMeshErrorFree() Work
	    }
	  move_data(numprocs, myid, BT_Elem_Ptr, BT_Node_Ptr,&timeprops);
	}

      step(BT_Elem_Ptr, BT_Node_Ptr, myid, numprocs, &matprops, &timeprops, 
	   &pileprops, &fluxprops, &statprops, &order_flag, &outline, 
	   &discharge,adaptflag);

      /*
       * output results to file 
       */
             if(timeprops.ifoutput()) {
//      if (timeprops.iter%30==1){//(timeprops.iter<1000 && timeprops.iter%60==58)
	//output_flag=1;
	//else if ( timeprops.iter%200==198)
	//output_flag=1;
	//    if(output_flag) 
	//	{
	move_data(numprocs, myid, BT_Elem_Ptr, BT_Node_Ptr,&timeprops);

	output_discharge(&matprops, &timeprops, &discharge, myid);
	//output_flag=0;

	if(myid==0){ 
	  output_summary(&timeprops, &statprops, savefileflag);
	}

	if(viz_flag&1)
	  tecplotter(BT_Elem_Ptr, BT_Node_Ptr, &matprops, &timeprops, &mapnames,statprops.vstar);

	if(viz_flag&2)
	  meshplotter(BT_Elem_Ptr, BT_Node_Ptr, &matprops, &timeprops, &mapnames,statprops.vstar);

#ifdef HAVE_HDF5
	if(viz_flag&8)
	  xdmerr=write_xdmf(BT_Elem_Ptr,BT_Node_Ptr,&timeprops,&matprops,&mapnames,XDMF_OLD);
#endif

	if(viz_flag&16){
	  if(myid==0) grass_sites_header_output(&timeprops);
	  grass_sites_proc_output(BT_Elem_Ptr, BT_Node_Ptr, myid, &matprops, 
				  &timeprops);
	}
      }

#ifdef PERFTEST
      int countedvalue=timeprops.iter%2+1;
      int e_buckets=BT_Elem_Ptr->get_no_of_buckets();
      HashEntry* entryp;
      for(i=0; i<e_buckets; i++)
	{
	  entryp = *(BT_Elem_Ptr->getbucketptr() + i);
	  while(entryp)
	    {	
	      Element *  EmTemp = (Element*)entryp->value;
	      assert(EmTemp);
	      assert(EmTemp->get_counted()!=countedvalue);

	      if((EmTemp->get_adapted_flag()>=NOTRECADAPTED)&&
		 (EmTemp->get_adapted_flag()<=BUFFER)
		 ) {
		//if this element doesn't belong on this processor don't involve
		element_counter++;
		EmTemp->put_counted(countedvalue);
	      }
	      entryp = entryp->next;
	    }
	}

      MPI_Barrier(MPI_COMM_WORLD);      
#endif
    }

  MPI_Barrier(MPI_COMM_WORLD);


  move_data(numprocs, myid, BT_Elem_Ptr, BT_Node_Ptr,&timeprops);
  MPI_Barrier(MPI_COMM_WORLD);

  output_discharge(&matprops, &timeprops, &discharge, myid);
  MPI_Barrier(MPI_COMM_WORLD);

  if(myid==0) output_summary(&timeprops, &statprops, savefileflag);

  //printf("hpfem.C 1: xcen=%g\n",statprops.xcen);

  if(viz_flag&1)
    tecplotter(BT_Elem_Ptr, BT_Node_Ptr, &matprops, &timeprops, &mapnames, 
	       statprops.vstar);
  //printf("hpfem.C 2: xcen=%g\n",statprops.xcen);
  MPI_Barrier(MPI_COMM_WORLD);

  if(viz_flag&2)
    meshplotter(BT_Elem_Ptr, BT_Node_Ptr, &matprops, &timeprops, &mapnames,
		statprops.vstar);
  MPI_Barrier(MPI_COMM_WORLD);

#ifdef HAVE_HDF5
  if(viz_flag&8)
    xdmerr=write_xdmf(BT_Elem_Ptr,BT_Node_Ptr,&timeprops,&matprops,&mapnames,XDMF_CLOSE);
  MPI_Barrier(MPI_COMM_WORLD);
#endif

  if(viz_flag&16){
    if(myid==0) grass_sites_header_output(&timeprops);
    grass_sites_proc_output(BT_Elem_Ptr, BT_Node_Ptr, myid, &matprops, 
			    &timeprops);}
  MPI_Barrier(MPI_COMM_WORLD);

  // write out ending warning, maybe flow hasn't finished moving
  sim_end_warning(BT_Elem_Ptr, &matprops, &timeprops, statprops.vstar);
  MPI_Barrier(MPI_COMM_WORLD);

  //write out the final pile statistics (and run time)
  if(myid==0) out_final_stats(&timeprops, &statprops);

  MPI_Barrier(MPI_COMM_WORLD);

  //write out stochastic simulation statistics
  //if(statprops.lhs.runid>=0)
  if(myid==0) output_stoch_stats(&matprops, &statprops);
  MPI_Barrier(MPI_COMM_WORLD);

  //saverun(&BT_Node_Ptr, myid, numprocs, &BT_Elem_Ptr, &matprops, &timeprops, &mapnames, 
  //      adaptflag, order_flag, &statprops, &discharge, &outline, &savefileflag); Was not possible because the saverun function doesn't write the information for laplacian, moreover element constructor requires some modifications
  
  MPI_Barrier(MPI_COMM_WORLD);
 

  //output maximum flow depth a.k.a. flow outline
  OutLine outline2;
  double dxy[2];
  dxy[0]=outline.dx;
  dxy[1]=outline.dy;
  outline2.init2(dxy,outline.xminmax,outline.yminmax);
  int NxNyout=outline.Nx*outline.Ny;
  MPI_Reduce(*(outline.pileheight),*(outline2.pileheight),NxNyout, 
	     MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
  if(myid==0) outline2.output(&matprops,&statprops);

#ifdef PERFTEST  
  long  m = element_counter, ii;

  MPI_Allreduce ( &element_counter, &ii, 1, 
		  MPI_LONG, MPI_SUM, MPI_COMM_WORLD );

  end=MPI_Wtime();
  char perffilename[256];
  sprintf(perffilename,"perform%04d.%04d",numprocs,myid);
  FILE *fpperf=fopen(perffilename,"w");
  fprintf(fpperf,"%d Finished -- used %ld elements of %ld total in %e seconds, %e\n",myid,m,ii,end-start, ii/(end-start));
  fclose(fpperf);
#endif
  PetscFinalize();
  MPI_Finalize();  
  return(0);  

}
示例#9
0
void step(HashTable* El_Table, HashTable* NodeTable, int myid, int nump, MatProps* matprops_ptr,
    TimeProps* timeprops_ptr, PileProps *pileprops_ptr, FluxProps *fluxprops,
    StatProps* statprops_ptr, int* order_flag, OutLine* outline_ptr, DISCHARGE* discharge,
    int adaptflag) {
	/*
	 * PREDICTOR-CORRECTED based on Davis' Simplified Godunov Method
	 */

	/* pass off proc data here (really only need state_vars for off-proc neighbors) */
	move_data(nump, myid, El_Table, NodeTable, timeprops_ptr);

	slopes(El_Table, NodeTable, matprops_ptr, 0);

	// get coefficients, eigenvalues, hmax and calculate the time step
	double dt = get_coef_and_eigen(El_Table, NodeTable, matprops_ptr, fluxprops, timeprops_ptr, 0);
	// here we store the required data (solution and functional sensitivity) for the 0 time step

	timeprops_ptr->incrtime(&dt); //also reduces dt if necessary

	// assign influxes and then if any new sources are activating in
	// current time step refine and re-mark cells
	adapt_fluxsrc_region(El_Table, NodeTable, matprops_ptr, pileprops_ptr, fluxprops, timeprops_ptr,
	    dt, myid, adaptflag);

	int i;
	HashEntryPtr* buck = El_Table->getbucketptr();
	HashEntryPtr currentPtr;
	Element* Curr_El;

	double dt2 = .5 * dt; // dt2 is set as dt/2 !

	/*
	 *  predictor step
	 */
	int j, k, counter;
	double tiny = GEOFLOW_TINY;
	double flux_src_coef = 0;

#ifdef SECOND_ORDER
	//-------------------go through all the elements of the subdomain and
	//-------------------calculate the state variables at time .5*delta_t
	/* mdj 2007-04 */
	int IF_STOPPED;
	double curr_time,influx[3],*d_uvec; //VxVy[2];
	double VxVy[2];
	Node* nd;
#pragma omp parallel for                                                \
  private(currentPtr,Curr_El,IF_STOPPED,influx,j,k,curr_time,flux_src_coef,VxVy)
	for(i=0; i<El_Table->get_no_of_buckets(); i++)
	if(*(buck+i))
	{
		currentPtr = *(buck+i);
		while(currentPtr) {

			Curr_El=(Element*)(currentPtr->value);

			influx[3];
			influx[0]=*(Curr_El->get_influx()+0);
			influx[1]=*(Curr_El->get_influx()+1);
			influx[2]=*(Curr_El->get_influx()+2);

			if(!(influx[0]>=0.0)) {
				printf("negative influx=%g\n",influx[0]);
				assert(0);
			}

			if(Curr_El->get_adapted_flag()>0) {

				d_uvec = Curr_El->get_d_state_vars();
				nd = (Node*) NodeTable->lookup(Curr_El->pass_key());

				// -- calc contribution of flux source
				flux_src_coef=0;
				curr_time=(timeprops_ptr->time)*(timeprops_ptr->TIME_SCALE);

				//VxVy[2];
				if(*(Curr_El->get_state_vars()+0)>GEOFLOW_TINY) {
					VxVy[0]=*(Curr_El->get_state_vars()+1)/ *(Curr_El->get_state_vars()+0);
					VxVy[1]=*(Curr_El->get_state_vars()+2)/ *(Curr_El->get_state_vars()+0);
				}
				else
				VxVy[0]=VxVy[1]=0.0;

#ifdef STOPCRIT_CHANGE_SOURCE
				IF_STOPPED=Curr_El->get_stoppedflags();
#else
				IF_STOPPED=!(!(Curr_El->get_stoppedflags()));
#endif

				predict_(Curr_El->get_state_vars(), d_uvec, (d_uvec+NUM_STATE_VARS),
						Curr_El->get_prev_state_vars(), &tiny,
						Curr_El->get_kactxy(), &dt2, Curr_El->get_gravity(),
						Curr_El->get_curvature(),
						&(matprops_ptr->bedfrict[Curr_El->get_material()]),
						&(matprops_ptr->intfrict),
						Curr_El->get_d_gravity(), &(matprops_ptr->frict_tiny),
						order_flag, VxVy,
						&IF_STOPPED,influx);

				/* apply bc's */
#ifdef APPLY_BC
				for(j=0;j<4;j++)
				if(*(Curr_El->get_neigh_proc()+j) == INIT)   // this is a boundary!
				for(k=0;k<NUM_STATE_VARS;k++)
				*(Curr_El->get_state_vars()+k) = 0;
#endif
			}
			currentPtr=currentPtr->next;
		}
	}
	/* finished predictor step */
	/* really only need to share dudx, state_vars, and kactxy */
	move_data(nump, myid, El_Table, NodeTable,timeprops_ptr);

	/* calculate the slopes for the new (half-time step) state variables */
	slopes(El_Table, NodeTable, matprops_ptr);
#endif  //SECOND_ORDER

	/* really only need to share dudx, state_vars, and kactxy */
	move_data(nump, myid, El_Table, NodeTable, timeprops_ptr);

	/* calculate kact/pass */
	double dt_not_used = get_coef_and_eigen(El_Table, NodeTable, matprops_ptr, fluxprops,
	    timeprops_ptr, 1);

	/*
	 * calculate edge states
	 */
	double outflow = 0.0; //shouldn't need the =0.0 assignment but just being cautious.
	//printf("step: before calc_edge_states\n"); fflush(stdout);

	calc_edge_states<Element>(El_Table, NodeTable, matprops_ptr, timeprops_ptr, myid, order_flag,
	    &outflow);
	outflow *= dt;

	/*
	 * corrector step and b.c.s
	 */

	//for comparison of magnitudes of forces in slumping piles
	double forceint = 0.0, elemforceint;
	double forcebed = 0.0, elemforcebed;
	double eroded = 0.0, elemeroded;
	double deposited = 0.0, elemdeposited;
	double realvolume = 0.0;

	buck = El_Table->getbucketptr();

	// mdj 2007-04 this loop has pretty much defeated me - there is
	//             a dependency in the Element class that causes incorrect
	//             results
	//

	for (i = 0; i < El_Table->get_no_of_buckets(); i++)
		if (*(buck + i)) {
			HashEntryPtr currentPtr = *(buck + i);
			while (currentPtr) {
				Element* Curr_El = (Element*) (currentPtr->value);
				if (Curr_El->get_adapted_flag() > 0) { //if this is a refined element don't involve!!!

					double *dxy = Curr_El->get_dx();
					// if calculations are first-order, predict is never called
					// ... so we need to update prev_states
//					void *Curr_El_out = (void *) Curr_El;
					//I believe it's because we need correct function be a friend function of node class, but we do not want to add element header to node.h
					if (*order_flag == 1)
						Curr_El->update_prev_state_vars();

					//if (*(Curr_El->pass_key())==2151461179 && *(Curr_El->pass_key()+1)==330382099 /*&& timeprops->iter == 9 */)
					//  cout<<"step is cheking the element"<<endl;

					correct(NodeTable, El_Table, dt, matprops_ptr, fluxprops, timeprops_ptr, Curr_El,
					    &elemforceint, &elemforcebed, &elemeroded, &elemdeposited);

					forceint += fabs(elemforceint);
					forcebed += fabs(elemforcebed);
					realvolume += dxy[0] * dxy[1] * *(Curr_El->get_state_vars());
					eroded += elemeroded;
					deposited += elemdeposited;

					double *coord = Curr_El->get_coord();
					//update the record of maximum pileheight in the area covered by this element
					double hheight = *(Curr_El->get_state_vars());

//					int ind = Curr_El->get_sol_rec_ind();
//					jacobian = solHyst->at(ind);

#ifdef MAX_DEPTH_MAP
					double pfheight[6];
					outline_ptr->update(coord[0] - 0.5 * dxy[0], coord[0] + 0.5 * dxy[0],
					    coord[1] - 0.5 * dxy[1], coord[1] + 0.5 * dxy[1], hheight, pfheight);
#endif

//#ifdef APPLY_BC
//					for (j = 0; j < 4; j++)
//						if (*(Curr_El->get_neigh_proc() + j) == INIT) // this is a boundary!
//							for (k = 0; k < NUM_STATE_VARS; k++)
//								*(Curr_El->get_state_vars() + k) = 0;
//#endif

				}
				currentPtr = currentPtr->next;
			}
		}

	//update the orientation of the "dryline" (divides partially wetted cells
	//into wet and dry parts solely based on which neighbors currently have
	//pileheight greater than GEOFLOW_TINY
	for (i = 0; i < El_Table->get_no_of_buckets(); i++) {
		HashEntryPtr currentPtr = *(buck + i);
		while (currentPtr) {
			Element* Curr_El = (Element*) (currentPtr->value);
			currentPtr = currentPtr->next;
			if (Curr_El->get_adapted_flag() > 0) //if this is a refined element don't involve!!!
				Curr_El->calc_wet_dry_orient(El_Table);
		}
	}

	/* finished corrector step */
	calc_stats(El_Table, NodeTable, myid, matprops_ptr, timeprops_ptr, statprops_ptr, discharge, dt);

//	double tempin[6], tempout[6];
//	tempin[0] = outflow;    //volume that flew out the boundaries this iteration
//	tempin[1] = eroded;     //volume that was eroded this iteration
//	tempin[2] = deposited;  //volume that is currently deposited
//	tempin[3] = realvolume; //"actual" volume within boundaries
//	tempin[4] = forceint;   //internal friction force
//	tempin[5] = forcebed;   //bed friction force
//
//	MPI_Reduce(tempin, tempout, 6, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
//
//	statprops_ptr->outflowvol += tempout[0] * (matprops_ptr->HEIGHT_SCALE)
//	    * (matprops_ptr->LENGTH_SCALE) * (matprops_ptr->LENGTH_SCALE);
//	statprops_ptr->erodedvol += tempout[1] * (matprops_ptr->HEIGHT_SCALE)
//	    * (matprops_ptr->LENGTH_SCALE) * (matprops_ptr->LENGTH_SCALE);
//	statprops_ptr->depositedvol = tempout[2] * (matprops_ptr->HEIGHT_SCALE)
//	    * (matprops_ptr->LENGTH_SCALE) * (matprops_ptr->LENGTH_SCALE);
//	statprops_ptr->realvolume = tempout[3] * (matprops_ptr->HEIGHT_SCALE)
//	    * (matprops_ptr->LENGTH_SCALE) * (matprops_ptr->LENGTH_SCALE);
//
//	statprops_ptr->forceint = tempout[4] / tempout[3] * matprops_ptr->GRAVITY_SCALE;
//	statprops_ptr->forcebed = tempout[5] / tempout[3] * matprops_ptr->GRAVITY_SCALE;

	//calc_volume(El_Table, myid, matprops_ptr, timeprops_ptr, dt, v_star, nz_star);

	return;
}
示例#10
0
文件: hist.c 项目: FauxFaux/cyclone
int main(int argc, char *argv[])
{
  char buffer[2000];
  FILE *infp = NULL;
  int nbins = 20, idx = 0;
  char *heapname, *point;
  double max, min, delta;
  struct bin *bins = NULL;
  double points[MAX_POINTS];
  double var, mean, SIQR, med, bindiff = 0.005;
  char **arg;
  int verbose = 0;

  /* get arguments */
  arg = argv + 1;
  while (*arg != NULL) {
    if ((*arg)[0] == '-') {
      switch((*arg)[1]) {
        case 'i':
          arg++;
	  if (infp != NULL) fclose(infp);
	  infp = fopen(*arg,"r");
	  if (infp == NULL) {
	    fprintf(stderr,"Could not open input file \"%s\"\n",arg);
	    USAGE(argv[0]);
	  }
	  break;

        case 'n':
          arg++;
          bindiff = 0.0; /* disable runtime divvying of bin sizes */
          nbins = atoi(*arg);
          bins = (struct bin *)calloc(nbins, sizeof(struct bin));
          if (bins == NULL) {
            fprintf(stderr,"Calloc failed\n");
            exit(1);
          }
          break;

        case 'f':
          arg++;
          sscanf(*arg,"%lf",&bindiff);
          break;

        case 'v':
	  verbose=1;
	  break;

        case '?':
          USAGE(argv[0]);

        default:
          fprintf(stderr,"Unknown option %s\n",*arg);
          USAGE(argv[0]);
     }
     arg++;
   }
   else
     break;
  }

  if (infp == NULL) infp = stdin;

  /* read/process input one line at a time;
     store the input points into the points array */ 
  while (fgets(buffer,sizeof(buffer),infp) != NULL) {
    heapname =  strtok(buffer," ");
    point = strtok(NULL," ");
    idx = 0;
    while (point != NULL) {
      if (idx == MAX_POINTS) {
        fprintf(stderr,"Can't have more than %d input points!\n",MAX_POINTS);
        exit(1);
      }
      if (sscanf(point,"%lf",&points[idx++]) != 1) {
	point = NULL;
	idx--;
      }
      point = strtok(NULL," ");
    }

    get_max_min_med(points,idx,&max,&min,&med);

    /* calculate/create # of bins if using fraction_from_med determination */
    if (bindiff != 0.0) {
      double delta = med * bindiff;
      nbins = ((max-min) / delta) + 1;

      if (bins != NULL)
        free(bins);
      bins = (struct bin *)calloc(nbins, sizeof(struct bin));
      if (bins == NULL) {
        fprintf(stderr,"Calloc failed\n");
        exit(1);
      }
    }

    init_bins(bins,nbins,max,min);
    calc_stats(bins,nbins,points,idx,&var,&mean,&SIQR);
    if (verbose)
      print_stats(heapname,min,bins,nbins,idx,var,mean,med,SIQR);
    else {
      double stddev, lowquart, hiquart;
      int qmed, qlow, qhi;
      stddev = sqrt(var);
      qlow = idx / 4;
      qhi = 3 * idx / 4;
      lowquart = points[qlow];
      hiquart = points[qhi];
      printf("%s %lf %lf %lf %lf %lf %lf\n",
	     heapname, mean, stddev/mean, med, lowquart, hiquart, SIQR);
    }
  }
  fclose(infp);

  return 0;
}
示例#11
0
void step(HashTable* El_Table, HashTable* NodeTable, int myid, int nump,
	  MatProps* matprops_ptr, TimeProps* timeprops_ptr, 
	  PileProps *pileprops_ptr, FluxProps *fluxprops, 
	  StatProps* statprops_ptr, int* order_flag, 
	  OutLine* outline_ptr, DISCHARGE* discharge, int adaptflag)
{
  /* 
   * PREDICTOR-CORRECTED based on Davis' Simplified Godunov Method 
   */

  /* pass off proc data here (really only need state_vars for off-proc neighbors) */
  move_data(nump, myid, El_Table, NodeTable,timeprops_ptr);

  slopes(El_Table, NodeTable, matprops_ptr);

  // get coefficients, eigenvalues, hmax and calculate the time step 
  double dt = get_coef_and_eigen(El_Table, NodeTable, matprops_ptr, 
				 fluxprops, timeprops_ptr,0);

  timeprops_ptr->incrtime(&dt); //also reduces dt if necessary

  // assign influxes and then if any new sources are activating in 
  // current time step refine and re-mark cells 
  adapt_fluxsrc_region(El_Table,NodeTable,matprops_ptr,pileprops_ptr,fluxprops,
		       timeprops_ptr,dt,myid,adaptflag);

  int i;

  HashEntryPtr* buck = El_Table->getbucketptr();
  HashEntryPtr currentPtr;
  Element* Curr_El;

  double dt2 = .5*dt; // dt2 is set as dt/2 !
  // printf("dt for explicit is ...%f \n", dt);

  /*
   *  predictor step
   */
  int j,k, counter;
  double tiny = GEOFLOW_TINY,phi;
  double flux_src_coef=0;

  // printf("the number of elements are ...........%d\n", num_nonzero_elem(El_Table));
#ifdef SECOND_ORDER
  //-------------------go through all the elements of the subdomain and  
  //-------------------calculate the state variables at time .5*delta_t
  /* mdj 2007-04 */
  int IF_STOPPED;
  double curr_time,influx[3],*d_uvec,*lap_phi; //VxVy[2];
  double VxVy[2];
  Node* nd;
#pragma omp parallel for                                                \
  private(currentPtr,Curr_El,IF_STOPPED,influx,j,k,curr_time,flux_src_coef,VxVy)
  for(i=0; i<El_Table->get_no_of_buckets(); i++)
    if(*(buck+i))
      {
	currentPtr = *(buck+i);
	while(currentPtr){

	  Curr_El=(Element*)(currentPtr->value);

	  influx[3];
	  influx[0]=*(Curr_El->get_influx()+0);
	  influx[1]=*(Curr_El->get_influx()+1);
	  influx[2]=*(Curr_El->get_influx()+2);

	  if(!(influx[0]>=0.0)){
	    printf("negative influx=%g\n",influx[0]);
	    assert(0);
	  }


	  if(Curr_El->get_adapted_flag()>0){
	    lap_phi=Curr_El->get_lap_phi();
	    d_uvec = Curr_El->get_d_state_vars();
	    nd = (Node*) NodeTable->lookup(Curr_El->pass_key());

	    // -- calc contribution of flux source
	    flux_src_coef=0;
	    curr_time=(timeprops_ptr->time)*(timeprops_ptr->TIME_SCALE);

	    //VxVy[2]; 
	    if(*(Curr_El->get_state_vars())<0/*GEOFLOW_TINY*/) {
	      VxVy[0]=*(Curr_El->get_state_vars()+2)/ *(Curr_El->get_state_vars()+1);
	      VxVy[1]=*(Curr_El->get_state_vars()+3)/ *(Curr_El->get_state_vars()+1);
	    }
	    else
	      VxVy[0]=VxVy[1]=0.0;

#ifdef STOPCRIT_CHANGE_SOURCE
	    IF_STOPPED=Curr_El->get_stoppedflags();
#else
	    IF_STOPPED=!(!(Curr_El->get_stoppedflags()));
#endif

	    predict_(Curr_El->get_state_vars(), d_uvec, (d_uvec+NUM_STATE_VARS),lap_phi,
		     Curr_El->get_prev_state_vars(), &tiny, 
		     Curr_El->get_kactxy(), &dt2, Curr_El->get_gravity(), 
		     Curr_El->get_curvature(),
		     &(matprops_ptr->bedfrict[Curr_El->get_material()]), 
		     &(matprops_ptr->intfrict),
		     Curr_El->get_d_gravity(), &(matprops_ptr->frict_tiny), 
		     order_flag, VxVy, 
		     &IF_STOPPED,influx);

	    /* apply bc's */
#ifdef APPLY_BC
	    for(j=0;j<4;j++)
	      if(*(Curr_El->get_neigh_proc()+j) == INIT)   // this is a boundary!
		for(k=1;k<NUM_STATE_VARS;k++)
		  *(Curr_El->get_state_vars()+k) = 0;
#endif
	  }
	  currentPtr=currentPtr->next;      	    
	}
      }
  /* finished predictor step */
  /* really only need to share dudx, state_vars, and kactxy */
  move_data(nump, myid, El_Table, NodeTable,timeprops_ptr);

  /* calculate the slopes for the new (half-time step) state variables */
  slopes(El_Table, NodeTable, matprops_ptr);
#endif  //SECOND_ORDER

	/* really only need to share dudx, state_vars, and kactxy */
  move_data(nump, myid, El_Table, NodeTable,timeprops_ptr);

  /* calculate kact/pass */
  double dt_not_used = get_coef_and_eigen(El_Table, NodeTable, matprops_ptr,
					  fluxprops, timeprops_ptr, 1);

  /*
   * calculate edge states
   */
  double outflow=0.0;  //shouldn't need the =0.0 assignment but just being cautious.
  //printf("step: before calc_edge_states\n"); fflush(stdout);
  calc_edge_states(El_Table,NodeTable,matprops_ptr,timeprops_ptr,myid,order_flag,&outflow);
	
  //printf("the outflow in step after calc_edge ..............%f\n",outflow);
  outflow*=dt;
  //printf("the dt in step ...............%f\n",dt);
  //printf("the outflow in step ...............%f\n",outflow);

 MapNames mapnames;
  char *b,*c,*d;
  char a[5]="abs";// ,b[5],c[5],d[5];
  b=c=d=a;
  int ce=0;

  mapnames.assign(a, b, c,d, ce);

  if (/*timeprops_ptr->iter%50==4||*/timeprops_ptr->iter==1){
    int tt=timeprops_ptr->iter;
    //for(int ii=0;ii<1000;ii++){

      initialization( NodeTable, El_Table, dt, matprops_ptr,fluxprops, timeprops_ptr);
      meshplotter(El_Table, NodeTable,matprops_ptr,timeprops_ptr,&mapnames,ce);
      //timeprops_ptr->iter++;
      //}
      //timeprops_ptr->iter=tt;
  }


  /*
   * corrector step and b.c.s
   */

  //for comparison of magnitudes of forces in slumping piles
  double forceint=0.0, elemforceint;
  double forcebed=0.0, elemforcebed;
  double eroded=0.0, elemeroded;
  double deposited=0.0, elemdeposited;
  double realvolume=0.0;



  for(i=0; i<El_Table->get_no_of_buckets(); i++)
    if(*(buck+i))
      {
	HashEntryPtr currentPtr = *(buck+i);
	while(currentPtr)
	  {
	    Element* Curr_El=(Element*)(currentPtr->value);
	    if(Curr_El->get_adapted_flag()>0) { //if this is a refined element don't involve!!!

	      double *dxy=Curr_El->get_dx();
	      // if calculations are first-order, predict is never called
	      // ... so we need to update prev_states
	      // double phi=*(Curr_El->get_state_vars())+*(Curr_El->get_state_vars()+4);

	      if ( *order_flag == 1 )
		Curr_El->update_prev_state_vars();

	      void *Curr_El_out= (void *) Curr_El;

	      correct(NodeTable, El_Table, dt, matprops_ptr,
		      fluxprops, timeprops_ptr,
		      Curr_El_out,
		      &elemforceint,&elemforcebed,
		      &elemeroded,&elemdeposited);

	      for(int kk=0;kk<6;kk++) 
		if (isnan(*(Curr_El->get_state_vars()+kk)))
		  printf("Hello this is the NAN");
	      forceint+=fabs(elemforceint);
	      forcebed+=fabs(elemforcebed);
	      realvolume+=dxy[0]*dxy[1]**(Curr_El->get_state_vars()+1);
	      eroded+=elemeroded;
	      deposited+=elemdeposited;

	      double *coord=Curr_El->get_coord();	      
	      //update the record of maximum pileheight in the area covered by this element
	      double hheight=*(Curr_El->get_state_vars()+1);
	      if(hheight>0 && hheight<0);


#ifdef MAX_DEPTH_MAP
	      double pfheight[6];
	      outline_ptr->update(coord[0]-0.5*dxy[0],coord[0]+0.5*dxy[0],
				  coord[1]-0.5*dxy[1],coord[1]+0.5*dxy[1],
				  hheight,pfheight);      
#endif

#ifdef APPLY_BC
	      for(j=0;j<4;j++)
		if(*(Curr_El->get_neigh_proc()+j) == INIT)   // this is a boundary!
		  for(k=1;k<NUM_STATE_VARS;k++)
		    *(Curr_El->get_state_vars()+k) = 0;
#endif
	    }
	    currentPtr=currentPtr->next;      	    
	  }
      }

//  for(i=0; i<El_Table->get_no_of_buckets(); i++) {
//    if(*(buck+i))
//      {
//  	HashEntryPtr currentPtr = *(buck+i);
//  	while(currentPtr)
//  	  {
//  	    Element* Curr_El=(Element*)(currentPtr->value);
//  	    if(Curr_El->get_adapted_flag()>0
//	       )//&& ((timeprops_ptr->iter%5==4)))//||(timeprops_ptr->iter%5==2)))
//  	      { //if this is a refined element don't involve!!!
//  		//if (*(Curr_El->get_state_vars()+1)>1e-3)
//		//{					
//		phi = *(Curr_El->get_state_vars());
//		if(phi>1) phi=1;
//		if(phi<0) phi=0;
		//}
  		//else 
		//phi=0;
	//	*(Curr_El->get_state_vars())=phi;
		//  		Curr_El->update_phase1(phi);
//  	      } 
//  	    currentPtr=currentPtr->next;      	    
//  	  }
//      }
//  }

  //update the orientation of the "dryline" (divides partially wetted cells
  //into wet and dry parts solely based on which neighbors currently have 
  //pileheight greater than GEOFLOW_TINY
  //for(i=0; i<El_Table->get_no_of_buckets(); i++) 
  // {
  //     HashEntryPtr currentPtr = *(buck+i);
  //    while(currentPtr) 
//	{
//	  Element* Curr_El=(Element*)(currentPtr->value);
//	  currentPtr=currentPtr->next;      	    
//	  if(Curr_El->get_adapted_flag()>0) //if this is a refined element don't involve!!!
//	    Curr_El->calc_wet_dry_orient(El_Table);
//	}
  //  }

  /* finished corrector step */
  calc_stats(El_Table, NodeTable, myid, matprops_ptr, timeprops_ptr, 
	     statprops_ptr, discharge, dt);

  double tempin[6], tempout[6];
  tempin[0]=outflow;    //volume that flew out the boundaries this iteration
  tempin[1]=eroded;     //volume that was eroded this iteration
  tempin[2]=deposited;  //volume that is currently deposited
  tempin[3]=realvolume; //"actual" volume within boundaries
  tempin[4]=forceint;   //internal friction force
  tempin[5]=forcebed;   //bed friction force

  MPI_Reduce(tempin,tempout,6,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);

  statprops_ptr->outflowvol+=tempout[0]*(matprops_ptr->HEIGHT_SCALE)*
    (matprops_ptr->LENGTH_SCALE)*(matprops_ptr->LENGTH_SCALE);
  statprops_ptr->erodedvol+=tempout[1]*(matprops_ptr->HEIGHT_SCALE)*
    (matprops_ptr->LENGTH_SCALE)*(matprops_ptr->LENGTH_SCALE);
  statprops_ptr->depositedvol=tempout[2]*(matprops_ptr->HEIGHT_SCALE)*
    (matprops_ptr->LENGTH_SCALE)*(matprops_ptr->LENGTH_SCALE);
  statprops_ptr->realvolume=tempout[3]*(matprops_ptr->HEIGHT_SCALE)*
    (matprops_ptr->LENGTH_SCALE)*(matprops_ptr->LENGTH_SCALE);

  statprops_ptr->forceint=tempout[4]/tempout[3]*matprops_ptr->GRAVITY_SCALE;
  statprops_ptr->forcebed=tempout[5]/tempout[3]*matprops_ptr->GRAVITY_SCALE;

  return;
}
示例#12
0
int control_loop_run( void )
{
    int first_time = 1;
    long long start, end;
	long long loop_start;
    uint32_t  rem_time;

    next_period = get_utime( ) + us_period;

    while( running )
    {
        trace_data.value_3 = (int16_t)( period * 1000 );
        trace_data.value_4 = (int16_t)( heli_state );

        /* start of STAT_TO_JAV */
        start              = get_utime( );
        loop_start         = start;
        rem_time           = (uint32_t)( start % MAX_TIME );
        trace_data.value_5 = (int16_t)( rem_time >> 16 );
        trace_data.value_6 = (int16_t)( rem_time );

        if( send_motor_signals( ) )
        {
            break;
        }

        end = get_utime( );
        rem_time           = (uint32_t)( end % MAX_TIME );
        trace_data.value_7 = (int16_t)( rem_time >> 16 );
        trace_data.value_8 = (int16_t)( rem_time );
        calc_stats( end - start, STAT_TO_JAV );

        /* start of STAT_FROM_JAV */
	    start = get_utime( );

	    if( javiator_port_get_data( &javiator_data ) )
        {
            fprintf( stderr, "ERROR: connection to JAviator broken\n" );
            heli_state = HELI_STATE_SHUTDOWN;
            perform_shut_down( );
            break;
	    }

        if( ubisense_enabled )
        {
            if( (new_data_x = new_data_y = ubisense_port_is_new_data( )) )
            {
                ubisense_port_get_data( &sensor_data );
            }
        }

	    end = get_utime( );
        rem_time            = (uint32_t)( end % MAX_TIME );
        trace_data.value_9  = (int16_t)( rem_time >> 16 );
        trace_data.value_10 = (int16_t)( rem_time );
	    calc_stats( end - start, STAT_FROM_JAV );

        /* start of STAT_FROM_TERM */
        start = get_utime( );

        if( check_terminal_connection( ) )
        {
            heli_state = HELI_STATE_SHUTDOWN;

            if( first_time )
            {
                fprintf( stderr, "ERROR: connection to Terminal broken\n" );
                first_time = 0;
            }
        }
        else
        {
            first_time = 1;
        }

        get_command_data( );
        get_control_params( );

        end = get_utime( );
        rem_time            = (uint32_t)( end % MAX_TIME );
        trace_data.value_11 = (int16_t)( rem_time >> 16 );
        trace_data.value_12 = (int16_t)( rem_time );
        calc_stats( end - start, STAT_FROM_TERM );

        /* start of STAT_CONTROL */
        start = get_utime( );

        prepare_sensor_data( );
 
        switch( heli_state )
        {
            case HELI_STATE_GROUND:
                perform_ground_actions( );
                break;

            case HELI_STATE_FLYING:
                compute_motor_signals( );
                break;

            case HELI_STATE_SHUTDOWN:
                perform_shut_down( );
                break;

            default:
                fprintf( stderr, "ERROR: invalid altitude mode %d\n", heli_state );
        }

        end = get_utime( );
        rem_time            = (uint32_t)( end % MAX_TIME );
        trace_data.value_13 = (int16_t)( rem_time >> 16 );
        trace_data.value_14 = (int16_t)( rem_time );
        calc_stats( end - start, STAT_CONTROL );

        /* start of STAT_TO_TERM */
        start = get_utime( );

        send_report_to_terminal( );
        send_trace_data_to_terminal( );

        end = get_utime( );
        rem_time            = (uint32_t)( end % MAX_TIME );
        trace_data.value_15 = (int16_t)( rem_time >> 16 );
        trace_data.value_16 = (int16_t)( rem_time );
        calc_stats( end - start, STAT_TO_TERM );
        calc_stats( end - loop_start, STAT_ALL );

        /* start of STAT_SLEEP */
        start = get_utime( );

        wait_for_next_period( );

        end = get_utime( );
        calc_stats( end - start, STAT_SLEEP );

        if( ++loop_count < 0 )
        {
            fprintf( stderr, "WARNING: stats overrun\n" );
            memset( stats, 0, sizeof( stats ) );
            loop_count = 0;
        }
    }

    outlier_filter_destroy( &cof_out_x );
    outlier_filter_destroy( &cof_out_y );
    iir_lp_filter_destroy ( &iir_acc_x );
    iir_lp_filter_destroy ( &iir_acc_y );
    iir_lp_filter_destroy ( &iir_acc_z );
    iir_lp_filter_destroy ( &iir_cmd_roll );
    iir_lp_filter_destroy ( &iir_cmd_pitch );
    iir_lp_filter_destroy ( &iir_cmd_yaw );
    iir_lp_filter_destroy ( &iir_cmd_z );
    average_filter_destroy( &avg_bmu_maps );
    median_filter_destroy ( &med_bmu_temp );
    median_filter_destroy ( &med_bmu_batt );
    attitude_ekf_destroy  ( &ekf_att_roll );
    attitude_ekf_destroy  ( &ekf_att_pitch );
    attitude_ekf_destroy  ( &ekf_att_yaw );
    position_ekf_destroy  ( &ekf_pos_x );
    position_ekf_destroy  ( &ekf_pos_y );
    position_ekf_destroy  ( &ekf_pos_z );
    controller_destroy    ( &ctrl_roll );
    controller_destroy    ( &ctrl_pitch );
    controller_destroy    ( &ctrl_yaw );
    controller_destroy    ( &ctrl_x );
    controller_destroy    ( &ctrl_y );
    controller_destroy    ( &ctrl_z );

    print_stats( );
    return( 0 );
}