Esempio n. 1
0
static void update_stats(struct Stats *st, int n, double dx, double dy,
			 double dg, double d2)
{
    update_max(&st->x, n, dx);
    update_max(&st->y, n, dy);
    update_max(&st->g, n, dg);
    st->sum2 += d2;
}
Esempio n. 2
0
int main() {
	freopen("perimeter.in", "r", stdin);
	freopen("perimeter.out", "w", stdout);
	int min_x = INF, min_y = INF;
	int max_x = -INF, max_y = -INF;
	scanf("%d", &n);
	for (int i = 1; i <= n; ++ i) {
		int x, y;
		scanf("%d%d", &x, &y);
		update_min(min_x, x);
		update_min(min_y, y);
		update_max(max_x, x);
		update_max(max_y, y);
		points[i] = Point(x, y);
		set.insert(points[i]);
	}

	for (int i = 1; i <= n; ++ i) {
		int x = points[i].x;
		int y = points[i].y;
		for (int j = 0; j < 8; ++ j) {
			int dx = x + D[j][0];
			int dy = y + D[j][1];
			if (set.find(Point(dx, dy)) == set.end()) {
				add(Point(dx, dy));
			}
		}
	}


	for (int i = 0; i <= counter; ++ i) {
		ancestor[i] = i;
	}
	foreach(iter, all_points) {
		int x = (*iter).first.x;
		int y = (*iter).first.y;
		if (x <= min_x || x >= max_x || y <= min_y || y >= max_y) {
			joint(0, (*iter).second);
		}
		for (int i = 0; i < 4; ++ i) {
			int dx = x + D[i][0];
			int dy = y + D[i][1];
			int id = get_id(Point(dx, dy));
			if (id != -1) {
				joint((*iter).second, id);
			}
		}
	}
Esempio n. 3
0
 double random_sr_repulsion (double rsq, RandomContext *random)
 {
     double rsq_evt = random_repulsive_lift_g  (rsq, random);
     if (rsq_evt <= sq (LJ_MINIMUM))
         update_max (&rsq_evt, random_repulsive_lift_lj (rsq, random));
     return rsq_evt - rsq;
 }
Esempio n. 4
0
static void update_swap(struct globalstat *gs,
			const libtop_tsamp_t *tsamp) {
    struct top_uinteger used_result, available_result;
    char used[6];
    char avail[6];

    if(!tsamp->xsu_is_valid) {
	gs->length = snprintf(gs->data, sizeof(gs->data),
			      "Swap: N/A");

	if(gs->length < 0)
	    reset_globalstat(gs);

	return;
    }

    /*FIXME a p_xsu added to libtop for delta mode would be nice.*/
    used_result = top_init_uinteger(tsamp->xsu.xsu_used, false);
    available_result = top_init_uinteger(tsamp->xsu.xsu_avail, false);

    if(top_humanize_uinteger(used, sizeof(used), used_result)
       || top_humanize_uinteger(avail, sizeof(avail), available_result)) {
	reset_globalstat(gs);
	return;
    }
    
    gs->length = snprintf(gs->data, sizeof(gs->data),
			  "Swap: %s + %s free.", used, avail);

    if(gs->length < 0)
	reset_globalstat(gs);

    update_max(gs);
}
Esempio n. 5
0
static void update_memregions(struct globalstat *gs,
			      const libtop_tsamp_t *tsamp) {
    char resident[6];
    char priv[6];
    char shared[6];

    
    

    if((-1 == humanize_globalstat(resident, sizeof(resident), tsamp->rprvt))
       || (-1 == humanize_globalstat(priv, sizeof(priv), tsamp->fw_private))
       || (-1 == humanize_globalstat(shared, sizeof(shared), tsamp->rshrd))) {
	reset_globalstat(gs);
	return;
    }

    gs->length = snprintf(gs->data, sizeof(gs->data),
			  "MemRegions: %" PRIu32 " total, "
			  "%s resident, "
			  "%s private, "
			  "%s shared.",
			  tsamp->reg,
			  resident,
			  priv,
			  shared);
    if(gs->length < 0) {
	reset_globalstat(gs);
	return;
    }
    
    update_max(gs);    
}
Esempio n. 6
0
int	*prepare_tab(char *file, int width, int *max, int height)
{
  int	j;
  int	i;
  int	*tab;

  if ((tab = malloc(sizeof(int) * my_strlen(file))) == NULL)
    return (exit_prepare_tab(tab, NULL));
  max = set_max();
  j = 0;
  i = 0;
  while (*file++ != '\n');
  while (file[i++] != '\0' && max[0] < width && max[0] < height)
    {
      if (file[i - 1] == '.')
	tab[j] = check_lowest(tab, width, j);
      else if (file[i - 1] == 'o')
	tab[j] = 0;
      else if (file[i - 1] == '\n' || file[i - 1] == '\0')
	tab[j] = -1;
      else
	return (exit_prepare_tab(tab, max));
      if (tab[j++] > max[0])
	max = update_max(max, j - 1, tab[j - 1]);
    }
  free(tab);
  return (max);
}
Esempio n. 7
0
static void update_sharedlibs(struct globalstat *gs, 
			      const libtop_tsamp_t *tsamp) {
    char code[6];
    char data[6];
    char linkedit[6];

    if((-1 == humanize_number(code, sizeof(code), tsamp->fw_code, "", 
			      HN_AUTOSCALE, GLOBALSTAT_HN_FORMAT))
       || (-1 == humanize_number(data, sizeof(data), tsamp->fw_data, "",
				 HN_AUTOSCALE, GLOBALSTAT_HN_FORMAT))
       || (-1 == humanize_number(linkedit, sizeof(linkedit), 
				 tsamp->fw_linkedit, "", HN_AUTOSCALE, 
				 GLOBALSTAT_HN_FORMAT))) {
	
	reset_globalstat(gs);
	return;
    }

    gs->length = snprintf(gs->data, sizeof(gs->data),
			  "SharedLibs: "
			  "%s resident, "
			  "%s data, "
			  "%s linkedit.",
			  code,
			  data,
			  linkedit);

    if(gs->length < 0) {
	reset_globalstat(gs);
	return;
    }

    update_max(gs);
}
Esempio n. 8
0
int main() {
	freopen("photo.in", "r", stdin);
	freopen("photo.out", "w", stdout);
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= m; ++ i) {
		scanf("%d%d", a + i, b + i);
	}
	int limit = n + 1;

	for (int i = 0; i <= limit; ++ i) {
		label[i] = limit;
	}
	for (int i = 1; i <= m; ++ i) {
		update_min(label[b[i]], a[i]);
	}
	for (int i = limit, now = limit; i > 0; -- i) {
		update_min(now, label[i]);
		right[i] = now - 1;
	}

	for (int i = 0; i <= limit; ++ i) {
		label[i] = 0;
	}
	for (int i = 1; i <= m; ++ i) {
		update_max(label[b[i]], a[i]);
	}
	for (int i = 1, now = 0; i <= limit; ++ i) {
		left[i] = now;
		update_max(now, label[i]);
	}

	build(1, 0, limit);
	for (int i = 1; i <= limit; ++ i) {
		if (left[i] <= right[i]) {
			dp[i] = query(1, 0, limit, left[i], right[i]) + 1;
			insert(1, 0, limit, i, dp[i]);
		}
	}
	if (dp[limit] <= 0) {
		puts("-1");
	} else {
		printf("%d\n", dp[limit] - 1);
	}
	return 0;
}
Esempio n. 9
0
static void update_cpu(struct globalstat *gs, const libtop_tsamp_t *tsamp) {
    unsigned long long userticks, systicks, idleticks, totalticks;
    int mode;
    unsigned long long userwhole, userpart, syswhole, syspart, 
	idlewhole, idlepart;
  
    userticks = tsamp->cpu.cpu_ticks[CPU_STATE_USER] 
	+ tsamp->cpu.cpu_ticks[CPU_STATE_NICE];
    systicks = tsamp->cpu.cpu_ticks[CPU_STATE_SYSTEM];
    idleticks = tsamp->cpu.cpu_ticks[CPU_STATE_IDLE];

    mode = top_prefs_get_mode();

    if(STATMODE_ACCUM == mode) {
	userticks -= (tsamp->b_cpu.cpu_ticks[CPU_STATE_USER] +
		      tsamp->b_cpu.cpu_ticks[CPU_STATE_NICE]);
    
	systicks -= tsamp->b_cpu.cpu_ticks[CPU_STATE_SYSTEM];
	idleticks -= tsamp->b_cpu.cpu_ticks[CPU_STATE_IDLE];
    }

    if(STATMODE_DELTA == mode || STATMODE_NON_EVENT == mode) {
	userticks -= (tsamp->p_cpu.cpu_ticks[CPU_STATE_USER] +
		      tsamp->p_cpu.cpu_ticks[CPU_STATE_NICE]);
    
	systicks -= tsamp->p_cpu.cpu_ticks[CPU_STATE_SYSTEM];
	idleticks -= tsamp->p_cpu.cpu_ticks[CPU_STATE_IDLE];
    }

    totalticks = userticks + systicks + idleticks;

    if(0 == totalticks)
	return;


    cpu_percent(userticks, totalticks, &userwhole, &userpart);
    cpu_percent(systicks, totalticks, &syswhole, &syspart);
    cpu_percent(idleticks, totalticks, &idlewhole, &idlepart);

    gs->length = snprintf(gs->data, sizeof(gs->data),
			  "CPU usage: " 
			  "%" PRIu64 "." "%" PRIu64 "%% user, "
			  "%" PRIu64 "." "%" PRIu64 "%% sys, "
			  "%" PRIu64 "." "%" PRIu64 "%% idle ",
			  userwhole, userpart, 
			  syswhole, syspart,
			  idlewhole, idlepart);

    if(gs->length < 0) {
	reset_globalstat(gs);
	return;
    }

    update_max(gs);
}
Esempio n. 10
0
static void update_load(struct globalstat *gs, const libtop_tsamp_t *tsamp) {
    gs->length = snprintf(gs->data, sizeof(gs->data),
			  "Load Avg: %.2f, %.2f, %.2f ",
			  tsamp->loadavg[0], tsamp->loadavg[1],
			  tsamp->loadavg[2]);

    if(gs->length < 0) {
	reset_globalstat(gs);
	return;
    }

    update_max(gs);
}
Esempio n. 11
0
void Histogram::add(double value, int rank) {  
  assert(rank>=0);
  if(value < 0){
    if(value >= -DOUBLE_EPSILON){
      cout << "warning: negative double value " << value << " changed to 0.0f" << endl;
      value = 0.0f;
    } else {
      cerr << "error: rank " << my_rank << ", add a negative value " << value << " into histogram" << endl;
      cerr << toString() << endl;
      exit(0);
    }
  }

  if (num_elems == 0) {
    double bin_size = (value != 0.0) ? (2.0 * value)/num_bins : 1.0;

    for (int i=0; i < num_bins; i++) {
      HistoBin *bin = new HistoBin(i*bin_size, (i+1) * bin_size);
      bins.push_back(bin);
    }
  }

  num_elems++;

  // maintain min/max values.
  update_min(value, rank);
  update_max(value, rank);
  update_avg(value, 1);

  // put the value in the histogram
  int binIdx = find_bin(value);
  if(binIdx != -1){
    bins[binIdx]->add(value);
  } else {
    double tail_start = bins[num_bins-1]->getEnd();
    double tail_end = 2 * value - tail_start;
    /*if(tail_end < tail_start){
			cout << "tail_end: " << tail_end << endl;
			cout << "tail_start: " << tail_start << endl;
			cout << "value: " << value << endl;
			cout << toString() << endl;
			while(1);
		}*/
    assert(tail_end >= tail_start);
    HistoBin *tail = new HistoBin(tail_start, tail_end);
    tail->add(value);
    bins.push_back(tail);
    smooth();
  }

}
Esempio n. 12
0
level replace_level_fn::apply(level const & l) {
    optional<level> r = m_f(l);
    if (r)
        return *r;
    switch (l.kind()) {
    case level_kind::Succ:
        return update_succ(l, apply(succ_of(l)));
    case level_kind::Max: case level_kind::IMax:
        return update_max(l, apply(to_max_core(l).m_lhs), apply(to_max_core(l).m_rhs));
    case level_kind::Zero: case level_kind::Param: case level_kind::Meta: case level_kind::Global:
        return l;
    }
    lean_unreachable(); // LCOV_EXCL_LINE
}
Esempio n. 13
0
 level apply(level const & l) {
     auto r = m_lvl_cache.find(l);
     if (r != m_lvl_cache.end())
         return *r;
     level res;
     switch (l.kind()) {
     case level_kind::Zero:   case level_kind::Param:
     case level_kind::Global: case level_kind::Meta:
         res = l;
         break;
     case level_kind::Succ:
         res = update_succ(l, apply(succ_of(l)));
         break;
     case level_kind::Max:
         res = update_max(l, apply(max_lhs(l)), apply(max_rhs(l)));
         break;
     case level_kind::IMax:
         res = update_max(l, apply(imax_lhs(l)), apply(imax_rhs(l)));
         break;
     }
     m_lvl_cache.insert(res);
     return res;
 }
