Ejemplo n.º 1
0
Archivo: magcal.c Proyecto: pa345/lib
static int
magcal_init(const satdata_mag *data, magcal_workspace *w)
{
  int s = 0;
  size_t i;
  size_t n = 0;

  for (i = 0; i < data->n; ++i)
    {
      /* don't store flagged data */
      if (data->flags[i])
        continue;

      /* don't process high latitude data */
      if (fabs(data->latitude[i]) > MAGCAL_MAX_LATITUDE)
        continue;

      w->Ex[n] = SATDATA_VEC_X(data->B_VFM, i);
      w->Ey[n] = SATDATA_VEC_Y(data->B_VFM, i);
      w->Ez[n] = SATDATA_VEC_Z(data->B_VFM, i);

      w->F[n] = data->F[i];

      ++n;
    }

  if (n < 200)
    {
      fprintf(stderr, "magcal_init: insufficient data points for calibration: %zu\n",
              n);
      return -1;
    }

  if (n != w->n)
    {
      gsl_multifit_fdfsolver_free(w->fdf_s);
      gsl_multifit_fdfridge_free(w->fdf_ridge);
      w->fdf_s = gsl_multifit_fdfsolver_alloc(w->fdf_type, n, w->p);
      w->fdf_ridge = gsl_multifit_fdfridge_alloc(w->fdf_type, n, w->p);
      w->n = n;
    }

#if MAGCAL_SCALE
  w->B_s = GSL_MAX(gsl_stats_sd(w->Ex, 1, n),
                   GSL_MAX(gsl_stats_sd(w->Ey, 1, n),
                           gsl_stats_sd(w->Ez, 1, n)));
#endif

  /* center and scale data arrays */
  for (i = 0; i < n; ++i)
    {
      w->Ex[i] /= w->B_s;
      w->Ey[i] /= w->B_s;
      w->Ez[i] /= w->B_s;
      w->F[i] /= w->B_s;
    }

  return s;
} /* magcal_init() */
Ejemplo n.º 2
0
void MultiPeakFit::guessInitialValues()
{
	if (!d_n || d_peaks > 1)
		return;

	size_t imin, imax;
	gsl_stats_minmax_index(&imin, &imax, d_y, 1, d_n);

	double min_out = d_y[imin];
	double max_out = d_y[imax];

	QVarLengthArray<double> temp(d_n);//double temp[d_n];
	for (int i = 0; i < d_n; i++)
		temp[i] = fabs(d_y[i]);
	size_t imax_temp = gsl_stats_max_index(temp.data(), 1, d_n);//size_t imax_temp = gsl_stats_max_index(temp, 1, d_n);

	double offset, area;
	if (imax_temp == imax)
		offset = min_out;
	else //reversed bell
		offset = max_out;

	double xc = d_x[imax_temp];
	double width = 2*gsl_stats_sd(d_x, 1, d_n);

	if (d_profile == Lorentz)
		area = M_PI_2*width*fabs(max_out - min_out);
	else
		area = sqrt(M_PI_2)*width*fabs(max_out - min_out);

	gsl_vector_set(d_param_init, 0, area);
	gsl_vector_set(d_param_init, 1, xc);
	gsl_vector_set(d_param_init, 2, width);
	gsl_vector_set(d_param_init, 3, offset);
}
Ejemplo n.º 3
0
void GaussAmpFit::guessInitialValues()
{
	size_t imin, imax;
	gsl_stats_minmax_index(&imin, &imax, d_y, 1, d_n);

	double min_out = d_y[imin];
	double max_out = d_y[imax];

	gsl_vector_set(d_param_init, 1, fabs(max_out - min_out));

#ifdef Q_CC_MSVC
	QVarLengthArray<double> temp(d_n);
#else
	double temp[d_n];
#endif
	for (int i = 0; i < d_n; i++)
		temp[i] = fabs(d_y[i]);
#ifdef Q_CC_MSVC
	size_t imax_temp = gsl_stats_max_index(temp.data(), 1, d_n);
#else
	size_t imax_temp = gsl_stats_max_index(temp, 1, d_n);
#endif

	gsl_vector_set(d_param_init, 2, d_x[imax_temp]);
	gsl_vector_set(d_param_init, 3, gsl_stats_sd(d_x, 1, d_n));

	if (imax_temp == imax)
		gsl_vector_set(d_param_init, 0, min_out);
	else //reversed bell
		gsl_vector_set(d_param_init, 0, max_out);
}
Ejemplo n.º 4
0
/**
 * Get a summary statistic for the orbital elements; for instance,
 * the median value calculated over all the elements of the list.
 * @param kl List
 * @param what Can be one of: STAT_MEAN, STAT_MEDIAN, STAT_STDDEV, STAT_MAD. 
 *      Summary statistic is calculated correctly for angle parameters.
 * @return A matrix whose entries are the summary statistic for the 
 * corresponding orbital element.
 */
gsl_matrix* KL_getElementsStats(const ok_list* kl, const int what) {
    
    int npl = MROWS(kl->kernels[0]->elements);
    if (npl == 0)
        return NULL;
    
    gsl_vector* v = gsl_vector_alloc(kl->size);
    
    gsl_matrix* m = gsl_matrix_alloc(npl, ALL_ELEMENTS_SIZE);
    gsl_matrix_set_all(m, 0.);
    
    
    for (int i = 0; i < npl; i++)
            for (int j = 0; j < ALL_ELEMENTS_SIZE; j++) {
                for (int n = 0; n < kl->size; n++) {
                    VSET(v, n, MGET(kl->kernels[n]->elements, i, j));
                }
                
                switch (what) {
                    case STAT_MEAN:
                        if (j == MA || j == LOP || j == INC || j == NODE || j == TRUEANOMALY)
                            MSET(m, i, j, ok_average_angle(v->data, v->size, false));
                        else
                            MSET(m, i, j, gsl_stats_mean(v->data, 1, v->size));
                        break;
                    case STAT_STDDEV:
                        if (j == MA || j == LOP || j == INC || j == NODE || j == TRUEANOMALY) {
                            MSET(m, i, j, ok_stddev_angle(v->data, v->size, false));
                        }
                        else
                            MSET(m, i, j, gsl_stats_sd(v->data, 1, v->size));
                        break;
                    case STAT_MEDIAN:
                        if (j == MA || j == LOP || j == INC || j == NODE || j == TRUEANOMALY)
                            MSET(m, i, j, ok_median_angle(v->data, v->size, false));
                        else {
                            gsl_sort_vector(v);
                            MSET(m, i, j, gsl_stats_median_from_sorted_data(v->data, 1, v->size));
                        }
                        break;
                    case STAT_MAD:
                        if (j == MA || j == LOP || j == INC || j == NODE || j == TRUEANOMALY) {
                            double med = ok_median_angle(v->data, v->size, false);
                            MSET(m, i, j, 1.4826 * ok_mad_angle(v->data, v->size, med, false));
                        } else {
                            gsl_sort_vector(v);
                            double med = gsl_stats_median_from_sorted_data(v->data, 1, v->size);
                            
                            MSET(m, i, j, 1.4826 * ok_mad(v->data, v->size, med));
                        }
                        break;
                    default:
                        // percentiles
                        gsl_sort_vector(v);
                        MSET(m, i, j, gsl_stats_quantile_from_sorted_data(v->data, 1, v->size, (double)(what)/100.));
                };
            }
    gsl_vector_free(v);
    return m;
}
Ejemplo n.º 5
0
bool myHistogram::Convert(vector<double> &x)
{
	gsl_histogram *r;
	size_t n=x.size();
	if(n<=2) return false;
	double *res;
	res=new double[n];
	size_t i;
	for(i=0;i<n;i++) res[i]=x[i];
	double std=gsl_stats_sd(res,1,n);
	double bin=3.49*std/pow(n*1.0,1.0/3);//Scott's ruler
	if(bin<=0) 
	{
		delete []res;
		return false;
	}
	double a=gsl_stats_min(res,1,n);
	double b=gsl_stats_max(res,1,n);
	int num=(int)((b-a)/bin);
	r=gsl_histogram_alloc(num);
	gsl_histogram_set_ranges_uniform(r,a,b);
	for(i=0;i<n;i++)
	{
		gsl_histogram_increment(r,res[i]);
	}	
	Convert(r,n);	
	gsl_histogram_free(r);
	delete []res;	
	return true;
}
Ejemplo n.º 6
0
double compute_cov_mean(long nreps, double* runtimes_sec,
        pred_method_info_t prediction_info) {
    int my_rank, i,j;
    double* mean_list = NULL;
    int nmeans;
    long current_nreps;
    double* tmp_runtimes;
    double cov_mean = COEF_ERROR_VALUE;

    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    if (my_rank == OUTPUT_ROOT_PROC) {
        double mean_of_means = 0, q1,q3, sd;
        long start_index, end_index;
        double* runtimes;

        nmeans = prediction_info.method_win;
        if (nmeans > nreps) {
            return COEF_ERROR_VALUE;
        }

        mean_list = (double*)malloc(prediction_info.method_win * sizeof(double));
        tmp_runtimes = (double*)malloc(nreps * sizeof(double));

        for (i = 0; i < nmeans; i++) {
            current_nreps = nreps - i;

            for (j=0; j < current_nreps; j++) {
                tmp_runtimes[j] = runtimes_sec[j];
            }

            runtimes = tmp_runtimes;
            gsl_sort(tmp_runtimes, 1, current_nreps);
            if (current_nreps > OUTLIER_FILTER_MIN_MEAS) {
                        q1 =  gsl_stats_quantile_from_sorted_data (tmp_runtimes, 1, current_nreps, 0.25);
                        q3 =  gsl_stats_quantile_from_sorted_data (tmp_runtimes, 1, current_nreps, 0.75);

                        filter_outliers_from_sorted(tmp_runtimes, current_nreps, q1, q3, OUTLIER_FILTER_THRES, &start_index, &end_index);
                        runtimes = runtimes + start_index;
                        current_nreps =  end_index - start_index + 1;
                    }
            mean_list[i] = gsl_stats_mean(runtimes, 1, current_nreps);
        }

        mean_of_means = gsl_stats_mean(mean_list, 1, nmeans);
        sd =  gsl_stats_sd(mean_list, 1, nmeans);
        cov_mean = sd/(mean_of_means);

        //printf("cov_mean=%lf, nreps = %ld, thres=%lf (mean_of_means=%.10f)\n", cov_mean, nreps, prediction_info.method_thres, mean_of_means);


        free(tmp_runtimes);
        free(mean_list);
    }

    return cov_mean;
}
Ejemplo n.º 7
0
// feature 11:  aspect ratio1: GEOMETRY_MAX(std_x,std_y) / GEOMETRY_MIN(std_x,std_y)
int LSL_lfeatures_class ::  feature_11(LSL_Point3D_container *laserfeat_cluster, Real *out)
{
	char ret = 1;
	
	double GEOMETRY_MIN_v, GEOMETRY_MAX_v, std1, std2;
	std::vector <double> pts_coord;
	
	laserfeat_cluster -> get_coords(pts_coord, GEOMETRY_COORD_X);	
	std1 = gsl_stats_sd (&pts_coord[0], 1, laserfeat_cluster->pts.size() -1) ;
	
	laserfeat_cluster -> get_coords(pts_coord, GEOMETRY_COORD_Y);	
	std2 = gsl_stats_sd (&pts_coord[0], 1, laserfeat_cluster->pts.size() -1) ;

	GEOMETRY_MAX_v = GEOMETRY_MAX(std1, std2);	
	GEOMETRY_MIN_v = GEOMETRY_MIN(std1, std2);

	*out = (1.0 + GEOMETRY_MIN_v) / ( 1.0 + GEOMETRY_MAX_v) ;
	return(ret);
}
Ejemplo n.º 8
0
/********************************************************************************
 * clusterupdatebatch: Runs clusterupdate multiple times and gets physics as well
 * as error estimates.
 *******************************************************************************/