Esempio n. 14
0
static void update_processes(struct globalstat *gs, 
			     const libtop_tsamp_t *tsamp) {
    int i, offset, chunksize;

    gs->length = snprintf(gs->data, sizeof(gs->data), 
			  "Processes: %" PRIu32 " total, ",
			  (uint32_t)tsamp->nprocs);

    if(gs->length <= 0) {
	reset_globalstat(gs);
	return;
    }

    offset = gs->length;

    for (i = 0; i < LIBTOP_NSTATES; ++i) {
	if(tsamp->state_breakdown[i]) {
	    chunksize = snprintf(gs->data + offset,
				 sizeof(gs->data) - offset,
				 "%d %s, ",
				 tsamp->state_breakdown[i],
				 libtop_state_str(i));
	    if(chunksize < 0)
		break;
	    
	    offset += chunksize; 	
	}
    }

    gs->length = offset;
    
    chunksize = snprintf(gs->data + gs->length, 
			 sizeof(gs->data) - gs->length, 
			 "%" PRIu32 " threads ", tsamp->threads);
    
    if(chunksize < 0) {
	reset_globalstat(gs);
	return;
    }

    gs->length += chunksize;
    assert(gs->length <= sizeof(gs->data));

    update_max(gs);
}
Esempio n. 15
0
static void update_purgeable(struct globalstat *gs,
			const libtop_tsamp_t *tsamp) {
    struct top_uinteger purgeable_result, purges_result, prev_purges, 
	purges_delta;
    char purgeable[6];
    char purges[6];
    char pdelta[6];
    uint64_t purgeable_mem;

    if(!tsamp->purgeable_is_valid) {
	gs->length = snprintf(gs->data, sizeof(gs->data),
			      "Purgeable: N/A");

	if(gs->length < 0)
	    reset_globalstat(gs);

	return;
    }

    purgeable_mem = tsamp->vm_stat.purgeable_count * tsamp->pagesize;

    purgeable_result = top_init_uinteger(purgeable_mem, false);
    purges_result = top_init_uinteger(tsamp->vm_stat.purges, false);
    prev_purges = top_init_uinteger(tsamp->p_vm_stat.purges, false);
    purges_delta = top_sub_uinteger(&purges_result, &prev_purges);

    if(top_humanize_uinteger(purgeable, sizeof(purgeable), purgeable_result)
       || top_sprint_uinteger(purges, sizeof(purges), purges_result)
       || top_sprint_uinteger(pdelta, sizeof(pdelta), purges_delta)) {
	reset_globalstat(gs);
	return;
    }
    
    gs->length = snprintf(gs->data, sizeof(gs->data),
			  "Purgeable: %s %s(%s) pages purged.", 
			  purgeable, purges,
			  pdelta);

    if(gs->length < 0)
	reset_globalstat(gs);

    update_max(gs);
}
Esempio n. 16
0
static void update_physmem(struct globalstat *gs,
			   const libtop_tsamp_t *tsamp) {
    char wired[6];
    char used[6];
    char physfree[6];
    uint64_t total_free, total_used, total_used_count;
    struct top_uinteger wiredresult, usedresult,
	physfreeresult;
    
    total_free = (uint64_t)tsamp->vm_stat.free_count * tsamp->pagesize;
    total_used_count = (uint64_t)tsamp->vm_stat.wire_count + tsamp->vm_stat.inactive_count
			+ tsamp->vm_stat.active_count + tsamp->vm_stat.compressor_page_count;
    total_used = total_used_count * tsamp->pagesize;

    wiredresult = top_init_uinteger(tsamp->vm_stat.wire_count
				    * tsamp->pagesize, false);
    usedresult = top_init_uinteger(total_used, false);
    physfreeresult = top_init_uinteger(total_free, false);

    if(top_humanize_uinteger(wired, sizeof(wired), wiredresult)
       || top_humanize_uinteger(used, sizeof(used), usedresult)
       || top_humanize_uinteger(physfree, sizeof(physfree), physfreeresult)) {
	fprintf(stderr, "top_humanize_uinteger failure in %s\n", __func__);
	reset_globalstat(gs);
	return;
    }

    gs->length = snprintf(gs->data, sizeof(gs->data),
			  "PhysMem: "
			  "%s used (%s wired), "
			  "%s unused.",
			  used, wired,
			  physfree);

    if(gs->length < 0) {
	reset_globalstat(gs);
	return;
    }

    update_max(gs);
}
Esempio n. 17
0
static void update_time(struct globalstat *gs,
			const libtop_tsamp_t *tsamp) {
    struct timeval tval;
    struct tm tm;
    
    gettimeofday(&tval, NULL);
    localtime_r(&(tval.tv_sec), &tm);

    if(STATMODE_ACCUM == top_prefs_get_mode()) {
	unsigned int sec, min, hour;

	timersub(&tsamp->time, &tsamp->b_time, &tval);

	sec = tval.tv_sec;
	min = sec / 60;
	hour = min / 60;

	gs->length = snprintf(gs->data, sizeof(gs->data), "%u:%02u:%02u",
			      hour, min % 60, sec % 60);

	if(gs->length < 0) {
	    reset_globalstat(gs);
	    return;
	}
    } else if(top_prefs_get_logging_mode()) {
	gs->length = strftime(gs->data, sizeof(gs->data), "%Y/%m/%d %T", &tm);
    } else {
	gs->length = strftime(gs->data, sizeof(gs->data), "%T", &tm);
    }

    if(0 == gs->length) {
	reset_globalstat(gs);
	return;
    }

    update_max(gs);
}
Esempio n. 18
0
static void update_vm(struct globalstat *gs,
		      const libtop_tsamp_t *tsamp) {
    char vsize[6];
    char fwvsize[6];
    struct top_uinteger vsize_result, fw_vsize_result;

    vsize_result = top_init_uinteger(tsamp->vsize, false);
    fw_vsize_result = top_init_uinteger(tsamp->fw_vsize, false);

    if(top_humanize_uinteger(vsize, sizeof(vsize), vsize_result))
	return;

    if(top_humanize_uinteger(fwvsize, sizeof(fwvsize), fw_vsize_result))
	return;

    gs->length = snprintf(gs->data, sizeof(gs->data),
			  "VM: "
			  "%s vsize, "
			  "%s framework vsize, "
			  "%" PRIu64 "(%" PRIu64 ") swapins, "
			  "%" PRIu64 "(%" PRIu64 ") swapouts.",
			  vsize,
			  fwvsize,
			  (unsigned long long)tsamp->vm_stat.swapins,
			  (unsigned long long)(tsamp->vm_stat.swapins 
					       - tsamp->p_vm_stat.swapins),
			  (unsigned long long)tsamp->vm_stat.swapouts,
			  (unsigned long long)(tsamp->vm_stat.swapouts 
					       - tsamp->p_vm_stat.swapouts));

    if(gs->length < 0) {
	reset_globalstat(gs);
	return;
    }

    update_max(gs);
}
Esempio n. 19
0
/* Return true if an error occurred. */
static bool update_networks(struct globalstat *gs,
			    const libtop_tsamp_t *tsamp) {
    struct top_uinteger inp, outp, inbytes, outbytes;
    char inpbuf[GENERIC_INT_SIZE];
    char outpbuf[GENERIC_INT_SIZE];
    char inbytesbuf[6];
    char outbytesbuf[6];
 
    inp = top_init_uinteger(tsamp->net_ipackets, false);
    outp = top_init_uinteger(tsamp->net_opackets, false);

    inbytes = top_init_uinteger(tsamp->net_ibytes, false);
    outbytes = top_init_uinteger(tsamp->net_obytes, false);

    switch(top_prefs_get_mode()) {
    case STATMODE_ACCUM: {
	/* The changes that occurred since the beginning sample. */
	struct top_uinteger binp, boutp, binbytes, boutbytes;
	
	binp = top_init_uinteger(tsamp->b_net_ipackets, false);
	boutp = top_init_uinteger(tsamp->b_net_opackets, false);
	binbytes = top_init_uinteger(tsamp->b_net_ibytes, false);
	boutbytes = top_init_uinteger(tsamp->b_net_obytes, false);

	inp = top_sub_uinteger(&inp, &binp);
	outp = top_sub_uinteger(&outp, &boutp);
	
	inbytes = top_sub_uinteger(&inbytes, &binbytes);
	outbytes = top_sub_uinteger(&outbytes, &boutbytes);
    }
	break;

    case STATMODE_DELTA: {
	/* The changes that occurred since the previous sample. */ 
	struct top_uinteger pinp, poutp, pinbytes, poutbytes;

	pinp = top_init_uinteger(tsamp->p_net_ipackets, false);
	poutp = top_init_uinteger(tsamp->p_net_opackets, false);
	pinbytes = top_init_uinteger(tsamp->p_net_ibytes, false);
	poutbytes = top_init_uinteger(tsamp->p_net_obytes, false);

	inp = top_sub_uinteger(&inp, &pinp);
	outp = top_sub_uinteger(&outp, &poutp);
	
	inbytes = top_sub_uinteger(&inbytes, &pinbytes);
	outbytes = top_sub_uinteger(&outbytes, &poutbytes);
    }
	break;
    }

    if(top_sprint_uinteger(inpbuf, sizeof(inpbuf), inp))
	return true;

    if(top_sprint_uinteger(outpbuf, sizeof(outpbuf), outp))
	return true;

    if(top_humanize_uinteger(inbytesbuf, sizeof(inbytesbuf), inbytes))
	return true;

    if(top_humanize_uinteger(outbytesbuf, sizeof(outbytesbuf), outbytes))
	return true;

    gs->length = snprintf(gs->data, sizeof(gs->data),
			  "Networks: "
			  "packets: "
			  "%s/%s in, "
			  "%s/%s out.",
			  inpbuf, inbytesbuf,
			  outpbuf, outbytesbuf);
    if(-1 == gs->length) {
	reset_globalstat(gs);
	return true;
    }

    update_max(gs);
    
    return false;
}
Esempio n. 20
0
    ErrorCode BoundBox::update(Interface &iface, const Range& elems)
    {
      ErrorCode rval;
      bMin = CartVect(HUGE_VAL);
      bMax = CartVect(-HUGE_VAL);
      
      CartVect coords;
      EntityHandle const *conn, *conn2;
      int len, len2;
      Range::const_iterator i;
  
        // vertices
      const Range::const_iterator elem_begin = elems.lower_bound( MBEDGE );
      for (i = elems.begin(); i != elem_begin; ++i) {
        rval = iface.get_coords( &*i, 1, coords.array() );
        if (MB_SUCCESS != rval)
          return rval;
        update_min(coords.array());
        update_max(coords.array());
      }

        // elements with vertex-handle connectivity list
      const Range::const_iterator poly_begin = elems.lower_bound( MBPOLYHEDRON, elem_begin );
      std::vector<EntityHandle> dum_vector;
      for (i = elem_begin; i != poly_begin; ++i) {
        rval = iface.get_connectivity( *i, conn, len, true, &dum_vector);
        if (MB_SUCCESS != rval)
          return rval;

        for (int j = 0; j < len; ++j) {
          rval = iface.get_coords( conn+j, 1, coords.array() );
          if (MB_SUCCESS != rval)
            return rval;
          update_min(coords.array());
          update_max(coords.array());
        }
      }
  
        // polyhedra
      const Range::const_iterator set_begin  = elems.lower_bound( MBENTITYSET, poly_begin );
      for (i = poly_begin; i != set_begin; ++i) {
        rval = iface.get_connectivity( *i, conn, len, true );
        if (MB_SUCCESS != rval)
          return rval;

        for (int j = 0; j < len; ++j) {
          rval = iface.get_connectivity( conn[j], conn2, len2 );
          for (int k = 0; k < len2; ++k) {
            rval = iface.get_coords( conn2+k, 1, coords.array() );
            if (MB_SUCCESS != rval)
              return rval;
            update_min(coords.array());
            update_max(coords.array());
          }
        }
      }
  
        // sets
      BoundBox box;
      for (i = set_begin; i != elems.end(); ++i) {
        Range tmp_elems;
        rval = iface.get_entities_by_handle(*i, tmp_elems);
        if (MB_SUCCESS != rval) return rval;
        rval = box.update(iface, tmp_elems);
        if (MB_SUCCESS != rval) return rval;

        update(box);
      }
  
      return MB_SUCCESS;
    }