int
clusterupdatebatch(lattice_site * lattice, settings conf, double beta, datapoint * data )
{
  int i,j;
  double * e_block, * m_block, * e_block_avg, * m_block_avg, \
         * e_block_error, * m_block_error, * c_block , * chi_block;
  gsl_vector * mag_vector;

  e_block       = (double *) malloc(conf.block_size*sizeof(double));
  m_block       = (double *) malloc(conf.block_size*sizeof(double));
  e_block_avg   = (double *) malloc(conf.blocks*sizeof(double));
  m_block_avg   = (double *) malloc(conf.blocks*sizeof(double));
  c_block       = (double *) malloc(conf.blocks*sizeof(double));
  chi_block     = (double *) malloc(conf.blocks*sizeof(double));
  e_block_error = (double *) malloc(conf.blocks*sizeof(double));
  m_block_error = (double *) malloc(conf.blocks*sizeof(double));

  mag_vector = gsl_vector_alloc(conf.spindims);

  //Settle first
  for(i = 0 ; i < conf.max_settle ; i++)
  {
   clusterupdate(lattice,conf,beta);
  }

  //Get averages and stdev for messurements
  for(i = 0 ; i < conf.blocks ; i++)
  {
    for(j = 0 ; j < conf.block_size ; j++)
    {
      clusterupdate(lattice,conf,beta);
      e_block[j] = total_energy(lattice,conf);
      m_block[j] = magnetization(lattice,conf,mag_vector);
    }
    e_block_avg[i]   = gsl_stats_mean(e_block,1,conf.block_size);
    e_block_error[i] = gsl_stats_sd(e_block,1,conf.block_size);
    m_block_avg[i]   = gsl_stats_mean(m_block,1,conf.block_size);
    m_block_error[i] = gsl_stats_sd(m_block,1,conf.block_size);
    c_block[i]       = gsl_pow_2(beta)*gsl_pow_2(e_block_error[i]);
    chi_block[i]     = beta*gsl_pow_2(m_block_error[i]);
  }
  (*data).beta      = beta;
  (*data).erg       = gsl_stats_mean(e_block_avg,1,conf.blocks);
  (*data).erg_error = gsl_stats_sd(e_block_avg,1,conf.blocks);
  (*data).mag       = gsl_stats_mean(m_block_avg,1,conf.blocks);
  (*data).mag_error = gsl_stats_sd(m_block_avg,1,conf.blocks);
  (*data).c         = gsl_stats_mean(c_block,1,conf.blocks);
  (*data).c_error   = gsl_stats_sd(c_block,1,conf.blocks);
  (*data).chi       = gsl_stats_mean(chi_block,1,conf.blocks);
  (*data).chi_error = gsl_stats_sd(chi_block,1,conf.blocks);

  free(e_block);
  free(m_block);
  free(e_block_avg);
  free(m_block_avg);
  free(e_block_error);
  free(m_block_error);
  gsl_vector_free(mag_vector);
  return(0);
}
Ejemplo n.º 9
0
/**
 * Compute the standard deviation of a REAL4Vector
 * \param [out] sigma  Pointer to the output standard deviation value
 * \param [in]  vector Pointer to a REAL4Vector of values
 * \return Status value
 */
INT4 calcStddev(REAL4 *sigma, REAL4Vector *vector)
{

   double *gslarray = NULL;
   XLAL_CHECK( (gslarray = XLALMalloc(sizeof(double)*vector->length)) != NULL, XLAL_ENOMEM );
   for (INT4 ii=0; ii<(INT4)vector->length; ii++) gslarray[ii] = (double)vector->data[ii];
   *sigma = (REAL4)gsl_stats_sd(gslarray, 1, vector->length);

   XLALFree((double*)gslarray);

   return XLAL_SUCCESS;

} /* calcStddev() */
Ejemplo n.º 10
0
void
test_basic(const size_t n, const double data[], const double tol)
{
  gsl_rstat_workspace *rstat_workspace_p = gsl_rstat_alloc();
  const double expected_mean = gsl_stats_mean(data, 1, n);
  const double expected_var = gsl_stats_variance(data, 1, n);
  const double expected_sd = gsl_stats_sd(data, 1, n);
  const double expected_sd_mean = expected_sd / sqrt((double) n);
  const double expected_skew = gsl_stats_skew(data, 1, n);
  const double expected_kurtosis = gsl_stats_kurtosis(data, 1, n);
  double expected_rms = 0.0;
  double mean, var, sd, sd_mean, rms, skew, kurtosis;
  size_t i, num;
  int status;

  /* compute expected rms */
  for (i = 0; i < n; ++i)
    expected_rms += data[i] * data[i];

  expected_rms = sqrt(expected_rms / n);

  /* add data to rstat workspace */
  for (i = 0; i < n; ++i)
    gsl_rstat_add(data[i], rstat_workspace_p);

  mean     = gsl_rstat_mean(rstat_workspace_p);
  var      = gsl_rstat_variance(rstat_workspace_p);
  sd       = gsl_rstat_sd(rstat_workspace_p);
  sd_mean  = gsl_rstat_sd_mean(rstat_workspace_p);
  rms      = gsl_rstat_rms(rstat_workspace_p);
  skew     = gsl_rstat_skew(rstat_workspace_p);
  kurtosis = gsl_rstat_kurtosis(rstat_workspace_p);
  num      = gsl_rstat_n(rstat_workspace_p);

  gsl_test_int(num, n, "n n=%zu" , n);
  gsl_test_rel(mean, expected_mean, tol, "mean n=%zu", n);
  gsl_test_rel(var, expected_var, tol, "variance n=%zu", n);
  gsl_test_rel(sd, expected_sd, tol, "stddev n=%zu", n);
  gsl_test_rel(sd_mean, expected_sd_mean, tol, "stddev_mean n=%zu", n);
  gsl_test_rel(rms, expected_rms, tol, "rms n=%zu", n);
  gsl_test_rel(skew, expected_skew, tol, "skew n=%zu", n);
  gsl_test_rel(kurtosis, expected_kurtosis, tol, "kurtosis n=%zu", n);

  status = gsl_rstat_reset(rstat_workspace_p);
  gsl_test_int(status, GSL_SUCCESS, "rstat returned success");
  num = gsl_rstat_n(rstat_workspace_p);

  gsl_test_int(num, 0, "n n=%zu" , n);

  gsl_rstat_free(rstat_workspace_p);
}
Ejemplo n.º 11
0
StatBox2D::BoxWhiskerData Layout2D::generateBoxWhiskerData(Column *colData,
                                                           int from, int to,
                                                           int key) {
  size_t size = static_cast<size_t>((to - from) + 1);

  double *data = new double[size];

  for (int i = 0, j = from; j < to + 1; i++, j++) {
    data[i] = colData->valueAt(i);
  }
  // sort the data
  gsl_sort(data, 1, size - 1);

  StatBox2D::BoxWhiskerData statBoxData;
  statBoxData.key = key;
  // basic stats
  statBoxData.mean = gsl_stats_mean(data, 1, size);
  statBoxData.median = gsl_stats_median_from_sorted_data(data, 1, size);
  statBoxData.sd = gsl_stats_sd(data, 1, size);
  statBoxData.se = statBoxData.sd / sqrt(static_cast<double>(size));
  // data bounds
  statBoxData.boxWhiskerDataBounds.sd_lower = statBoxData.mean - statBoxData.sd;
  statBoxData.boxWhiskerDataBounds.sd_upper = statBoxData.mean + statBoxData.sd;
  statBoxData.boxWhiskerDataBounds.se_lower = statBoxData.mean - statBoxData.se;
  statBoxData.boxWhiskerDataBounds.se_upper = statBoxData.mean + statBoxData.se;
  statBoxData.boxWhiskerDataBounds.perc_1 =
      gsl_stats_quantile_from_sorted_data(data, 1, size, 0.01);
  statBoxData.boxWhiskerDataBounds.perc_5 =
      gsl_stats_quantile_from_sorted_data(data, 1, size, 0.05);
  statBoxData.boxWhiskerDataBounds.perc_10 =
      gsl_stats_quantile_from_sorted_data(data, 1, size, 0.10);
  statBoxData.boxWhiskerDataBounds.perc_25 =
      gsl_stats_quantile_from_sorted_data(data, 1, size, 0.25);
  statBoxData.boxWhiskerDataBounds.perc_75 =
      gsl_stats_quantile_from_sorted_data(data, 1, size, 0.75);
  statBoxData.boxWhiskerDataBounds.perc_90 =
      gsl_stats_quantile_from_sorted_data(data, 1, size, 0.90);
  statBoxData.boxWhiskerDataBounds.perc_95 =
      gsl_stats_quantile_from_sorted_data(data, 1, size, 0.95);
  statBoxData.boxWhiskerDataBounds.perc_99 =
      gsl_stats_quantile_from_sorted_data(data, 1, size, 0.99);
  statBoxData.boxWhiskerDataBounds.max = data[size - 1];
  statBoxData.boxWhiskerDataBounds.min = data[0];

  // delete the double data pointer
  delete[] data;

  return statBoxData;
}
Ejemplo n.º 12
0
/* Statistics code
 * Make only one call to reading for a particular time range and compute all our stats
 */
void _compute_statistics(cdb_range_t *range, uint64_t *num_recs, cdb_record_t *records) {

    uint64_t i     = 0;
    uint64_t valid = 0;
    double sum     = 0.0;
    double *values = calloc(*num_recs, sizeof(double));

    for (i = 0; i < *num_recs; i++) {

        if (!isnan(records[i].value)) {

            sum += values[valid] = records[i].value;
            valid++;
        }
    }

    range->num_recs = valid;
    range->mean     = gsl_stats_mean(values, 1, valid);
    range->max      = gsl_stats_max(values, 1, valid);
    range->min      = gsl_stats_min(values, 1, valid);
    range->sum      = sum;
    range->stddev   = gsl_stats_sd(values, 1, valid);
    range->absdev   = gsl_stats_absdev(values, 1, valid);

    /* The rest need sorted data */
    gsl_sort(values, 1, valid);

    range->median   = gsl_stats_median_from_sorted_data(values, 1, valid);
    range->pct95th  = gsl_stats_quantile_from_sorted_data(values, 1, valid, 0.95);
    range->pct75th  = gsl_stats_quantile_from_sorted_data(values, 1, valid, 0.75);
    range->pct50th  = gsl_stats_quantile_from_sorted_data(values, 1, valid, 0.50);
    range->pct25th  = gsl_stats_quantile_from_sorted_data(values, 1, valid, 0.25);

    /* MAD must come last because it alters the values array
     * http://en.wikipedia.org/wiki/Median_absolute_deviation */
    for (i = 0; i < valid; i++) {
        values[i] = fabs(values[i] - range->median);

        if (values[i] < 0.0) {
            values[i] *= -1.0;
        }
    }

    /* Final sort is required MAD */
    gsl_sort(values, 1, valid);
    range->mad = gsl_stats_median_from_sorted_data(values, 1, valid);

    free(values);
}
void single_sort(const char *dist_name, function_ptr dist_func, const char *sort_name, function_ptr sort_func, int runs, int side)
{
	double cmean, csdev, tmean, tsdev;
	struct timespec t0, t1;

	int progress = (runs <= 10) ? 1 : runs / 10;

	std::cout << std::setw(4) << side << "  ";
	std::cout << dist_name << "  " << sort_name << "  " << std::flush;
	for (int i = 1; i <= runs; i++) {
		random_seed(i);
		tcomp = tread = twrit = 0;
		(*dist_func)();

		if ((i % progress) == 0) {
			std::cout << '.' << std::flush;
		}
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t0);
		(*sort_func)();
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t1);

		comp[i - 1] = tcomp;
		msec[i - 1] = (t1.tv_sec - t0.tv_sec) * 1000.0 + (t1.tv_nsec - t0.tv_nsec) * 0.000001;
		if (! is_spatially_sorted()) {
			std::cout << "result is not sorted!\n";
		}
	}
	cmean = gsl_stats_mean(comp, 1, runs);
	csdev = gsl_stats_sd(comp, 1, runs);
	tmean = gsl_stats_mean(msec, 1, runs);
	tsdev = gsl_stats_sd(msec, 1, runs);
	std::cout << std::setprecision(0) << std::fixed;
	std::cout << std::setw(12) << cmean << ' ' << std::setw(12) << csdev << ' ';
	std::cout << std::setprecision(2) << std::fixed;
	std::cout << std::setw(12) << tmean << ' ' << std::setw(12) << tsdev << '\n';
}
Ejemplo n.º 14
0
/**
 * Get a summary statistic for the parameters; for instance,
 * the median value calculated over all the elements of the list.
 * @param kl List
 * @param what Can be one of: STAT_MEAN, STAT_MEDIAN, STAT_STDDEV, STAT_MAD. 
 * @return A vector whose entries are the summary statistic for the 
 * corresponding orbital parameter.
 */
gsl_vector* KL_getParsStats(const ok_list* kl, const int what) {

    gsl_vector* v = gsl_vector_alloc(kl->size);
    gsl_vector* ret = gsl_vector_calloc(PARAMS_SIZE + 1);
    
    
    for (int j = 0; j < PARAMS_SIZE + 1; j++) {
        if (j == PARAMS_SIZE)
                for (int n = 0; n < kl->size; n++) {
                        VSET(v, n, kl->kernels[n]->merit);
                }
        else
                for (int n = 0; n < kl->size; n++) {
                        VSET(v, n, VGET(kl->kernels[n]->params, j));
                }

        switch (what) {
            case STAT_MEAN:
                VSET(ret, j, gsl_stats_mean(v->data, 1, v->size));
                break;
            case STAT_STDDEV:
                VSET(ret, j, gsl_stats_sd(v->data, 1, v->size));
                break;
            case STAT_MEDIAN:
                gsl_sort_vector(v);
                VSET(ret, j, gsl_stats_median_from_sorted_data(v->data, 1, v->size));
                break;
            case STAT_MAD:
                gsl_sort_vector(v);
                double med = gsl_stats_median_from_sorted_data(v->data, 1, v->size);
                VSET(ret, j, 1.4826 * ok_mad(v->data, v->size, med));
                break;
            default:
                // percentiles
                gsl_sort_vector(v);
                VSET(v , j, gsl_stats_quantile_from_sorted_data(v->data, 1, v->size, (double)(what)/100.));
        };
    };
            
    gsl_vector_free(v);
    return ret;
}
Ejemplo n.º 15
0
bool myHistogram::Convert(double *res,int n)
{
	gsl_histogram *r;
	if(n<=2) return false;
	double std=gsl_stats_sd(res,1,n);
	double bin=3.49*std/pow(n*1.0,1.0/3);//Scott's ruler
	if(bin<=0) return false;	
	double a=gsl_stats_min(res,1,n);
	double b=gsl_stats_max(res,1,n);
	int num=(int)((b-a)/bin);
	r=gsl_histogram_alloc(num);
	gsl_histogram_set_ranges_uniform(r,a,b);
	for(int i=0;i<n;i++)
	{
		gsl_histogram_increment(r,res[i]);
	}	
	Convert(r,n);	
	gsl_histogram_free(r);	
	return true;
}
Ejemplo n.º 16
0
// feature 08:   countour regularity (in 2D plane xy)
int LSL_lfeatures_class ::  feature_08(LSL_Point3D_container *laserfeat_cluster, Real *out)
{
	char ret=1;

	if(laserfeat_cluster->pts.size() > 2)
	{
		std::vector <double> dist ( laserfeat_cluster->pts.size() - 1);
		
		int c = 0;
		for(unsigned int i = 0; i <laserfeat_cluster->pts.size() - 1; i++,c++)
			dist[c] = distance_L2_XY (&laserfeat_cluster->pts[i] , &laserfeat_cluster->pts[i + 1]);


		*out = gsl_stats_sd (&dist[0], 1, dist.size());
	}
	else	
		ret = 0;

	return(ret);
}
Ejemplo n.º 17
0
bool HistList::AddHist(double *res,int n,double m,double sd,CString raw)
{
	gsl_histogram *r;
	if(n<=0) return false;
	double std=gsl_stats_sd(res,1,n);
	double bin=3.49*std/pow(n*1.0,1.0/3);//Scott's ruler
	if(bin<=0) return false;	
	double a=gsl_stats_min(res,1,n);
	double b=gsl_stats_max(res,1,n);
	int num=(int)((b-a)/bin);
	r=gsl_histogram_alloc(num);
	gsl_histogram_set_ranges_uniform(r,a,b);
	for(int i=0;i<n;i++)
	{
		gsl_histogram_increment(r,res[i]);
	}
	bool bResult=AddHist(r,m,sd,raw);
	gsl_histogram_free(r);
	return bResult;
}
Ejemplo n.º 18
0
Archivo: test.c Proyecto: gaponenko/gsl
void
test_basic(const size_t n, const double data[], const double tol)
{
  gsl_rstat_workspace *rstat_workspace_p = gsl_rstat_alloc();
  const double expected_mean = gsl_stats_mean(data, 1, n);
  const double expected_var = gsl_stats_variance(data, 1, n);
  const double expected_sd = gsl_stats_sd(data, 1, n);
  const double expected_skew = gsl_stats_skew(data, 1, n);
  const double expected_kurtosis = gsl_stats_kurtosis(data, 1, n);
  double expected_rms = 0.0;
  double mean, var, sd, rms, skew, kurtosis;
  size_t i;

  /* compute expected rms */
  for (i = 0; i < n; ++i)
    expected_rms += data[i] * data[i];

  expected_rms = sqrt(expected_rms / n);

  /* add data to rstat workspace */
  for (i = 0; i < n; ++i)
    gsl_rstat_add(data[i], rstat_workspace_p);

  mean = gsl_rstat_mean(rstat_workspace_p);
  var = gsl_rstat_variance(rstat_workspace_p);
  sd = gsl_rstat_sd(rstat_workspace_p);
  rms = gsl_rstat_rms(rstat_workspace_p);
  skew = gsl_rstat_skew(rstat_workspace_p);
  kurtosis = gsl_rstat_kurtosis(rstat_workspace_p);

  gsl_test_rel(mean, expected_mean, tol, "mean n=%zu", n);
  gsl_test_rel(var, expected_var, tol, "variance n=%zu", n);
  gsl_test_rel(sd, expected_sd, tol, "stddev n=%zu", n);
  gsl_test_rel(rms, expected_rms, tol, "rms n=%zu", n);
  gsl_test_rel(skew, expected_skew, tol, "skew n=%zu", n);
  gsl_test_rel(kurtosis, expected_kurtosis, tol, "kurtosis n=%zu", n);

  gsl_rstat_free(rstat_workspace_p);
}
Ejemplo n.º 19
0
CAMLprim value ml_gsl_stats_sd(value ow, value omean, value data)
{
  size_t len = Double_array_length(data);
  double result;
  if(ow == Val_none)
    if(omean == Val_none)
      result = gsl_stats_sd(Double_array_val(data), 1, len);
    else
      result = gsl_stats_sd_m(Double_array_val(data), 1, len, 
			      Double_val(Unoption(omean)));
  else {
    value w = Unoption(ow);
    check_array_size(data, w);
    if(omean == Val_none)
      result = gsl_stats_wsd(Double_array_val(w), 1, 
			     Double_array_val(data), 1, len);
    else
      result = gsl_stats_wsd_m(Double_array_val(w), 1, 
			       Double_array_val(data), 1, len, 
			       Double_val(Unoption(omean)));
  }
  return copy_double(result);
}
Ejemplo n.º 20
0
void GaussAmpFit::guessInitialValues()
{
	size_t imin, imax;
	gsl_stats_minmax_index(&imin, &imax, d_y, 1, d_n);

	double min_out = d_y[imin];
	double max_out = d_y[imax];

	gsl_vector_set(d_param_init, 1, fabs(max_out - min_out));

	double temp[d_n];
	for (int i = 0; i < d_n; i++)
		temp[i] = fabs(d_y[i]);
	size_t imax_temp = gsl_stats_max_index(temp, 1, d_n);

	gsl_vector_set(d_param_init, 2, d_x[imax_temp]);
	gsl_vector_set(d_param_init, 3, gsl_stats_sd(d_x, 1, d_n));

	if (imax_temp == imax)
		gsl_vector_set(d_param_init, 0, min_out);
	else //reversed bell
		gsl_vector_set(d_param_init, 0, max_out);
}
Ejemplo n.º 21
0
int
test_nist (void)
{
  size_t i ;

  const size_t nlew = 200 ; 

  const double lew[200] = { 
    -213, -564,  -35,  -15,  141,  115, -420, -360,  203, -338, -431,  194,
    -220, -513,  154, -125, -559,   92,  -21, -579,  -52,   99, -543, -175,
     162, -457, -346,  204, -300, -474,  164, -107, -572,   -8,   83, -541,
    -224,  180, -420, -374,  201, -236, -531,   83,   27, -564, -112,  131,
    -507, -254,  199, -311, -495,  143,  -46, -579,  -90,  136, -472, -338,
     202, -287, -477,  169, -124, -568,   17,   48, -568, -135,  162, -430,
    -422,  172,  -74, -577,  -13,   92, -534, -243,  194, -355, -465,  156,
     -81, -578,  -64,  139, -449, -384,  193, -198, -538,  110,  -44, -577,
      -6,   66, -552, -164,  161, -460, -344,  205, -281, -504,  134,  -28,
    -576, -118,  156, -437, -381,  200, -220, -540,   83,   11, -568, -160,
     172, -414, -408,  188, -125, -572,  -32,  139, -492, -321,  205, -262,
    -504,  142,  -83, -574,    0,   48, -571, -106,  137, -501, -266,  190,
    -391, -406,  194, -186, -553,   83,  -13, -577,  -49,  103, -515, -280,
     201,  300, -506,  131,  -45, -578,  -80,  138, -462, -361,  201, -211,
    -554,   32,   74, -533, -235,  187, -372, -442,  182, -147, -566,   25,
      68, -535, -244,  194, -351, -463,  174, -125, -570,   15,   72, -550,
    -190,  172, -424, -385,  198, -218, -536,   96 } ;

  const size_t nlottery = 218 ;

  const double lottery[218] = { 
    162, 671, 933, 414, 788, 730, 817, 33, 536, 875, 670, 236, 473, 167,
    877, 980, 316, 950, 456, 92, 517, 557, 956, 954, 104, 178, 794, 278,
    147, 773, 437, 435, 502, 610, 582, 780, 689, 562, 964, 791, 28, 97,
    848, 281, 858, 538, 660, 972, 671, 613, 867, 448, 738, 966, 139, 636,
    847, 659, 754, 243, 122, 455, 195, 968, 793, 59, 730, 361, 574, 522,
    97, 762, 431, 158, 429, 414, 22, 629, 788, 999, 187, 215, 810, 782,
    47, 34, 108, 986, 25, 644, 829, 630, 315, 567, 919, 331, 207, 412,
    242, 607, 668, 944, 749, 168, 864, 442, 533, 805, 372, 63, 458, 777,
    416, 340, 436, 140, 919, 350, 510, 572, 905, 900, 85, 389, 473, 758,
    444, 169, 625, 692, 140, 897, 672, 288, 312, 860, 724, 226, 884, 508,
    976, 741, 476, 417, 831, 15, 318, 432, 241, 114, 799, 955, 833, 358,
    935, 146, 630, 830, 440, 642, 356, 373, 271, 715, 367, 393, 190, 669,
    8, 861, 108, 795, 269, 590, 326, 866, 64, 523, 862, 840, 219, 382,
    998, 4, 628, 305, 747, 247, 34, 747, 729, 645, 856, 974, 24, 568, 24,
    694, 608, 480, 410, 729, 947, 293, 53, 930, 223, 203, 677, 227, 62,
    455, 387, 318, 562, 242, 428, 968 } ;

  const size_t nmavro = 50 ;

  const double mavro[50] = { 
    2.00180, 2.00170, 2.00180, 2.00190, 2.00180, 2.00170, 2.00150,
    2.00140, 2.00150, 2.00150, 2.00170, 2.00180, 2.00180, 2.00190,
    2.00190, 2.00210, 2.00200, 2.00160, 2.00140, 2.00130, 2.00130,
    2.00150, 2.00150, 2.00160, 2.00150, 2.00140, 2.00130, 2.00140,
    2.00150, 2.00140, 2.00150, 2.00160, 2.00150, 2.00160, 2.00190,
    2.00200, 2.00200, 2.00210, 2.00220, 2.00230, 2.00240, 2.00250,
    2.00270, 2.00260, 2.00260, 2.00260, 2.00270, 2.00260, 2.00250, 
    2.00240 } ;

  const size_t nmichelson = 100 ;

  const double michelson [100] = { 
    299.85, 299.74, 299.90, 300.07, 299.93, 299.85, 299.95, 299.98,
    299.98, 299.88, 300.00, 299.98, 299.93, 299.65, 299.76, 299.81,
    300.00, 300.00, 299.96, 299.96, 299.96, 299.94, 299.96, 299.94,
    299.88, 299.80, 299.85, 299.88, 299.90, 299.84, 299.83, 299.79,
    299.81, 299.88, 299.88, 299.83, 299.80, 299.79, 299.76, 299.80,
    299.88, 299.88, 299.88, 299.86, 299.72, 299.72, 299.62, 299.86,
    299.97, 299.95, 299.88, 299.91, 299.85, 299.87, 299.84, 299.84,
    299.85, 299.84, 299.84, 299.84, 299.89, 299.81, 299.81, 299.82,
    299.80, 299.77, 299.76, 299.74, 299.75, 299.76, 299.91, 299.92,
    299.89, 299.86, 299.88, 299.72, 299.84, 299.85, 299.85, 299.78,
    299.89, 299.84, 299.78, 299.81, 299.76, 299.81, 299.79, 299.81,
    299.82, 299.85, 299.87, 299.87, 299.81, 299.74, 299.81, 299.94,
    299.95, 299.80, 299.81, 299.87 } ;

  const size_t npidigits = 5000 ;
  const double pidigits [5000] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8,
    9, 7, 9, 3, 2, 3, 8, 4, 6, 2, 6, 4, 3, 3, 8, 3, 2, 7, 9, 5, 0, 2,
    8, 8, 4, 1, 9, 7, 1, 6, 9, 3, 9, 9, 3, 7, 5, 1, 0, 5, 8, 2, 0, 9,
    7, 4, 9, 4, 4, 5, 9, 2, 3, 0, 7, 8, 1, 6, 4, 0, 6, 2, 8, 6, 2, 0,
    8, 9, 9, 8, 6, 2, 8, 0, 3, 4, 8, 2, 5, 3, 4, 2, 1, 1, 7, 0, 6, 7,
    9, 8, 2, 1, 4, 8, 0, 8, 6, 5, 1, 3, 2, 8, 2, 3, 0, 6, 6, 4, 7, 0,
    9, 3, 8, 4, 4, 6, 0, 9, 5, 5, 0, 5, 8, 2, 2, 3, 1, 7, 2, 5, 3, 5,
    9, 4, 0, 8, 1, 2, 8, 4, 8, 1, 1, 1, 7, 4, 5, 0, 2, 8, 4, 1, 0, 2,
    7, 0, 1, 9, 3, 8, 5, 2, 1, 1, 0, 5, 5, 5, 9, 6, 4, 4, 6, 2, 2, 9,
    4, 8, 9, 5, 4, 9, 3, 0, 3, 8, 1, 9, 6, 4, 4, 2, 8, 8, 1, 0, 9, 7,
    5, 6, 6, 5, 9, 3, 3, 4, 4, 6, 1, 2, 8, 4, 7, 5, 6, 4, 8, 2, 3, 3,
    7, 8, 6, 7, 8, 3, 1, 6, 5, 2, 7, 1, 2, 0, 1, 9, 0, 9, 1, 4, 5, 6,
    4, 8, 5, 6, 6, 9, 2, 3, 4,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8, 4, 2, 6, 3, 1, 2, 9, 8, 6, 0, 8, 0, 9,
    9, 8, 8, 8, 6, 8, 7, 4, 1, 3, 2, 6, 0, 4, 7, 2 } ;


  const size_t nacc1 = 3 ;
  const double numacc1[3] = { 10000001, 10000003, 10000002 } ;

  const size_t nacc2 = 1001 ;
  double numacc2[1001] ;

  const size_t nacc3 = 1001 ;
  double numacc3[1001] ;

  const size_t nacc4 = 1001 ;
  double numacc4[1001] ;

  numacc2[0] = 1.2 ;
  numacc3[0] = 1000000.2 ; 
  numacc4[0] = 10000000.2 ; 
 
  for (i = 1 ; i < 1000  ; i += 2) 
    {
      numacc2[i] = 1.1 ;
      numacc2[i+1] = 1.3 ;
      numacc3[i] = 1000000.1 ;
      numacc3[i+1] = 1000000.3 ;
      numacc4[i] = 10000000.1 ;
      numacc4[i+1] = 10000000.3 ;
    }

  gsl_ieee_env_setup ();

  {
    double mean = gsl_stats_mean (lew, 1, nlew);
    double sd = gsl_stats_sd (lew, 1, nlew);
    double lag1 = gsl_stats_lag1_autocorrelation (lew, 1, nlew);

    double expected_mean = -177.435000000000;
    double expected_sd = 277.332168044316;
    double expected_lag1 = -0.307304800605679;

    gsl_test_rel (mean, expected_mean, 1e-15, "lew gsl_stats_mean") ;
    gsl_test_rel (sd, expected_sd, 1e-15, "lew gsl_stats_sd") ;
    gsl_test_rel (lag1, expected_lag1, 1e-14, "lew autocorrelation") ;
  }


  {
    double mean = gsl_stats_mean (lottery, 1, nlottery);
    double sd = gsl_stats_sd (lottery, 1, nlottery);
    double lag1 = gsl_stats_lag1_autocorrelation (lottery, 1, nlottery);

    double expected_mean = 518.958715596330;
    double expected_sd = 291.699727470969;
    double expected_lag1 = -0.120948622967393;

    gsl_test_rel (mean, expected_mean, 1e-15, "lottery gsl_stats_mean") ;
    gsl_test_rel (sd, expected_sd, 1e-15, "lottery gsl_stats_sd") ;
    gsl_test_rel (lag1, expected_lag1, 1e-14, "lottery autocorrelation") ;
  }

  {
    double mean = gsl_stats_mean (mavro, 1, nmavro);
    double sd = gsl_stats_sd (mavro, 1, nmavro);
    double lag1 = gsl_stats_lag1_autocorrelation (mavro, 1, nmavro);

    double expected_mean = 2.00185600000000;
    double expected_sd = 0.000429123454003053;
    double expected_lag1 = 0.937989183438248;

    gsl_test_rel (mean, expected_mean, 1e-15, "mavro gsl_stats_mean") ;
    gsl_test_rel (sd, expected_sd, 1e-13, "mavro gsl_stats_sd") ;
    gsl_test_rel (lag1, expected_lag1, 1e-13, "mavro autocorrelation") ;
  }


  {
    double mean = gsl_stats_mean (michelson, 1, nmichelson);
    double sd = gsl_stats_sd (michelson, 1, nmichelson);
    double lag1 = gsl_stats_lag1_autocorrelation (michelson, 1, nmichelson);

    double expected_mean = 299.852400000000;
    double expected_sd = 0.0790105478190518;
    double expected_lag1 = 0.535199668621283;

    gsl_test_rel (mean, expected_mean, 1e-15, "michelson gsl_stats_mean") ;
    gsl_test_rel (sd, expected_sd, 1e-13, "michelson gsl_stats_sd") ;
    gsl_test_rel (lag1, expected_lag1, 1e-13, "michelson autocorrelation") ;
  }

  {
    double mean = gsl_stats_mean (pidigits, 1, npidigits);
    double sd = gsl_stats_sd (pidigits, 1, npidigits);
    double lag1 = gsl_stats_lag1_autocorrelation (pidigits, 1, npidigits);

    double expected_mean = 4.53480000000000;
    double expected_sd = 2.86733906028871;
    double expected_lag1 = -0.00355099287237972;

    gsl_test_rel (mean, expected_mean, 1e-14, "pidigits gsl_stats_mean") ;
    gsl_test_rel (sd, expected_sd, 1e-15, "pidigits gsl_stats_sd") ;
    gsl_test_rel (lag1, expected_lag1, 1e-14, "pidigits autocorrelation") ;
  }
    
  {
    double mean = gsl_stats_mean (numacc1, 1, nacc1);
    double sd = gsl_stats_sd (numacc1, 1, nacc1);
    double lag1 = gsl_stats_lag1_autocorrelation (numacc1, 1, nacc1);

    double expected_mean = 10000002;
    double expected_sd = 1;
    double expected_lag1 = -0.5;

    gsl_test_rel (mean, expected_mean, 1e-15, "acc1 gsl_stats_mean") ;
    gsl_test_rel (sd, expected_sd, 1e-15, "acc1 gsl_stats_sd") ;
    gsl_test_rel (lag1, expected_lag1, 1e-15, "acc1 autocorrelation") ;
  }

  {
    double mean = gsl_stats_mean (numacc2, 1, nacc2);
    double sd = gsl_stats_sd (numacc2, 1, nacc2);
    double lag1 = gsl_stats_lag1_autocorrelation (numacc2, 1, nacc2);

    double expected_mean = 1.2;
    double expected_sd = 0.1;
    double expected_lag1 = -0.999;

    gsl_test_rel (mean, expected_mean, 1e-15, "acc2 gsl_stats_mean") ;
    gsl_test_rel (sd, expected_sd, 1e-15, "acc2 gsl_stats_sd") ;
    gsl_test_rel (lag1, expected_lag1, 1e-10, "acc2 autocorrelation") ;
  }

  {
    double mean = gsl_stats_mean (numacc3, 1, nacc3);
    double sd = gsl_stats_sd (numacc3, 1, nacc3);
    double lag1 = gsl_stats_lag1_autocorrelation (numacc3, 1, nacc3);

    double expected_mean = 1000000.2;
    double expected_sd = 0.1;
    double expected_lag1 = -0.999;

    gsl_test_rel (mean, expected_mean, 1e-15, "acc3 gsl_stats_mean") ;
    gsl_test_rel (sd, expected_sd, 1e-9, "acc3 gsl_stats_sd") ;
    gsl_test_rel (lag1, expected_lag1, 1e-10, "acc3 autocorrelation") ;
  }


  {
    double mean = gsl_stats_mean (numacc4, 1, nacc4);
    double sd = gsl_stats_sd (numacc4, 1, nacc4);
    double lag1 = gsl_stats_lag1_autocorrelation (numacc4, 1, nacc4);

    double expected_mean = 10000000.2;
    double expected_sd = 0.1;
    double expected_lag1 = -0.999;

    gsl_test_rel (mean, expected_mean, 1e-15, "acc4 gsl_stats_mean") ;
    gsl_test_rel (sd, expected_sd, 1e-7, "acc4 gsl_stats_sd") ;
    gsl_test_rel (lag1, expected_lag1, 1e-10, "acc4 autocorrelation") ;
  }

  return 0;
}
FrequencyCountDialog::FrequencyCountDialog(Table *t, QWidget* parent, Qt::WFlags fl )
    : QDialog( parent, fl ),
    d_source_table(t),
    d_result_table(NULL),
    d_col_name(""),
    d_col_values(NULL),
	d_bins(10)
{
	setObjectName( "FrequencyCountDialog" );
	setWindowTitle(tr("QtiPlot - Frequency count"));
	setSizeGripEnabled( true );
	setAttribute(Qt::WA_DeleteOnClose);

    QGroupBox *gb1 = new QGroupBox();
    QGridLayout *gl1 = new QGridLayout(gb1);

	ApplicationWindow *app = (ApplicationWindow *)parent;
	double min = 0.0, max = 0.0, step = 0.0;
	if (t){
        int col = -1;
        int sr = 0;
        int er = t->numRows();
        int ts = t->table()->currentSelection();
        if (ts >= 0){
            Q3TableSelection sel = t->table()->selection(ts);
            sr = sel.topRow();
            er = sel.bottomRow() + 1;
            col = sel.leftCol();
            d_col_name = t->colName(col);
        }
        int size = 0;
        for (int i = sr; i < er; i++){
            if (!t->text(i, col).isEmpty())
                size++;
        }

        if (size > 1)
            d_col_values = gsl_vector_alloc(size);

        if (d_col_values){
            int aux = 0;
            for (int i = sr; i < er; i++){
                if (!t->text(i, col).isEmpty()){
                    gsl_vector_set(d_col_values, aux, t->cell(i, col));
                    aux++;
                }
            }

            gsl_sort_vector(d_col_values);

            min = floor(gsl_vector_get(d_col_values, 0));
            max = ceil(gsl_vector_get(d_col_values, size - 1));
            step = (max - min)/(double)d_bins;

            int p = app->d_decimal_digits;
            double *data = d_col_values->data;
            QLocale l = app->locale();
            QString s = "[" + QDateTime::currentDateTime().toString(Qt::LocalDate)+ " \"" + t->objectName() + "\"]\n";
            s += tr("Statistics on %1").arg(d_col_name) + ":\n";
            s += tr("Mean") + " = " + l.toString(gsl_stats_mean (data, 1, size), 'f', p) + "\n";
            s += tr("Standard Deviation") + " = " + l.toString(gsl_stats_sd(data, 1, size), 'f', p) + "\n";
            s += tr("Median") + " = " + l.toString(gsl_stats_median_from_sorted_data(data, 1, size), 'f', p) + "\n";
            s += tr("Size") + " = " + QString::number(size) + "\n";
            s += "--------------------------------------------------------------------------------------\n";
            app->updateLog(s);
        }
	}

    gl1->addWidget(new QLabel(tr("From Minimum")), 0, 0);

	boxStart = new DoubleSpinBox();
	boxStart->setLocale(app->locale());
	boxStart->setValue(min);
	boxStart->setDecimals(app->d_decimal_digits);
	gl1->addWidget(boxStart, 0, 1);

    gl1->addWidget(new QLabel(tr("To Maximum")), 1, 0);

    boxEnd = new DoubleSpinBox();
	boxEnd->setLocale(app->locale());
    boxEnd->setValue(max);
    boxEnd->setDecimals(app->d_decimal_digits);
    gl1->addWidget(boxEnd, 1, 1);

    gl1->addWidget(new QLabel(tr("Step Size")), 2, 0);

    boxStep = new DoubleSpinBox();
	boxStep->setLocale(app->locale());
    boxStep->setValue(step);
    boxStep->setDecimals(app->d_decimal_digits);
    gl1->addWidget(boxStep, 2, 1);

    gl1->setRowStretch(3, 1);
	gl1->setColumnStretch(1, 1);

	buttonApply = new QPushButton(tr( "&Apply" ));
    buttonApply->setDefault( true );
    buttonCancel = new QPushButton(tr( "&Cancel" ));
    buttonOk = new QPushButton(tr( "&Ok" ));

    QVBoxLayout *vl = new QVBoxLayout();
 	vl->addWidget(buttonApply);
 	vl->addWidget(buttonOk);
	vl->addWidget(buttonCancel);
    vl->addStretch();

    QHBoxLayout *hb = new QHBoxLayout(this);
    hb->addWidget(gb1, 1);
    hb->addLayout(vl);

	connect( buttonApply, SIGNAL( clicked() ), this, SLOT( apply() ) );
    connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
    connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
}
Ejemplo n.º 23
0
void BoxCurve::drawBox(QPainter *painter, const QwtDiMap &xMap, const QwtDiMap &yMap, double *dat, int size)
{
const int px = xMap.transform(x(0));
const int px_min = xMap.transform(x(0) - 0.5);
const int px_max = xMap.transform(x(0) + 0.5);
const int box_width = 1+(px_max - px_min)*b_width/100;
const int hbw = box_width/2;
const int median = yMap.transform(gsl_stats_median_from_sorted_data (dat, 1, size));
int b_lowerq, b_upperq;
double sd, se, mean;
if(w_range == SD || w_range == SE || b_range == SD || b_range == SE)
	{
	sd = gsl_stats_sd(dat, 1, size);
	se = sd/sqrt((double)size);
	mean = gsl_stats_mean(dat, 1, size);
	}

if(b_range == SD)
	{
	b_lowerq = yMap.transform(mean - sd*b_coeff);
	b_upperq = yMap.transform(mean + sd*b_coeff);
	}
else if(b_range == SE)
	{
	b_lowerq = yMap.transform(mean - se*b_coeff);
	b_upperq = yMap.transform(mean + se*b_coeff);
	}
else
	{
	b_lowerq = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 1-0.01*b_coeff));
	b_upperq = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 0.01*b_coeff));
	}