Esempio n. 21
0
unsigned long smbios_write_tables(unsigned long current)
{
	struct smbios_entry *se;
	unsigned long tables;
	int len = 0;
	int max_struct_size = 0;
	int handle = 0;

	current = ALIGN(current, 16);
	printk(BIOS_DEBUG, "%s: %08lx\n", __func__, current);

	se = (struct smbios_entry *)current;
	current += sizeof(struct smbios_entry);
	current = ALIGN(current, 16);

	tables = current;
	update_max(len, max_struct_size, smbios_write_type0(&current, handle++));
	update_max(len, max_struct_size, smbios_write_type1(&current, handle++));
	update_max(len, max_struct_size, smbios_write_type2(&current, handle++));
	update_max(len, max_struct_size, smbios_write_type3(&current, handle++));
	update_max(len, max_struct_size, smbios_write_type4(&current, handle++));
	update_max(len, max_struct_size, smbios_write_type11(&current, &handle));
#if CONFIG_ELOG
	update_max(len, max_struct_size, elog_smbios_write_type15(&current, handle++));
#endif
	update_max(len, max_struct_size, smbios_write_type17(&current, &handle));
	update_max(len, max_struct_size, smbios_write_type32(&current, handle++));

	update_max(len, max_struct_size, smbios_walk_device_tree(all_devices, &handle, &current));

	update_max(len, max_struct_size, smbios_write_type127(&current, handle++));

	memset(se, 0, sizeof(struct smbios_entry));
	memcpy(se->anchor, "_SM_", 4);
	se->length = sizeof(struct smbios_entry);
	se->major_version = 2;
	se->minor_version = 7;
	se->max_struct_size = max_struct_size;
	se->struct_count = handle;
	memcpy(se->intermediate_anchor_string, "_DMI_", 5);

	se->struct_table_address = (u32)tables;
	se->struct_table_length = len;

	se->intermediate_checksum = smbios_checksum((u8 *)se + 0x10,
						    sizeof(struct smbios_entry) - 0x10);
	se->checksum = smbios_checksum((u8 *)se, sizeof(struct smbios_entry));
	return current;
}
Esempio n. 22
0
int main(int argc, char *argv[])
{

    FILE *in_fp;
    int out_fd;
    char *infile, *outmap;
    int xcol, ycol, zcol, max_col, percent;
    int do_zfilter;
    int method = -1;
    int bin_n, bin_min, bin_max, bin_sum, bin_sumsq, bin_index;
    double zrange_min, zrange_max, d_tmp;
    char *fs;			/* field delim */
    off_t filesize;
    int linesize;
    long estimated_lines;
    int from_stdin;
    int can_seek;

    RASTER_MAP_TYPE rtype;
    struct History history;
    char title[64];
    void *n_array, *min_array, *max_array, *sum_array, *sumsq_array,
	*index_array;
    void *raster_row, *ptr;
    struct Cell_head region;
    int rows, cols;		/* scan box size */
    int row, col;		/* counters */

    int pass, npasses;
    unsigned long line;
    char buff[BUFFSIZE];
    double x, y, z;
    char **tokens;
    int ntokens;		/* number of tokens */
    double pass_north, pass_south;
    int arr_row, arr_col;
    unsigned long count, count_total;

    double min = 0.0 / 0.0;	/* init as nan */
    double max = 0.0 / 0.0;	/* init as nan */
    double zscale = 1.0;
    size_t offset, n_offset;
    int n = 0;
    double sum = 0.;
    double sumsq = 0.;
    double variance, mean, skew, sumdev;
    int pth = 0;
    double trim = 0.0;

    int j, k;
    int head_id, node_id;
    int r_low, r_up;

    struct GModule *module;
    struct Option *input_opt, *output_opt, *delim_opt, *percent_opt,
	*type_opt;
    struct Option *method_opt, *xcol_opt, *ycol_opt, *zcol_opt, *zrange_opt,
	*zscale_opt;
    struct Option *trim_opt, *pth_opt;
    struct Flag *scan_flag, *shell_style, *skipline;


    G_gisinit(argv[0]);

    module = G_define_module();
    module->keywords = _("raster, import, LIDAR");
    module->description =
	_("Create a raster map from an assemblage of many coordinates using univariate statistics.");

    input_opt = G_define_standard_option(G_OPT_F_INPUT);
    input_opt->description =
	_("ASCII file containing input data (or \"-\" to read from stdin)");

    output_opt = G_define_standard_option(G_OPT_R_OUTPUT);

    method_opt = G_define_option();
    method_opt->key = "method";
    method_opt->type = TYPE_STRING;
    method_opt->required = NO;
    method_opt->description = _("Statistic to use for raster values");
    method_opt->options =
	"n,min,max,range,sum,mean,stddev,variance,coeff_var,median,percentile,skewness,trimmean";
    method_opt->answer = "mean";
    method_opt->guisection = _("Statistic");

    type_opt = G_define_option();
    type_opt->key = "type";
    type_opt->type = TYPE_STRING;
    type_opt->required = NO;
    type_opt->options = "CELL,FCELL,DCELL";
    type_opt->answer = "FCELL";
    type_opt->description = _("Storage type for resultant raster map");

    delim_opt = G_define_standard_option(G_OPT_F_SEP);
    delim_opt->guisection = _("Input");

    xcol_opt = G_define_option();
    xcol_opt->key = "x";
    xcol_opt->type = TYPE_INTEGER;
    xcol_opt->required = NO;
    xcol_opt->answer = "1";
    xcol_opt->description =
	_("Column number of x coordinates in input file (first column is 1)");
    xcol_opt->guisection = _("Input");

    ycol_opt = G_define_option();
    ycol_opt->key = "y";
    ycol_opt->type = TYPE_INTEGER;
    ycol_opt->required = NO;
    ycol_opt->answer = "2";
    ycol_opt->description = _("Column number of y coordinates in input file");
    ycol_opt->guisection = _("Input");

    zcol_opt = G_define_option();
    zcol_opt->key = "z";
    zcol_opt->type = TYPE_INTEGER;
    zcol_opt->required = NO;
    zcol_opt->answer = "3";
    zcol_opt->description = _("Column number of data values in input file");
    zcol_opt->guisection = _("Input");

    zrange_opt = G_define_option();
    zrange_opt->key = "zrange";
    zrange_opt->type = TYPE_DOUBLE;
    zrange_opt->required = NO;
    zrange_opt->key_desc = "min,max";
    zrange_opt->description = _("Filter range for z data (min,max)");

    zscale_opt = G_define_option();
    zscale_opt->key = "zscale";
    zscale_opt->type = TYPE_DOUBLE;
    zscale_opt->required = NO;
    zscale_opt->answer = "1.0";
    zscale_opt->description = _("Scale to apply to z data");

    percent_opt = G_define_option();
    percent_opt->key = "percent";
    percent_opt->type = TYPE_INTEGER;
    percent_opt->required = NO;
    percent_opt->answer = "100";
    percent_opt->options = "1-100";
    percent_opt->description = _("Percent of map to keep in memory");

    pth_opt = G_define_option();
    pth_opt->key = "pth";
    pth_opt->type = TYPE_INTEGER;
    pth_opt->required = NO;
    pth_opt->options = "1-100";
    pth_opt->description = _("pth percentile of the values");
    pth_opt->guisection = _("Statistic");

    trim_opt = G_define_option();
    trim_opt->key = "trim";
    trim_opt->type = TYPE_DOUBLE;
    trim_opt->required = NO;
    trim_opt->options = "0-50";
    trim_opt->description =
	_("Discard <trim> percent of the smallest and <trim> percent of the largest observations");
    trim_opt->guisection = _("Statistic");

    scan_flag = G_define_flag();
    scan_flag->key = 's';
    scan_flag->description = _("Scan data file for extent then exit");

    shell_style = G_define_flag();
    shell_style->key = 'g';
    shell_style->description =
	_("In scan mode, print using shell script style");

    skipline = G_define_flag();
    skipline->key = 'i';
    skipline->description = _("Ignore broken lines");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);


    /* parse input values */
    infile = input_opt->answer;
    outmap = output_opt->answer;

    if (shell_style->answer && !scan_flag->answer) {
	scan_flag->answer = 1;
    }

    fs = delim_opt->answer;
    if (strcmp(fs, "\\t") == 0)
	fs = "\t";
    if (strcmp(fs, "tab") == 0)
	fs = "\t";
    if (strcmp(fs, "space") == 0)
	fs = " ";

    xcol = atoi(xcol_opt->answer);
    ycol = atoi(ycol_opt->answer);
    zcol = atoi(zcol_opt->answer);
    if ((xcol < 0) || (ycol < 0) || (zcol < 0))
	G_fatal_error(_("Please specify a reasonable column number."));
    max_col = (xcol > ycol) ? xcol : ycol;
    max_col = (zcol > max_col) ? zcol : max_col;

    percent = atoi(percent_opt->answer);
    zscale = atof(zscale_opt->answer);

    /* parse zrange */
    do_zfilter = FALSE;
    if (zrange_opt->answer != NULL) {
	if (zrange_opt->answers[0] == NULL)
	    G_fatal_error(_("Invalid zrange"));

	sscanf(zrange_opt->answers[0], "%lf", &zrange_min);
	sscanf(zrange_opt->answers[1], "%lf", &zrange_max);
	do_zfilter = TRUE;

	if (zrange_min > zrange_max) {
	    d_tmp = zrange_max;
	    zrange_max = zrange_min;
	    zrange_min = d_tmp;
	}
    }

    /* figure out what maps we need in memory */
    /*  n               n
       min              min
       max              max
       range            min max         max - min
       sum              sum
       mean             sum n           sum/n
       stddev           sum sumsq n     sqrt((sumsq - sum*sum/n)/n)
       variance         sum sumsq n     (sumsq - sum*sum/n)/n
       coeff_var        sum sumsq n     sqrt((sumsq - sum*sum/n)/n) / (sum/n)
       median           n               array index to linked list
       percentile       n               array index to linked list
       skewness         n               array index to linked list
       trimmean         n               array index to linked list
     */
    bin_n = FALSE;
    bin_min = FALSE;
    bin_max = FALSE;
    bin_sum = FALSE;
    bin_sumsq = FALSE;
    bin_index = FALSE;

    if (strcmp(method_opt->answer, "n") == 0) {
	method = METHOD_N;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "min") == 0) {
	method = METHOD_MIN;
	bin_min = TRUE;
    }
    if (strcmp(method_opt->answer, "max") == 0) {
	method = METHOD_MAX;
	bin_max = TRUE;
    }
    if (strcmp(method_opt->answer, "range") == 0) {
	method = METHOD_RANGE;
	bin_min = TRUE;
	bin_max = TRUE;
    }
    if (strcmp(method_opt->answer, "sum") == 0) {
	method = METHOD_SUM;
	bin_sum = TRUE;
    }
    if (strcmp(method_opt->answer, "mean") == 0) {
	method = METHOD_MEAN;
	bin_sum = TRUE;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "stddev") == 0) {
	method = METHOD_STDDEV;
	bin_sum = TRUE;
	bin_sumsq = TRUE;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "variance") == 0) {
	method = METHOD_VARIANCE;
	bin_sum = TRUE;
	bin_sumsq = TRUE;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "coeff_var") == 0) {
	method = METHOD_COEFF_VAR;
	bin_sum = TRUE;
	bin_sumsq = TRUE;
	bin_n = TRUE;
    }
    if (strcmp(method_opt->answer, "median") == 0) {
	method = METHOD_MEDIAN;
	bin_index = TRUE;
    }
    if (strcmp(method_opt->answer, "percentile") == 0) {
	if (pth_opt->answer != NULL)
	    pth = atoi(pth_opt->answer);
	else
	    G_fatal_error(_("Unable to calculate percentile without the pth option specified!"));
	method = METHOD_PERCENTILE;
	bin_index = TRUE;
    }
    if (strcmp(method_opt->answer, "skewness") == 0) {
	method = METHOD_SKEWNESS;
	bin_index = TRUE;
    }
    if (strcmp(method_opt->answer, "trimmean") == 0) {
	if (trim_opt->answer != NULL)
	    trim = atof(trim_opt->answer) / 100.0;
	else
	    G_fatal_error(_("Unable to calculate trimmed mean without the trim option specified!"));
	method = METHOD_TRIMMEAN;
	bin_index = TRUE;
    }

    if (strcmp("CELL", type_opt->answer) == 0)
	rtype = CELL_TYPE;
    else if (strcmp("DCELL", type_opt->answer) == 0)
	rtype = DCELL_TYPE;
    else
	rtype = FCELL_TYPE;

    if (method == METHOD_N)
	rtype = CELL_TYPE;


    G_get_window(&region);
    rows = (int)(region.rows * (percent / 100.0));
    cols = region.cols;

    G_debug(2, "region.n=%f  region.s=%f  region.ns_res=%f", region.north,
	    region.south, region.ns_res);
    G_debug(2, "region.rows=%d  [box_rows=%d]  region.cols=%d", region.rows,
	    rows, region.cols);

    npasses = (int)ceil(1.0 * region.rows / rows);

    if (!scan_flag->answer) {
	/* allocate memory (test for enough before we start) */
	if (bin_n)
	    n_array = G_calloc(rows * (cols + 1), G_raster_size(CELL_TYPE));
	if (bin_min)
	    min_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	if (bin_max)
	    max_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	if (bin_sum)
	    sum_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	if (bin_sumsq)
	    sumsq_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	if (bin_index)
	    index_array =
		G_calloc(rows * (cols + 1), G_raster_size(CELL_TYPE));

	/* and then free it again */
	if (bin_n)
	    G_free(n_array);
	if (bin_min)
	    G_free(min_array);
	if (bin_max)
	    G_free(max_array);
	if (bin_sum)
	    G_free(sum_array);
	if (bin_sumsq)
	    G_free(sumsq_array);
	if (bin_index)
	    G_free(index_array);

	/** end memory test **/
    }


    /* open input file */
    if (strcmp("-", infile) == 0) {
	from_stdin = TRUE;
	in_fp = stdin;
	infile = G_store("stdin");	/* filename for history metadata */
    }
    else {
	if ((in_fp = fopen(infile, "r")) == NULL)
	    G_fatal_error(_("Unable to open input file <%s>"), infile);
    }

    can_seek = fseek(in_fp, 0, SEEK_SET) == 0;

    /* can't rewind() non-files */
    if (!can_seek && npasses != 1) {
	G_warning(_("If input is not from a file it is only possible to perform a single pass."));
	npasses = 1;
    }

    if (scan_flag->answer) {
	if (zrange_opt->answer)
	    G_warning(_("zrange will not be taken into account during scan"));

	scan_bounds(in_fp, xcol, ycol, zcol, fs, shell_style->answer,
		    skipline->answer, zscale);

	if (!from_stdin)
	    fclose(in_fp);

	exit(EXIT_SUCCESS);
    }


    /* open output map */
    out_fd = G_open_raster_new(outmap, rtype);
    if (out_fd < 0)
	G_fatal_error(_("Unable to create raster map <%s>"), outmap);

    if (can_seek) {
	/* guess at number of lines in the file without actually reading it all in */
	for (line = 0; line < 10; line++) {	/* arbitrarily use 10th line for guess */
	    if (0 == G_getl2(buff, BUFFSIZE - 1, in_fp))
		break;
	    linesize = strlen(buff) + 1;
	}
	fseek(in_fp, 0L, SEEK_END);
	filesize = ftell(in_fp);
	rewind(in_fp);
	if (linesize < 6)	/* min possible: "0,0,0\n" */
	    linesize = 6;
	estimated_lines = filesize / linesize;
	G_debug(2, "estimated number of lines in file: %ld", estimated_lines);
    }
    else
	estimated_lines = -1;

    /* allocate memory for a single row of output data */
    raster_row = G_allocate_raster_buf(rtype);

    G_message(_("Reading data ..."));

    count_total = 0;

    /* main binning loop(s) */
    for (pass = 1; pass <= npasses; pass++) {
	if (npasses > 1)
	    G_message(_("Pass #%d (of %d) ..."), pass, npasses);

	if (can_seek)
	    rewind(in_fp);

	/* figure out segmentation */
	pass_north = region.north - (pass - 1) * rows * region.ns_res;
	if (pass == npasses)
	    rows = region.rows - (pass - 1) * rows;
	pass_south = pass_north - rows * region.ns_res;

	G_debug(2, "pass=%d/%d  pass_n=%f  pass_s=%f  rows=%d",
		pass, npasses, pass_north, pass_south, rows);


	if (bin_n) {
	    G_debug(2, "allocating n_array");
	    n_array = G_calloc(rows * (cols + 1), G_raster_size(CELL_TYPE));
	    blank_array(n_array, rows, cols, CELL_TYPE, 0);
	}
	if (bin_min) {
	    G_debug(2, "allocating min_array");
	    min_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	    blank_array(min_array, rows, cols, rtype, -1);	/* fill with NULLs */
	}
	if (bin_max) {
	    G_debug(2, "allocating max_array");
	    max_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	    blank_array(max_array, rows, cols, rtype, -1);	/* fill with NULLs */
	}
	if (bin_sum) {
	    G_debug(2, "allocating sum_array");
	    sum_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	    blank_array(sum_array, rows, cols, rtype, 0);
	}
	if (bin_sumsq) {
	    G_debug(2, "allocating sumsq_array");
	    sumsq_array = G_calloc(rows * (cols + 1), G_raster_size(rtype));
	    blank_array(sumsq_array, rows, cols, rtype, 0);
	}
	if (bin_index) {
	    G_debug(2, "allocating index_array");
	    index_array =
		G_calloc(rows * (cols + 1), G_raster_size(CELL_TYPE));
	    blank_array(index_array, rows, cols, CELL_TYPE, -1);	/* fill with NULLs */
	}

	line = 0;
	count = 0;
	G_percent_reset();

	while (0 != G_getl2(buff, BUFFSIZE - 1, in_fp)) {
	    line++;

	    if (line % 10000 == 0) {	/* mod for speed */
		if (!can_seek)
		    G_clicker();
		else if (line < estimated_lines)
		    G_percent(line, estimated_lines, 3);
	    }

	    if ((buff[0] == '#') || (buff[0] == '\0')) {
		continue;	/* line is a comment or blank */
	    }

	    G_chop(buff);	/* remove leading and trailing whitespace from the string.  unneded?? */
	    tokens = G_tokenize(buff, fs);
	    ntokens = G_number_of_tokens(tokens);

	    if ((ntokens < 3) || (max_col > ntokens)) {
		if (skipline->answer) {
		    G_warning(_("Not enough data columns. "
				"Incorrect delimiter or column number? "
				"Found the following character(s) in row %lu:\n[%s]"),
			      line, buff);
		    G_warning(_("Line ignored as requested"));
		    continue;	/* line is garbage */
		}
		else {
		    G_fatal_error(_("Not enough data columns. "
				    "Incorrect delimiter or column number? "
				    "Found the following character(s) in row %lu:\n[%s]"),
				  line, buff);
		}
	    }

	    /* too slow?
	       if ( G_projection() == PROJECTION_LL ) {
	       G_scan_easting( tokens[xcol-1], &x, region.proj);
	       G_scan_northing( tokens[ycol-1], &y, region.proj);
	       }
	       else {
	     */
	    if (1 != sscanf(tokens[ycol - 1], "%lf", &y))
		G_fatal_error(_("Bad y-coordinate line %lu column %d. <%s>"),
			      line, ycol, tokens[ycol - 1]);
	    if (y <= pass_south || y > pass_north) {
		G_free_tokens(tokens);
		continue;
	    }
	    if (1 != sscanf(tokens[xcol - 1], "%lf", &x))
		G_fatal_error(_("Bad x-coordinate line %lu column %d. <%s>"),
			      line, xcol, tokens[xcol - 1]);
	    if (x < region.west || x > region.east) {
		G_free_tokens(tokens);
		continue;
	    }
	    if (1 != sscanf(tokens[zcol - 1], "%lf", &z))
		G_fatal_error(_("Bad z-coordinate line %lu column %d. <%s>"),
			      line, zcol, tokens[zcol - 1]);

	    z = z * zscale;

	    if (zrange_opt->answer) {
		if (z < zrange_min || z > zrange_max) {
		    G_free_tokens(tokens);
		    continue;
		}
	    }

	    count++;
	    /*          G_debug(5, "x: %f, y: %f, z: %f", x, y, z); */
	    G_free_tokens(tokens);

	    /* find the bin in the current array box */
	    arr_row = (int)((pass_north - y) / region.ns_res);
	    arr_col = (int)((x - region.west) / region.ew_res);

	    /*          G_debug(5, "arr_row: %d   arr_col: %d", arr_row, arr_col); */

	    /* The range should be [0,cols-1]. We use (int) to round down,
	       but if the point exactly on eastern edge arr_col will be /just/
	       on the max edge .0000000 and end up on the next row.
	       We could make above bounds check "if(x>=region.east) continue;"
	       But instead we go to all sorts of trouble so that not one single
	       data point is lost. GE is too small to catch them all.
	       We don't try to make y happy as percent segmenting will make some
	       points happen twice that way; so instead we use the y<= test above.
	     */
	    if (arr_col >= cols) {
		if (((x - region.west) / region.ew_res) - cols <
		    10 * GRASS_EPSILON)
		    arr_col--;
		else {		/* oh well, we tried. */
		    G_debug(3,
			    "skipping extraneous data point [%.3f], column %d of %d",
			    x, arr_col, cols);
		    continue;
		}
	    }

	    if (bin_n)
		update_n(n_array, cols, arr_row, arr_col);
	    if (bin_min)
		update_min(min_array, cols, arr_row, arr_col, rtype, z);
	    if (bin_max)
		update_max(max_array, cols, arr_row, arr_col, rtype, z);
	    if (bin_sum)
		update_sum(sum_array, cols, arr_row, arr_col, rtype, z);
	    if (bin_sumsq)
		update_sumsq(sumsq_array, cols, arr_row, arr_col, rtype, z);
	    if (bin_index) {
		ptr = index_array;
		ptr =
		    G_incr_void_ptr(ptr,
				    ((arr_row * cols) +
				     arr_col) * G_raster_size(CELL_TYPE));

		if (G_is_null_value(ptr, CELL_TYPE)) {	/* first node */
		    head_id = new_node();
		    nodes[head_id].next = -1;
		    nodes[head_id].z = z;
		    G_set_raster_value_c(ptr, head_id, CELL_TYPE);	/* store index to head */
		}
		else {		/* head is already there */

		    head_id = G_get_raster_value_c(ptr, CELL_TYPE);	/* get index to head */
		    head_id = add_node(head_id, z);
		    if (head_id != -1)
			G_set_raster_value_c(ptr, head_id, CELL_TYPE);	/* store index to head */
		}
	    }
	}			/* while !EOF */

	G_percent(1, 1, 1);	/* flush */
	G_debug(2, "pass %d finished, %lu coordinates in box", pass, count);
	count_total += count;


	/* calc stats and output */
	G_message(_("Writing to map ..."));
	for (row = 0; row < rows; row++) {

	    switch (method) {
	    case METHOD_N:	/* n is a straight copy */
		G_raster_cpy(raster_row,
			     n_array +
			     (row * cols * G_raster_size(CELL_TYPE)), cols,
			     CELL_TYPE);
		break;

	    case METHOD_MIN:
		G_raster_cpy(raster_row,
			     min_array + (row * cols * G_raster_size(rtype)),
			     cols, rtype);
		break;

	    case METHOD_MAX:
		G_raster_cpy(raster_row,
			     max_array + (row * cols * G_raster_size(rtype)),
			     cols, rtype);
		break;

	    case METHOD_SUM:
		G_raster_cpy(raster_row,
			     sum_array + (row * cols * G_raster_size(rtype)),
			     cols, rtype);
		break;

	    case METHOD_RANGE:	/* (max-min) */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    offset = (row * cols + col) * G_raster_size(rtype);
		    min = G_get_raster_value_d(min_array + offset, rtype);
		    max = G_get_raster_value_d(max_array + offset, rtype);
		    G_set_raster_value_d(ptr, max - min, rtype);
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;

	    case METHOD_MEAN:	/* (sum / n) */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    offset = (row * cols + col) * G_raster_size(rtype);
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    n = G_get_raster_value_c(n_array + n_offset, CELL_TYPE);
		    sum = G_get_raster_value_d(sum_array + offset, rtype);

		    if (n == 0)
			G_set_null_value(ptr, 1, rtype);
		    else
			G_set_raster_value_d(ptr, (sum / n), rtype);

		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;

	    case METHOD_STDDEV:	/*  sqrt(variance)        */
	    case METHOD_VARIANCE:	/*  (sumsq - sum*sum/n)/n */
	    case METHOD_COEFF_VAR:	/*  100 * stdev / mean    */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    offset = (row * cols + col) * G_raster_size(rtype);
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    n = G_get_raster_value_c(n_array + n_offset, CELL_TYPE);
		    sum = G_get_raster_value_d(sum_array + offset, rtype);
		    sumsq = G_get_raster_value_d(sumsq_array + offset, rtype);

		    if (n == 0)
			G_set_null_value(ptr, 1, rtype);
		    else {
			variance = (sumsq - sum * sum / n) / n;
			if (variance < GRASS_EPSILON)
			    variance = 0.0;

			if (method == METHOD_STDDEV)
			    G_set_raster_value_d(ptr, sqrt(variance), rtype);

			else if (method == METHOD_VARIANCE)
			    G_set_raster_value_d(ptr, variance, rtype);

			else if (method == METHOD_COEFF_VAR)
			    G_set_raster_value_d(ptr,
						 100 * sqrt(variance) / (sum /
									 n),
						 rtype);

		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;
	    case METHOD_MEDIAN:	/* median, if only one point in cell we will use that */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    if (G_is_null_value(index_array + n_offset, CELL_TYPE))	/* no points in cell */
			G_set_null_value(ptr, 1, rtype);
		    else {	/* one or more points in cell */

			head_id =
			    G_get_raster_value_c(index_array + n_offset,
						 CELL_TYPE);
			node_id = head_id;

			n = 0;

			while (node_id != -1) {	/* count number of points in cell */
			    n++;
			    node_id = nodes[node_id].next;
			}

			if (n == 1)	/* only one point, use that */
			    G_set_raster_value_d(ptr, nodes[head_id].z,
						 rtype);
			else if (n % 2 != 0) {	/* odd number of points: median_i = (n + 1) / 2 */
			    n = (n + 1) / 2;
			    node_id = head_id;
			    for (j = 1; j < n; j++)	/* get "median element" */
				node_id = nodes[node_id].next;

			    G_set_raster_value_d(ptr, nodes[node_id].z,
						 rtype);
			}
			else {	/* even number of points: median = (val_below + val_above) / 2 */

			    z = (n + 1) / 2.0;
			    n = floor(z);
			    node_id = head_id;
			    for (j = 1; j < n; j++)	/* get element "below" */
				node_id = nodes[node_id].next;

			    z = (nodes[node_id].z +
				 nodes[nodes[node_id].next].z) / 2;
			    G_set_raster_value_d(ptr, z, rtype);
			}
		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;
	    case METHOD_PERCENTILE:	/* rank = (pth*(n+1))/100; interpolate linearly */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    if (G_is_null_value(index_array + n_offset, CELL_TYPE))	/* no points in cell */
			G_set_null_value(ptr, 1, rtype);
		    else {
			head_id =
			    G_get_raster_value_c(index_array + n_offset,
						 CELL_TYPE);
			node_id = head_id;
			n = 0;

			while (node_id != -1) {	/* count number of points in cell */
			    n++;
			    node_id = nodes[node_id].next;
			}

			z = (pth * (n + 1)) / 100.0;
			r_low = floor(z);	/* lower rank */
			if (r_low < 1)
			    r_low = 1;
			else if (r_low > n)
			    r_low = n;

			r_up = ceil(z);	/* upper rank */
			if (r_up > n)
			    r_up = n;

			node_id = head_id;
			for (j = 1; j < r_low; j++)	/* search lower value */
			    node_id = nodes[node_id].next;

			z = nodes[node_id].z;	/* save lower value */
			node_id = head_id;
			for (j = 1; j < r_up; j++)	/* search upper value */
			    node_id = nodes[node_id].next;

			z = (z + nodes[node_id].z) / 2;
			G_set_raster_value_d(ptr, z, rtype);
		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;
	    case METHOD_SKEWNESS:	/* skewness = sum(xi-mean)^3/(N-1)*s^3 */
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    if (G_is_null_value(index_array + n_offset, CELL_TYPE))	/* no points in cell */
			G_set_null_value(ptr, 1, rtype);
		    else {
			head_id =
			    G_get_raster_value_c(index_array + n_offset,
						 CELL_TYPE);
			node_id = head_id;

			n = 0;	/* count */
			sum = 0.0;	/* sum */
			sumsq = 0.0;	/* sum of squares */
			sumdev = 0.0;	/* sum of (xi - mean)^3 */
			skew = 0.0;	/* skewness */

			while (node_id != -1) {
			    z = nodes[node_id].z;
			    n++;
			    sum += z;
			    sumsq += (z * z);
			    node_id = nodes[node_id].next;
			}

			if (n > 1) {	/* if n == 1, skew is "0.0" */
			    mean = sum / n;
			    node_id = head_id;
			    while (node_id != -1) {
				z = nodes[node_id].z;
				sumdev += pow((z - mean), 3);
				node_id = nodes[node_id].next;
			    }

			    variance = (sumsq - sum * sum / n) / n;
			    if (variance < GRASS_EPSILON)
				skew = 0.0;
			    else
				skew =
				    sumdev / ((n - 1) *
					      pow(sqrt(variance), 3));
			}
			G_set_raster_value_d(ptr, skew, rtype);
		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;
	    case METHOD_TRIMMEAN:
		ptr = raster_row;
		for (col = 0; col < cols; col++) {
		    n_offset = (row * cols + col) * G_raster_size(CELL_TYPE);
		    if (G_is_null_value(index_array + n_offset, CELL_TYPE))	/* no points in cell */
			G_set_null_value(ptr, 1, rtype);
		    else {
			head_id =
			    G_get_raster_value_c(index_array + n_offset,
						 CELL_TYPE);

			node_id = head_id;
			n = 0;
			while (node_id != -1) {	/* count number of points in cell */
			    n++;
			    node_id = nodes[node_id].next;
			}

			if (1 == n)
			    mean = nodes[head_id].z;
			else {
			    k = floor(trim * n + 0.5);	/* number of ranks to discard on each tail */

			    if (k > 0 && (n - 2 * k) > 0) {	/* enough elements to discard */
				node_id = head_id;
				for (j = 0; j < k; j++)	/* move to first rank to consider */
				    node_id = nodes[node_id].next;

				j = k + 1;
				k = n - k;
				n = 0;
				sum = 0.0;

				while (j <= k) {	/* get values in interval */
				    n++;
				    sum += nodes[node_id].z;
				    node_id = nodes[node_id].next;
				    j++;
				}
			    }
			    else {
				node_id = head_id;
				n = 0;
				sum = 0.0;
				while (node_id != -1) {
				    n++;
				    sum += nodes[node_id].z;
				    node_id = nodes[node_id].next;
				}
			    }
			    mean = sum / n;
			}
			G_set_raster_value_d(ptr, mean, rtype);
		    }
		    ptr = G_incr_void_ptr(ptr, G_raster_size(rtype));
		}
		break;

	    default:
		G_fatal_error("?");
	    }

	    /* write out line of raster data */
	    if (1 != G_put_raster_row(out_fd, raster_row, rtype)) {
		G_close_cell(out_fd);
		G_fatal_error(_("Writing map, row %d"),
			      ((pass - 1) * rows) + row);
	    }
	}

	/* free memory */
	if (bin_n)
	    G_free(n_array);
	if (bin_min)
	    G_free(min_array);
	if (bin_max)
	    G_free(max_array);
	if (bin_sum)
	    G_free(sum_array);
	if (bin_sumsq)
	    G_free(sumsq_array);
	if (bin_index) {
	    G_free(index_array);
	    G_free(nodes);
	    num_nodes = 0;
	    max_nodes = 0;
	    nodes = NULL;
	}

    }				/* passes loop */

    G_percent(1, 1, 1);		/* flush */
    G_free(raster_row);

    /* close input file */
    if (!from_stdin)
	fclose(in_fp);

    /* close raster file & write history */
    G_close_cell(out_fd);

    sprintf(title, "Raw x,y,z data binned into a raster grid by cell %s",
	    method_opt->answer);
    G_put_cell_title(outmap, title);

    G_short_history(outmap, "raster", &history);
    G_command_history(&history);
    strncpy(history.datsrc_1, infile, RECORD_LEN);
    history.datsrc_1[RECORD_LEN - 1] = '\0';	/* strncpy() doesn't null terminate if maxfill */
    G_write_history(outmap, &history);


    sprintf(buff, _("%lu points found in region."), count_total);
    G_done_msg(buff);
    G_debug(1, "Processed %lu lines.", line);

    exit(EXIT_SUCCESS);

}
Esempio n. 23
0
/*
 * Checks h/w handshake lines for "go" status.  Count the number of times it
 * was "stop".  In UART_HANDSHAKE_AUTO mode, after a limit is reached force
 * the status to "go".
 */
static boolean_t is_hw_tx_handshake_go(mon_serial_device_t *p_device)
{
	/* Modem Status Register image */
	uart_msr_t msr;
	/* flags transmit "go" by h/w handshake */
	boolean_t hw_handshake_go;

	if ((p_device->handshake_mode == UART_HANDSHAKE_AUTO) ||
	    (p_device->handshake_mode == UART_HANDSHAKE_HW)) {
		/* Read the h/w handshake signals */

		msr.data =
			hw_read_port_8(p_device->io_base + UART_REGISTER_MSR);
		hw_handshake_go = (msr.bits.cts == 1) && (msr.bits.dsr == 1);

		if (hw_handshake_go) {
			/* Other side set h/w handshake to "go".  Reset the counter. */

			update_avg(&p_device->hw_handshake_stopped_count_avg,
				p_device->hw_handshake_stopped_count);
			p_device->hw_handshake_stopped_count = 0;
		} else if (p_device->hw_handshake_stopped_count >=
			   hw_handshake_stopped_limit) {
			/* Other side has indicated h/w handshake "stop" for too long. */

			if (p_device->handshake_mode == UART_HANDSHAKE_AUTO) {
				/* In auto mode, assume the h/w handshake is stuck and force */
				/* the status to "go" */

				hw_handshake_go = TRUE;
				p_device->num_chars_hw_handshake_auto_go++;
				if (p_device->hw_handshake_stopped_count ==
				    hw_handshake_stopped_limit) {
					/* Update the statistic only on the first character */
					/* we decided to auto-go */

					update_avg(
						&p_device->hw_handshake_stopped_count_avg,
						p_device->hw_handshake_stopped_count);
					p_device->hw_handshake_stopped_count++;
				}
			}
		} else {
			/* Increment the stop count and update the statistics */

			if (p_device->hw_handshake_stopped_count == 0) {
				/* We just stopped, increment the stops statistics counter */

				p_device->num_chars_hw_handshake_stopped++;
			}

			p_device->hw_handshake_stopped_count++;

			update_max(&p_device->hw_handshake_stopped_count_max,
				p_device->hw_handshake_stopped_count);
		}
	} else {
		/* No h/w handshake, always "go" */

		hw_handshake_go = TRUE;
	}

	return hw_handshake_go;
}
Esempio n. 24
0
/*
 * Updates the running average and maximum of a counter
 *    p_max - Maximum
 *    p_avg - Running average, as uint16_t.uint16_t
 *    count - New input
 */
static
void update_max_and_avg(uint32_t *p_max, uint32_t *p_avg, uint32_t count)
{
	update_max(p_max, count);
	update_avg(p_avg, count);
}
Esempio n. 25
0
/* Return true if an error ocurred. */
static bool update_disks(struct globalstat *gs, const libtop_tsamp_t *tsamp) {
    char rbuf[GENERIC_INT_SIZE];
    char wbuf[GENERIC_INT_SIZE];
    char rsizebuf[6];
    char wsizebuf[6];
    struct top_uinteger rops, wops, rbytes, wbytes;

    rops = top_init_uinteger(tsamp->disk_rops, false);
    wops = top_init_uinteger(tsamp->disk_wops, false);
    rbytes = top_init_uinteger(tsamp->disk_rbytes, false);
    wbytes = top_init_uinteger(tsamp->disk_wbytes, false);

    switch(top_prefs_get_mode()) {
    case STATMODE_ACCUM: {
	struct top_uinteger brops, bwops, brbytes, bwbytes;
	
	brops = top_init_uinteger(tsamp->b_disk_rops, false);
	bwops = top_init_uinteger(tsamp->b_disk_wops, false);
	brbytes = top_init_uinteger(tsamp->b_disk_rbytes, false);
	bwbytes = top_init_uinteger(tsamp->b_disk_wbytes, false);

	rops = top_sub_uinteger(&rops, &brops);
	wops = top_sub_uinteger(&wops, &bwops);
	rbytes = top_sub_uinteger(&rbytes, &brbytes);
	wbytes = top_sub_uinteger(&wbytes, &bwbytes);
    }
	break;

    case STATMODE_DELTA: {
	struct top_uinteger props, pwops, prbytes, pwbytes;
	
	props = top_init_uinteger(tsamp->p_disk_rops, false);
	pwops = top_init_uinteger(tsamp->p_disk_wops, false);
	prbytes = top_init_uinteger(tsamp->p_disk_rbytes, false);
	pwbytes = top_init_uinteger(tsamp->p_disk_wbytes, false);

	rops = top_sub_uinteger(&rops, &props);
	wops = top_sub_uinteger(&wops, &pwops);
	rbytes = top_sub_uinteger(&rbytes, &prbytes);
	wbytes = top_sub_uinteger(&wbytes, &pwbytes);
    }
	break;
    }

    if(top_sprint_uinteger(rbuf, sizeof(rbuf), rops))
	return true;

    if(top_sprint_uinteger(wbuf, sizeof(wbuf), wops))
	return true;
    
    if(top_humanize_uinteger(rsizebuf, sizeof(rsizebuf), rbytes))
	return true;

    if(top_humanize_uinteger(wsizebuf, sizeof(wsizebuf), wbytes))
	return true;
    
    gs->length = snprintf(gs->data, sizeof(gs->data),
			  "Disks: "
			  "%s/%s read, "
			  "%s/%s written.",
			  rbuf, rsizebuf,
			  wbuf, wsizebuf);

    if(-1 == gs->length) {
	reset_globalstat(gs);
	return true;
    }
			
    update_max(gs);

    return false;
}