//draw box
if (b_style == Rect)
	{
	const QRect r = QRect(px - hbw, b_upperq, box_width, b_lowerq - b_upperq + 1);
	painter->fillRect(r, QwtPlotCurve::brush());
	painter->drawRect(r);
	}
else if (b_style == Diamond)
	{
	const QPointArray pa(4);	
	pa[0] = QPoint(px, b_upperq);	
	pa[1] = QPoint(px + hbw, median);
	pa[2] = QPoint(px, b_lowerq);
	pa[3] = QPoint(px - hbw, median);

	painter->setBrush(QwtPlotCurve::brush());
	painter->drawPolygon(pa);
	}
else if (b_style == WindBox)
	{
	const int lowerq = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 0.25));
	const int upperq = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 0.75));
	const QPointArray pa(8);	
	pa[0] = QPoint(px + hbw, b_upperq);	
	pa[1] = QPoint(int(px + 0.4*box_width), upperq);
	pa[2] = QPoint(int(px + 0.4*box_width), lowerq);
	pa[3] = QPoint(px + hbw, b_lowerq);
	pa[4] = QPoint(px - hbw, b_lowerq);
	pa[5] = QPoint(int(px - 0.4*box_width), lowerq);
	pa[6] = QPoint(int(px - 0.4*box_width), upperq);
	pa[7] = QPoint(px - hbw, b_upperq);	

	painter->setBrush(QwtPlotCurve::brush());
	painter->drawPolygon(pa);
	}
else if (b_style == Notch)
	{
	int j = (int)ceil(0.5*(size - 1.96*sqrt((double)size)));
	int k = (int)ceil(0.5*(size + 1.96*sqrt((double)size)));
	const int lowerCI = yMap.transform(dat[j]);
	const int upperCI = yMap.transform(dat[k]);

	const QPointArray pa(10);	
	pa[0] = QPoint(px + hbw, b_upperq);	
	pa[1] = QPoint(px + hbw, upperCI);
	pa[2] = QPoint(int(px + 0.25*hbw), median);
	pa[3] = QPoint(px + hbw, lowerCI);
	pa[4] = QPoint(px + hbw, b_lowerq);
	pa[5] = QPoint(px - hbw, b_lowerq);
	pa[6] = QPoint(px - hbw, lowerCI);
	pa[7] = QPoint(int(px - 0.25*hbw), median);
	pa[8] = QPoint(px - hbw, upperCI);
	pa[9] = QPoint(px - hbw, b_upperq);	

	painter->setBrush(QwtPlotCurve::brush());
	painter->drawPolygon(pa);
	}

if (w_range)
	{//draw whiskers
	const int l = int(0.1*box_width);
	int w_upperq, w_lowerq;
	if(w_range == SD)
		{
		w_lowerq = yMap.transform(mean - sd*w_coeff);
		w_upperq = yMap.transform(mean + sd*w_coeff);
		}
	else if(w_range == SE)
		{
		w_lowerq = yMap.transform(mean - se*w_coeff);
		w_upperq = yMap.transform(mean + se*w_coeff);
		}
	else
		{
		w_lowerq = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 1-0.01*w_coeff));
		w_upperq = yMap.transform(gsl_stats_quantile_from_sorted_data (dat, 1, size, 0.01*w_coeff));
		}

	painter->drawLine(px - l, w_lowerq, px + l, w_lowerq);
	painter->drawLine(px - l, w_upperq, px + l, w_upperq);

	if (b_style)
		{
		if (w_upperq != b_upperq)
			painter->drawLine(px, w_upperq, px, b_upperq);
		if (w_lowerq != b_lowerq)
			painter->drawLine(px, w_lowerq, px, b_lowerq);
		}
	else
		painter->drawLine(px, w_upperq, px, w_lowerq);
	}

//draw median line
if (b_style == Notch || b_style == NoBox)
	return;
if (b_style == WindBox)
	painter->drawLine(int(px - 0.4*box_width), median, int(px + 0.4*box_width), median);
else
	painter->drawLine(px - hbw, median, px + hbw, median);
}
Ejemplo n.º 24
0
int
main()
{
  gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
  const double tol1 = 1.0e-8;
  const double tol2 = 1.0e-3;

  gsl_ieee_env_setup();

  {
    const size_t N = 2000000;
    double *data = random_data(N, r);
    double data2[] = { 4.0, 7.0, 13.0, 16.0 };
    size_t i;

    test_basic(2, data, tol1);
    test_basic(100, data, tol1);
    test_basic(1000, data, tol1);
    test_basic(10000, data, tol1);
    test_basic(50000, data, tol1);
    test_basic(80000, data, tol1);
    test_basic(1500000, data, tol1);
    test_basic(2000000, data, tol1);

    for (i = 0; i < 4; ++i)
      data2[i] += 1.0e9;

    test_basic(4, data2, tol1);

    free(data);
  }

  {
    /* dataset from Jain and Chlamtac paper */
    const size_t n_jain = 20;
    const double data_jain[] = {  0.02,  0.15,  0.74,  3.39,  0.83,
                                  22.37, 10.15, 15.43, 38.62, 15.92,
                                  34.60, 10.28,  1.47,  0.40,  0.05,
                                  11.39,  0.27,  0.42,  0.09, 11.37 };
    double expected_jain = 4.44063435326;
  
    test_quantile(0.5, data_jain, n_jain, expected_jain, tol1, "jain");
  }

  {
    size_t n = 1000000;
    double *data = malloc(n * sizeof(double));
    double *sorted_data = malloc(n * sizeof(double));
    gsl_rstat_workspace *rstat_workspace_p = gsl_rstat_alloc();
    double p;
    size_t i;

    for (i = 0; i < n; ++i)
      {
        data[i] = gsl_ran_gaussian_tail(r, 1.3, 1.0);
        gsl_rstat_add(data[i], rstat_workspace_p);
      }

    memcpy(sorted_data, data, n * sizeof(double));
    gsl_sort(sorted_data, 1, n);

    /* test quantile calculation */
    for (p = 0.1; p <= 0.9; p += 0.1)
      {
        double expected = gsl_stats_quantile_from_sorted_data(sorted_data, 1, n, p);
        test_quantile(p, data, n, expected, tol2, "gauss");
      }

    /* test mean, variance */
    {
      const double expected_mean = gsl_stats_mean(data, 1, n);
      const double expected_var = gsl_stats_variance(data, 1, n);
      const double expected_sd = gsl_stats_sd(data, 1, n);
      const double expected_skew = gsl_stats_skew(data, 1, n);
      const double expected_kurtosis = gsl_stats_kurtosis(data, 1, n);
      const double expected_median = gsl_stats_quantile_from_sorted_data(sorted_data, 1, n, 0.5);

      const double mean = gsl_rstat_mean(rstat_workspace_p);
      const double var = gsl_rstat_variance(rstat_workspace_p);
      const double sd = gsl_rstat_sd(rstat_workspace_p);
      const double skew = gsl_rstat_skew(rstat_workspace_p);
      const double kurtosis = gsl_rstat_kurtosis(rstat_workspace_p);
      const double median = gsl_rstat_median(rstat_workspace_p);

      gsl_test_rel(mean, expected_mean, tol1, "mean");
      gsl_test_rel(var, expected_var, tol1, "variance");
      gsl_test_rel(sd, expected_sd, tol1, "stddev");
      gsl_test_rel(skew, expected_skew, tol1, "skew");
      gsl_test_rel(kurtosis, expected_kurtosis, tol1, "kurtosis");
      gsl_test_abs(median, expected_median, tol2, "median");
    }

    free(data);
    free(sorted_data);
    gsl_rstat_free(rstat_workspace_p);
  }

  gsl_rng_free(r);

  exit (gsl_test_summary());
}
Ejemplo n.º 25
0
/**
 * Computes the Lomb-Scargle periodogram of the matrix "data". "data" should contain at least three
 * columns: time, measurement and measurement error. The periodogram is calculated in "samples" intervals
 * between "Pmin" and "Pmax", spaced logarithmically. 
 * 
 * The function returns a matrix of "samples" rows and several columns, including period, power (z) and 
 * an estimation of the upper bound for the false alarm probability. The estimation is calculated using 
 * the method of Baluev, 2008 (Baluev08). The column PS_Z_LS contains the unnormalized LS periodogram 
 * (z = 1/2 * (Chi^2_0 - Chi^2_SC)), while the column PS_Z contains z_1 = 1/2 * N_H * z / Chi^2_0 (z_1 in Baluev08). 
 * The FAP upper bound is estimated as ~ tau(z_1). (Another estimate of the FAP can be calculated by 
 * estimating the indep. frequencies through your own algorithm, or using the ok_periodogram_boot routine.)
 * 
 * @param data Input data containing the data; each row containing (t_i, x_i, sigma_i)
 * @param samples Number of frequencies sampled
 * @param Pmin Minimum period sampled
 * @param Pmax Maximum period sampled
 * @param method Method to compute periodogram (ignored)
 * @param timecol Time column (e.g. 0) in the matrix data
 * @param valcol Value column (e.g. 1) in the matrix data
 * @param sigmacol Sigma column (e.g. 2) in the matrix data
 * @param p If not NULL, it is used to return additional info for the periodogram and reuse matrices to save space/speed. If you pass
 * a value different than NULL, you are responsible for deallocating the workspace and its fields. p->buf is an array of
 * gsl_matrix*, sized the same as the value of omp_get_max_threads().
 * @return A matrix containing: {PS_TIME, PS_Z, PS_FAP, PS_Z_LS} (period, power, FAP upper limit, unnormalized
 * LS power). You are responsible for deallocating it.
 */
gsl_matrix* ok_periodogram_ls(const gsl_matrix* data, const unsigned int samples, const double Pmin, const double Pmax, const int method,
                              unsigned int timecol, unsigned int valcol, unsigned int sigcol, ok_periodogram_workspace* p) {

    gsl_matrix* ret = NULL;
    gsl_matrix* buf = NULL;
    gsl_vector* bufv = gsl_vector_alloc(data->size1);

    int ndata = data->size1;

    // If no pre-allocated buffers are passed through p, or p is null,
    // allocate those buffers.
    if (p != NULL) {
        if (p->per != NULL && MROWS(p->per) == samples && MCOLS(p->per) == PS_SIZE)
            ret = p->per;
        if (p->buf != NULL && MROWS(p->buf) == ndata && MCOLS(p->per) == 5)
            ret = p->buf;
    }

    ret = (ret != NULL ? ret : gsl_matrix_alloc(samples, PS_SIZE));
    buf = (buf != NULL ? buf : gsl_matrix_alloc(ndata, 5));

    double fmin = 1. / Pmax;
    double fmax = 1. / Pmin;
    double df = (fmax - fmin) / (double) samples;


    gsl_matrix_get_col(bufv, data, timecol);
    double W = 2. * M_PI * gsl_stats_sd(bufv->data, 1, ndata) / Pmin;
    gsl_matrix_get_col(bufv, data, valcol);
    double avg = gsl_stats_mean(bufv->data, 1, ndata);
    double z1_max = 0.;
    double xa[ndata];

    // pre-calculate cdf, sdf
    for (int i = 0; i < ndata; i++) {
        double t = MGET(data, i, timecol) - MGET(data, 0, timecol);
        MSET(buf, i, BUF_CDF, cos(2 * M_PI * df * t));
        MSET(buf, i, BUF_SDF, sin(2 * M_PI * df * t));
        MSET(buf, i, BUF_C, cos(2 * M_PI * fmin * t));
        MSET(buf, i, BUF_S, sin(2 * M_PI * fmin * t));
        MSET(buf, i, BUF_SIG, 1. / (MGET(data, i, sigcol) * MGET(data, i, sigcol)));
        xa[i] = MGET(data, i, valcol) - avg;
    }

    // Calculate periodogram by looping over all angular frequencies
    for (int i = 0; i < samples; i++) {
        // Current frequency
        double f = fmin + df * i;


        double w = 2 * M_PI*f;

        // Calculate tau(w)
        double s_2wt = 0.;
        double c_2wt = 0.;

        for (int j = 0; j < ndata; j++) {
            double cos_wt = C(j);
            double sin_wt = S(j);
            c_2wt += (1. - 2. * sin_wt * sin_wt) * SIG(j);
            s_2wt += (2. * sin_wt * cos_wt) * SIG(j);
        }

        double tau = atan2(s_2wt, c_2wt) / (2. * w);
        double numa = 0.;
        double numb = 0.;
        double dena = 0.;
        double denb = 0.;
        double numa_w = 0.;
        double numb_w = 0.;
        double dena_w = 0.;
        double denb_w = 0.;

        double coswtau = cos(w * tau);
        double sinwtau = sin(w * tau);
        double chi2_h = 0.;
        double chi2_h_w = 0;

        for (int j = 0; j < ndata; j++) {

            double sig = SIG(j);

            const double cos_wt = C(j);
            const double sin_wt = S(j);

            double cos_wdf = CDF(j);
            double sin_wdf = SDF(j);

            double c = cos_wt * coswtau + sin_wt * sinwtau;
            double s = sin_wt * coswtau - cos_wt * sinwtau;
            double x = xa[j];

            MSET(buf, j, BUF_C, cos_wt * cos_wdf - sin_wt * sin_wdf);
            MSET(buf, j, BUF_S, sin_wt * cos_wdf + cos_wt * sin_wdf);

            numa += x * c * sig;
            numb += x * s * sig;
            dena += c * c * sig;
            denb += s * s * sig;
            chi2_h += x * x * sig;

            numa_w += c;
            numb_w += s;
            dena_w += c*c;
            denb_w += s*s;

            chi2_h_w += 1;
        }


        double z = 0.5 * (numa * numa / dena + numb * numb / denb);
        double z_1 = z * ndata / chi2_h;

        double w_1 = 0.5 * (numa_w * numa_w / dena_w + numb_w * numb_w / denb_w) * ndata / chi2_h_w;

        double fap_single = pow(1. - 2. * z_1 / (double) ndata, 0.5 * (double) (ndata - 3.));
        double tau_z = W * fap_single * sqrt(z_1);

        MSET(ret, samples - i - 1, PS_TIME, 1. / f);
        MSET(ret, samples - i - 1, PS_Z, z_1);
        MSET(ret, samples - i - 1, PS_Z_LS, z);
        MSET(ret, samples - i - 1, PS_FAP, MIN(fap_single + tau_z, 1.));
        MSET(ret, samples - i - 1, PS_TAU, tau);
        MSET(ret, samples - i - 1, PS_WIN, w_1);

        z1_max = MAX(z1_max, z_1);
    }

    if (p != NULL && p->calc_z_fap) {
        gsl_root_fsolver * s = gsl_root_fsolver_alloc(gsl_root_fsolver_brent);
        double pars[3];
        pars[0] = ndata;
        pars[1] = W;
        pars[2] = 0.;

        gsl_function F;
        F.function = _baluev_tau;
        F.params = pars;

        double zz = z1_max;
        while (_baluev_tau(zz, pars) > 1e-3)
            zz *= 2;

        p->z_fap_3 = _find_z(s, &F, 1e-3, 0.1, zz);
        p->z_fap_2 = _find_z(s, &F, 1e-2, 0.1, p->z_fap_3);
        p->z_fap_1 = _find_z(s, &F, 1e-1, 0.1, p->z_fap_2);


        gsl_root_fsolver_free(s);
        p->calc_z_fap = false;
    }

    if (p == NULL) {
        gsl_matrix_free(buf);
    } else {
        p->per = ret;
        p->buf = buf;
        p->zmax = z1_max;
    };

    gsl_vector_free(bufv);

    return ret;
}
Ejemplo n.º 26
0
void ErrDialog::add()
{
	ApplicationWindow *app = qobject_cast<ApplicationWindow *>(parent());
	if (!app)
		return;
	MultiLayer *plot = (MultiLayer *)app->activeWindow(ApplicationWindow::MultiLayerWindow);
	if (!plot)
		return;
	Graph* g = plot->activeLayer();
	if (!g)
		return;

	QString name = nameLabel->currentText();
	DataCurve *curve = g->dataCurve(name);
	if (!curve){
		QMessageBox::critical(app, tr("QtiPlot - Error"),
		tr("This feature is not available for user defined function curves!"));
		return;
	}

	int direction = xErrBox->isChecked() ? 0 : 1;

	ErrorBarsCurve *er = NULL;
	if (columnBox->isChecked()){
		QString errColumnName = tableNamesBox->currentText() + "_" + colNamesBox->currentText();
		Table *errTable = app->table(errColumnName);
		if (!errTable)
			return;
		/*if (w->numRows() != errTable->numRows()){
			QMessageBox::critical(app, tr("QtiPlot - Error"), tr("The selected columns have different numbers of rows!"));
			return;
		}*/
		if (errTable->isEmptyColumn(errTable->colIndex(errColumnName))){
			QMessageBox::critical(app, tr("QtiPlot - Error"), tr("The selected error column is empty!"));
			return;
		}
		er = g->addErrorBars(curve, errTable, errColumnName, direction);
	} else {
		Table *t = curve->table();
		if (!t)
			return;
		if (direction == ErrorBarsCurve::Horizontal)
			t->addCol(Table::xErr);
		else
			t->addCol(Table::yErr);

		int r = curve->dataSize();
		int rows = t->numRows();
		int col = t->numCols() - 1;
		int ycol = t->colIndex(curve->title().text());
		if (!direction)
			ycol = t->colIndex(curve->xColumnName());

		QVarLengthArray<double> Y(r);
		if (direction == ErrorBarsCurve::Horizontal){
			for (int i = 0; i < r; i++)
				Y[i] = curve->x(i);
		} else {
			for (int i = 0; i < r; i++)
				Y[i] = curve->y(i);
		}

		if (percentBox->isChecked()){
			double prc = 0.01*valueBox->value();
			int aux = 0;
			for (int i = curve->startRow(); i <= curve->endRow(); i++){
				if (!t->text(i, ycol).isEmpty() && aux < r){
					t->setCell(i, col, Y[aux]*prc);
					aux++;
				}
			}
		} else if (standardBox->isChecked() || standardErrorBox->isChecked()){
			double sd = gsl_stats_sd(Y.data(), 1, r);
			if (standardErrorBox->isChecked())
				sd /= sqrt(r);
			for (int i = 0; i < rows; i++){
				if (!t->text(i, ycol).isEmpty())
					t->setCell(i, col, sd);
			}
		}
		er = g->addErrorBars(curve, t, t->colName(col), direction);
	}

	if (er){
		er->setColor(curve->pen().color());
		g->replot();
		plot->notifyChanges();
	}
}
Ejemplo n.º 27
0
int main(int argc, char *argv []) {

	if(populate_env_variable(REF_ERROR_CODES_FILE, "L2_ERROR_CODES_FILE")) {

		printf("\nUnable to populate [REF_ERROR_CODES_FILE] variable with corresponding environment variable. Routine will proceed without error handling\n");

	}

	if (argc != 15) {

		if(populate_env_variable(SPF_BLURB_FILE, "L2_SPF_BLURB_FILE")) {

			RETURN_FLAG = 1;

		} else {

			print_file(SPF_BLURB_FILE);

		}

		write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATFI", -1, "Status flag for L2 spfind routine", ERROR_CODES_FILE_WRITE_ACCESS);

		return 1;

	} else {
		// ***********************************************************************
		// Redefine routine input parameters
		
		char *target_f				= strdup(argv[1]);	
		int bin_size_px				= strtol(argv[2], NULL, 0);
		double bg_percentile			= strtod(argv[3], NULL);
		double clip_sigma			= strtod(argv[4], NULL);
		int median_filter_width_px		= strtol(argv[5], NULL, 0);	
		double min_SNR				= strtod(argv[6], NULL);
		int min_spatial_width_px		= strtol(argv[7], NULL, 0);
                int finding_window_lo_px                = strtol(argv[8], NULL, 0);
                int finding_window_hi_px                = strtol(argv[9], NULL, 0);                
		int max_centering_num_px		= strtol(argv[10], NULL, 0);		
		int centroid_half_window_size_px	= strtol(argv[11], NULL, 0);
		int min_used_bins			= strtol(argv[12], NULL, 0);
		int window_x_lo				= strtol(argv[13], NULL, 0);
		int window_x_hi				= strtol(argv[14], NULL, 0);
		
		// ***********************************************************************
		// Open target file (ARG 1), get parameters and perform any data format 
		// checks

		fitsfile *target_f_ptr;

		int target_f_maxdim = 2, target_f_status = 0, target_f_bitpix, target_f_naxis;
		long target_f_naxes [2] = {1,1};

		if(!fits_open_file(&target_f_ptr, target_f, IMG_READ_ACCURACY, &target_f_status)) {

			if(!populate_img_parameters(target_f, target_f_ptr, target_f_maxdim, &target_f_bitpix, &target_f_naxis, target_f_naxes, &target_f_status, "TARGET FRAME")) {

				if (target_f_naxis != 2) {	// any data format checks here

					write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATFI", -2, "Status flag for L2 spfind routine", ERROR_CODES_FILE_WRITE_ACCESS);

					free(target_f);
					if(fits_close_file(target_f_ptr, &target_f_status)) fits_report_error (stdout, target_f_status); 

					return 1;
	
				}

			} else { 

				write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATFI", -3, "Status flag for L2 spfind routine", ERROR_CODES_FILE_WRITE_ACCESS);
				fits_report_error(stdout, target_f_status); 

				free(target_f);
				if(fits_close_file(target_f_ptr, &target_f_status)) fits_report_error (stdout, target_f_status); 

				return 1; 

			}

		} else { 

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATFI", -4, "Status flag for L2 spfind routine", ERROR_CODES_FILE_WRITE_ACCESS);
			fits_report_error(stdout, target_f_status); 

			free(target_f);

			return 1; 

		}
		
		// ***********************************************************************
		// Set the range limits

		int cut_x [2] = {window_x_lo, window_x_hi};
		int cut_y [2] = {1, target_f_naxes[1]};

		// ***********************************************************************
		// Set parameters used when reading data from target file (ARG 1)

		long fpixel [2] = {cut_x[0], cut_y[0]};
		long nxelements = (cut_x[1] - cut_x[0]) + 1;
		long nyelements = (cut_y[1] - cut_y[0]) + 1;

		// ***********************************************************************
		// Create arrays to store pixel values from target fits file (ARG 1)

		double target_f_pixels [nxelements];
		
		// ***********************************************************************
		// Get target fits file (ARG 1) values and store in 2D array

		int ii;

		double target_frame_values [nyelements][nxelements];
		memset(target_frame_values, 0, sizeof(double)*nxelements*nyelements);
		for (fpixel[1] = cut_y[0]; fpixel[1] <= cut_y[1]; fpixel[1]++) {

			memset(target_f_pixels, 0, sizeof(double)*nxelements);

			if(!fits_read_pix(target_f_ptr, TDOUBLE, fpixel, nxelements, NULL, target_f_pixels, NULL, &target_f_status)) {

				for (ii=0; ii<nxelements; ii++) {

					target_frame_values[fpixel[1]-1][ii] = target_f_pixels[ii];

				}

			} else { 

				write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATFI", -5, "Status flag for L2 spfind routine", ERROR_CODES_FILE_WRITE_ACCESS);
				fits_report_error(stdout, target_f_status); 

				free(target_f);									
				if(fits_close_file(target_f_ptr, &target_f_status)) fits_report_error (stdout, target_f_status); 

				return 1; 

			}

		}
		
		// FIND VALUES OF PEAK CENTROID ALONG DISPERSION AXIS
		// ***********************************************************************		
		// 1.	Bin array according to bin width given by [bin_size_px]
			
		int disp_nelements = nxelements, spat_nelements = nyelements;
		
		int disp_nelements_binned = (int)floor(disp_nelements/bin_size_px);			
		double this_frame_values_binned[spat_nelements][disp_nelements_binned];
		memset(this_frame_values_binned, 0, sizeof(double)*spat_nelements*disp_nelements_binned);
		
		double this_bin_value;
		int bin_number = 0;
		int jj;
		for (jj=0; jj<spat_nelements; jj++) {
			this_bin_value = 0;
			bin_number = 0;
			for (ii=0; ii<disp_nelements; ii++) {
				if (ii % bin_size_px == 0 && ii != 0) {
					this_frame_values_binned[jj][bin_number] = this_bin_value;
					bin_number++;
					this_bin_value = 0;
				}
				this_bin_value += target_frame_values[jj][ii];
			}
		}

		printf("\nFinding peaks");
		printf("\n-------------------------------------\n");	
		double peaks[disp_nelements_binned];
		int num_bins_used = 0;
		for (ii=0; ii<disp_nelements_binned; ii++) {

			// 1a.	Establish if any target flux is in this bin
			// 	First find the mean/sd of the [bg_percentile]th lowest valued pixels as an initial parameters for sigma clip			
			double this_spat_values[spat_nelements];
			double this_spat_values_sorted[spat_nelements];
			for (jj=0; jj<spat_nelements; jj++) {
				this_spat_values[jj] = this_frame_values_binned[jj][ii];
			}			
			memcpy(this_spat_values_sorted, this_spat_values, sizeof(double)*spat_nelements);	
			gsl_sort(this_spat_values_sorted, 1, spat_nelements);
			
			int bg_nelements = (int)floor(spat_nelements*bg_percentile);
			double bg_values [bg_nelements];
			int idx = 0;
			for (jj=0; jj<spat_nelements; jj++) {
				if (this_spat_values_sorted[jj] != 0) {			// avoid 0s set from median filter edges
					bg_values[idx] = this_spat_values_sorted[jj];
					idx++;
					if (idx == bg_nelements)
						break;
				}
			}

			if (idx != bg_nelements) {
				write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATFI", -6, "Status flag for L2 spfind routine", ERROR_CODES_FILE_WRITE_ACCESS);

				free(target_f);
				if(fits_close_file(target_f_ptr, &target_f_status)) fits_report_error (stdout, target_f_status); 

				return 1;
			}
			
			double start_mean = gsl_stats_mean(bg_values, 1, bg_nelements);
			double start_sd	  = gsl_stats_sd(bg_values, 1, bg_nelements);

			// 1b.	Iterative sigma clip around dataset with the initial guess
			int retain_indexes[spat_nelements];
			double final_mean, final_sd;
			int final_num_retained_indexes;
			
			printf("\nBin:\t\t\t\t%d", ii);	
			printf("\nStart mean:\t\t\t%f", start_mean);
			printf("\nStart SD:\t\t\t%f", start_sd);
			iterative_sigma_clip(this_spat_values, spat_nelements, clip_sigma, retain_indexes, start_mean, start_sd, &final_mean, &final_sd, &final_num_retained_indexes, FALSE);
			printf("\nFinal mean:\t\t\t%f", final_mean);
			printf("\nFinal SD:\t\t\t%f", final_sd);
			
			// 2.	Smooth array with median filter
			double this_spat_values_smoothed[spat_nelements];			
			memset(this_spat_values_smoothed, 0, sizeof(double)*spat_nelements);
			median_filter(this_spat_values, this_spat_values_smoothed, spat_nelements, median_filter_width_px);
			
			// 3.	Ascertain if this bin contains target flux
			int num_pixels_contain_target_flux = 0;
			for (jj=0; jj<spat_nelements-1; jj++) {
				if (this_spat_values_smoothed[jj] > final_mean + final_sd*min_SNR) {
					num_pixels_contain_target_flux++;
				}
			}
			printf("\nNum pixels (target):\t\t%d", num_pixels_contain_target_flux);
			
			printf("\nDoes bin contain target flux?\t");
			if (num_pixels_contain_target_flux >= min_spatial_width_px) {
				printf("Yes\n");
			} else {
				printf("No\n");
				peaks[ii] = -1;
				continue;
			}
			
			// 3.	Take derivatives
			double this_spat_values_der[spat_nelements-1];
			memset(this_spat_values_der, 0, sizeof(double)*spat_nelements-1);
			for (jj=1; jj<spat_nelements; jj++) {
				this_spat_values_der[jj-1] = this_frame_values_binned[jj][ii] - this_frame_values_binned[jj-1][ii];
			}
			
			// 4.	Smooth derivatives
			double this_spat_values_der_smoothed[spat_nelements-1];	
			memcpy(this_spat_values_der_smoothed, this_spat_values_der, sizeof(double)*spat_nelements-1);
			median_filter(this_spat_values_der, this_spat_values_der_smoothed, spat_nelements-1, median_filter_width_px);				
			
			// 5.	Pick most positive gradient from window, retaining proper index   
                        double this_spat_values_der_smoothed_windowed[spat_nelements-1]; 
                        memcpy(this_spat_values_der_smoothed_windowed, this_spat_values_der_smoothed, sizeof(double)*spat_nelements-1);
                        for (jj=0; jj<spat_nelements; jj++) {
                            if (jj >= finding_window_lo_px && jj <= finding_window_hi_px) {
                                this_spat_values_der_smoothed_windowed[jj] = this_spat_values_der_smoothed_windowed[jj];
                            } else {
                                this_spat_values_der_smoothed_windowed[jj] = -1;
                            }  
                        }
			size_t this_pk_idx = gsl_stats_max_index(this_spat_values_der_smoothed_windowed, 1, spat_nelements-1);
			printf("Start peak index:\t\t%d\n", this_pk_idx);	
			
			// 6.	Using this index, walk through centering window [max_centering_num_px] and find derivative turnover point
			printf("Found turnover:\t\t\t");			
			bool found_turnover = FALSE;
			for (jj=this_pk_idx; jj<this_pk_idx+max_centering_num_px; jj++) {
				if (this_spat_values_der_smoothed[jj] < 0.) {
					this_pk_idx = jj;
					found_turnover = TRUE;
					break;
				}
			}
			
			if (found_turnover) {
				printf("Yes\n");
				printf("End peak index:\t\t\t%d\n", this_pk_idx);	
			} else {
				printf("No\n");
				peaks[ii] = -1;
				continue;
			}

			// 7.	Get parabolic centroid using the full centroid window [centroid_half_window_size_px]
			double this_pk_window_idxs[1 + (2*centroid_half_window_size_px)];
			double this_pk_window_vals[1 + (2*centroid_half_window_size_px)];
			
			memset(this_pk_window_idxs, 0, sizeof(double)*(1 + (2*centroid_half_window_size_px)));
			memset(this_pk_window_vals, 0, sizeof(double)*(1 + (2*centroid_half_window_size_px)));
			idx = 0;
			for (jj=this_pk_idx-centroid_half_window_size_px; jj<=this_pk_idx+centroid_half_window_size_px; jj++) {
				this_pk_window_idxs[idx] = jj;
				this_pk_window_vals[idx] = this_frame_values_binned[jj][ii];
				idx++;
			}	
			
			int order = 2;
			double coeffs [order+1];  
			memset(coeffs, 0, sizeof(double)*order+1);
			double chi_squared;
			if (calc_least_sq_fit(2, 1 + (2*centroid_half_window_size_px), this_pk_window_idxs, this_pk_window_vals, coeffs, &chi_squared)) {

				write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATFI", -7, "Status flag for L2 spfind routine", ERROR_CODES_FILE_WRITE_ACCESS);

				free(target_f);
				if(fits_close_file(target_f_ptr, &target_f_status)) fits_report_error (stdout, target_f_status); 

				return 1; 		

			}
			
			double fitted_peak_idx = -coeffs[1]/(2*coeffs[2]);
			printf("Fitted peak index:\t\t%f\n", fitted_peak_idx);

			// 8.	Ensure fitted peak location is within finding window
			printf("Is fitted peak within window?\t");
			if (fitted_peak_idx > finding_window_lo_px && fitted_peak_idx < finding_window_hi_px) {
				printf("Yes\n");
                                num_bins_used++;
			} else {
				printf("No\n");
				peaks[ii] = -1;
				continue;
			}

			peaks[ii] = fitted_peak_idx;	
			
			/*for (jj=0; jj<spat_nelements-1; jj++) {
				printf("%d\t%f\t%f\n", jj, this_spat_values_der_smoothed[jj], this_spat_values_der[jj]);
			}*/ // DEBUG	
			
		}	
		
		printf("\nNum bins used:\t%d\n", num_bins_used);		
		
		if (num_bins_used < min_used_bins) {
			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATFI", -8, "Status flag for L2 spfind routine", ERROR_CODES_FILE_WRITE_ACCESS);

			free(target_f);
			if(fits_close_file(target_f_ptr, &target_f_status)) fits_report_error (stdout, target_f_status); 

			return 1;
		}		
		
		// ***********************************************************************
		// Create [FRFIND_OUTPUTF_PEAKS_FILE] output file and print a few 
		// parameters

		FILE *outputfile;
		outputfile = fopen(SPFIND_OUTPUTF_PEAKS_FILE, FILE_WRITE_ACCESS);

		if (!outputfile) { 

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATFI", -9, "Status flag for L2 spfind routine", ERROR_CODES_FILE_WRITE_ACCESS);

			free(target_f);
			if(fits_close_file(target_f_ptr, &target_f_status)) fits_report_error (stdout, target_f_status); 

			return 1;


		}

		char timestr [80];
		memset(timestr, '\0', sizeof(char)*80);

		find_time(timestr);

		fprintf(outputfile, "#### %s ####\n\n", SPFIND_OUTPUTF_PEAKS_FILE);
		fprintf(outputfile, "# Lists the coordinates of the peaks found using the spfind routine.\n\n");
		fprintf(outputfile, "# Run filename:\t%s\n", target_f);
		fprintf(outputfile, "# Run datetime:\t%s\n\n", timestr);
		
		for (ii=0; ii<disp_nelements_binned; ii++) {
			if (peaks[ii] == -1)
				continue;
			
			fprintf(outputfile, "%f\t%f\n", cut_x[0]+(ii*bin_size_px) + (double)bin_size_px/2., peaks[ii]);	
		}
		
		fprintf(outputfile, "%d", EOF);		
		
		// ***********************************************************************
		// Clean up heap memory

		free(target_f);

		// ***********************************************************************
		// Close [FRFIND_OUTPUTF_PEAKS_FILE] output file and target file (ARG 1)
		
		if (fclose(outputfile)) {

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATFI", -10, "Status flag for L2 spfind routine", ERROR_CODES_FILE_WRITE_ACCESS);

			if(fits_close_file(target_f_ptr, &target_f_status)) fits_report_error (stdout, target_f_status); 

			return 1; 

		}

		if(fits_close_file(target_f_ptr, &target_f_status)) { 

			write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATFI", -11, "Status flag for L2 spfind routine", ERROR_CODES_FILE_WRITE_ACCESS);
			fits_report_error (stdout, target_f_status); 

			return 1; 

	    	}		
		
		// ***********************************************************************
		// Write success to [ERROR_CODES_FILE]

		write_key_to_file(ERROR_CODES_FILE, REF_ERROR_CODES_FILE, "L2STATFI", RETURN_FLAG, "Status flag for L2 spfind routine", ERROR_CODES_FILE_WRITE_ACCESS);

		return 0;

	}

}
Ejemplo n.º 28
0
int
gsl_multifit_robust(const gsl_matrix * X,
                    const gsl_vector * y,
                    gsl_vector * c,
                    gsl_matrix * cov,
                    gsl_multifit_robust_workspace *w)
{
  /* check matrix and vector sizes */
  if (X->size1 != y->size)
    {
      GSL_ERROR
        ("number of observations in y does not match rows of matrix X",
         GSL_EBADLEN);
    }
  else if (X->size2 != c->size)
    {
      GSL_ERROR ("number of parameters c does not match columns of matrix X",
                 GSL_EBADLEN);
    }
  else if (cov->size1 != cov->size2)
    {   
      GSL_ERROR ("covariance matrix is not square", GSL_ENOTSQR);
    }   
  else if (c->size != cov->size1)
    {   
      GSL_ERROR
        ("number of parameters does not match size of covariance matrix",
         GSL_EBADLEN);
    }
  else if (X->size1 != w->n || X->size2 != w->p)
    {
      GSL_ERROR
        ("size of workspace does not match size of observation matrix",
         GSL_EBADLEN);
    }
  else
    {
      int s;
      double chisq;
      const double tol = GSL_SQRT_DBL_EPSILON;
      int converged = 0;
      size_t numit = 0;
      const size_t n = y->size;
      double sigy = gsl_stats_sd(y->data, y->stride, n);
      double sig_lower;
      size_t i;

      /*
       * if the initial fit is very good, then finding outliers by comparing
       * them to the residual standard deviation is difficult. Therefore we
       * set a lower bound on the standard deviation estimate that is a small
       * fraction of the standard deviation of the data values
       */
      sig_lower = 1.0e-6 * sigy;
      if (sig_lower == 0.0)
        sig_lower = 1.0;

      /* compute initial estimates using ordinary least squares */
      s = gsl_multifit_linear(X, y, c, cov, &chisq, w->multifit_p);
      if (s)
        return s;

      /* save Q S^{-1} of original matrix */
      gsl_matrix_memcpy(w->QSI, w->multifit_p->QSI);
      gsl_vector_memcpy(w->D, w->multifit_p->D);

      /* compute statistical leverage of each data point */
      s = gsl_linalg_SV_leverage(w->multifit_p->A, w->resfac);
      if (s)
        return s;

      /* correct residuals with factor 1 / sqrt(1 - h) */
      for (i = 0; i < n; ++i)
        {
          double h = gsl_vector_get(w->resfac, i);

          if (h > 0.9999)
            h = 0.9999;

          gsl_vector_set(w->resfac, i, 1.0 / sqrt(1.0 - h));
        }

      /* compute residuals from OLS fit r = y - X c */
      s = gsl_multifit_linear_residuals(X, y, c, w->r);
      if (s)
        return s;

      /* compute estimate of sigma from ordinary least squares */
      w->stats.sigma_ols = gsl_blas_dnrm2(w->r) / sqrt((double) w->stats.dof);

      while (!converged && ++numit <= w->maxiter)
        {
          double sig;

          /* adjust residuals by statistical leverage (see DuMouchel and O'Brien) */
          s = gsl_vector_mul(w->r, w->resfac);
          if (s)
            return s;

          /* compute estimate of standard deviation using MAD */
          sig = robust_madsigma(w->r, w);

          /* scale residuals by standard deviation and tuning parameter */
          gsl_vector_scale(w->r, 1.0 / (GSL_MAX(sig, sig_lower) * w->tune));

          /* compute weights using these residuals */
          s = w->type->wfun(w->r, w->weights);
          if (s)
            return s;

          gsl_vector_memcpy(w->c_prev, c);

          /* solve weighted least squares with new weights */
          s = gsl_multifit_wlinear(X, w->weights, y, c, cov, &chisq, w->multifit_p);
          if (s)
            return s;

          /* compute new residuals r = y - X c */
          s = gsl_multifit_linear_residuals(X, y, c, w->r);
          if (s)
            return s;

          converged = robust_test_convergence(w->c_prev, c, tol);
        }

      /* compute final MAD sigma */
      w->stats.sigma_mad = robust_madsigma(w->r, w);

      /* compute robust estimate of sigma */
      w->stats.sigma_rob = robust_robsigma(w->r, w->stats.sigma_mad, w->tune, w);

      /* compute final estimate of sigma */
      w->stats.sigma = robust_sigma(w->stats.sigma_ols, w->stats.sigma_rob, w);

      /* store number of iterations */
      w->stats.numit = numit;

      {
        double dof = (double) w->stats.dof;
        double rnorm = w->stats.sigma * sqrt(dof); /* see DuMouchel, sec 4.2 */
        double ss_err = rnorm * rnorm;
        double ss_tot = gsl_stats_tss(y->data, y->stride, n);

        /* compute R^2 */
        w->stats.Rsq = 1.0 - ss_err / ss_tot;

        /* compute adjusted R^2 */
        w->stats.adj_Rsq = 1.0 - (1.0 - w->stats.Rsq) * (n - 1.0) / dof;

        /* compute rmse */
        w->stats.rmse = sqrt(ss_err / dof);

        /* store SSE */
        w->stats.sse = ss_err;
      }

      /* calculate covariance matrix = sigma^2 (X^T X)^{-1} */
      s = robust_covariance(w->stats.sigma, cov, w);
      if (s)
        return s;

      /* raise an error if not converged */
      if (numit > w->maxiter)
        {
          GSL_ERROR("maximum iterations exceeded", GSL_EMAXITER);
        }

      return s;
    }
} /* gsl_multifit_robust() */
Ejemplo n.º 29
0
int main (void)
{
  int i, j, warn, counter;
  double lim[15];
  lim[0]=0.01;
  //lim[1]=0.02;
  lim[1]=0.03;
  //lim[3]=0.04;
  lim[2]=0.05;
  //lim[5]=0.09;
  lim[3]=0.11;
  //lim[7]=0.14;
  lim[4]=0.17;
  //lim[9]=0.208;
  lim[5]=0.26;
  //lim[11]=0.32;
  lim[6]=0.4;
  //lim[13]=0.51;
  lim[7]=0.64;
  //lim[15]=0.8;
  lim[8]=1.0;
  //lim[17]=1.25;
  lim[9]=1.56;
  //lim[19]=1.95;
  lim[10]=2.44;
  //lim[21]=3.05;
  lim[11]=3.81;
  //lim[23]=4.76;
  lim[12]=5.96;
  //lim[25]=7.45;
  lim[13]=9.31;
  //lim[27]=11.64;
  lim[14]=14.55;
  //lim[29]=18.18;
  counter = 0.0;
  
  double pos[N],vel[N],err[N],vel_sq, sum;
  double mean, median, skew, sd, kurtosis, error, sum1, sum2;
  
    
  FILE *velo, *sig, *script;
  velo = fopen("organized.dat", "r");
  sig = fopen("sigma.dat","w");
  
  for(i=0.0; i<N; i++)
    {        
      fscanf(velo, "%lf %lf %lf", &pos[i], &vel[i], &err[i]);
    } 
      
  //printf ("The sample mean is %g\n", mean); 
  fclose(velo);
  
  for(j=0.0; j<14.0; j=j+1.0)
    {
      counter = 0.0;
      for(i = 0.0;(i)<=N; i++)
	{
	  if( lim[j] <= pos[i] && pos[i] < lim[(j)+1] )
	    {
	      counter++;
	      gsl_sort (vel, 1, counter);
	      mean = gsl_stats_mean(vel, 1, counter);
	      median = gsl_stats_median_from_sorted_data (vel, 1, counter);
	      sd = gsl_stats_sd (vel, 1, counter);
	      skew = gsl_stats_skew(vel, 1, counter);
	      kurtosis = gsl_stats_kurtosis (vel, 1, counter); 

	      sum1 = (vel[i]-mean)*(vel[i]-mean);
	      sum1++;
	      sum2 = (vel[i]-mean)*err[i];
	      sum2++;
	      error = 1.0/(sqrt(counter)) * pow(sum1,-0.5) * sum2;

	    }
	}
	
      printf("Particulas entre %lf y %lf es %d\n",lim[j],lim[j+1], counter);
      printf("Error %lf\n", error);
      printf ("The sample mean is %g\n", mean);
      printf ("The median is %g\n", median);
      printf ("Standard deviation is %g\n", sd);
      printf ("Skewness is %g\n", skew);
      printf ("kurtosis is %g\n\n", kurtosis);
      //printf("Sigma in the bin is: %.2f\n\n", sig);
      fprintf(sig, "%lf\t %lf\t %lf\t %d\n", (lim[j]+lim[j+1])*0.5, sd, error, counter);
      
    }
    fclose(sig);
    
    script = fopen( "script1.gpl", "w" );
      fprintf(script, "set grid\nset terminal png\nset output 'Sigma_vs_rad.png'\nset nokey\n");
      fprintf( script, "set title 'Sigma vs Radius'\n" );
      fprintf( script, "set logscale x\n" );
      fprintf( script, "set xlabel 'Radius in Arcmin'\n" );
      fprintf( script, "set xrange [0.01:20]\n" );
      //fprintf( script, "set logscale x 10\n" );
      fprintf( script, "set ylabel 'Sigma (km/s)'\n" );
      fprintf( script, "plot 'sigma.dat' u 1:2:3 pt 7 ps 1 with errorbars\n");
      fclose(script);
      
      warn = system("gnuplot script1.gpl");
      
      return(warn);
      

}
Ejemplo n.º 30
0
/**
 * Compute the standard deviation of a REAL8Vector
 * \param [in] vector Pointer to a REAL8Vector of values
 * \return Standard deviation value
 */
REAL8 calcStddevD(REAL8Vector *vector)
{
   REAL8 stddev = gsl_stats_sd((double*)vector->data, 1, vector->length);
   return stddev;
} /* calcStddevD() */