void simulate_RT(component c, double a){
	/* Memory Allocation, Structures and Fields */
	grid_volume v = vol2d(size_x,size_y,a); /* Grid volume for computations */
	structure s0(v,air,pml(h_PML,Y));     /* Reference case: no scatterers; PML termination in the y-direction */
	structure s(v,air_glass_grating,pml(h_PML,Y));	/* Structure to be simulated; PML termination in the y-direction */
	fields f0(&s0); /* Fields for reference case */
	fields f(&s);   /* Fields for simulation structure */
	h5file *eps_file_ptr=f.open_h5file(eps_file_name);
	f.output_hdf5(Dielectric, v.surroundings(), eps_file_ptr, true);    /* Outputting dielectric function as .h5 file; <fields>.output_hdf5(<field_type>,<?>) */

	/* Flux Lines for Transmissions and Reflection Detectors */
	volume flux_line_trans(vec(0,h_PML+4*h_sep+d),vec(size_x,h_PML+4*h_sep+d));
	volume flux_line_refl(vec(0,h_PML+2*h_sep),vec(size_x,h_PML+2*h_sep));

	/* Appropriate Bloch Boundary Conditions */
	double k_x=n_air*freq_centre*sin(theta_degrees*const_pi/180.0);
	f0.use_bloch(vec(k_x,0.0));
	f.use_bloch(vec(k_x,0.0));

	/* Light Sources */
	gaussian_src_time src(freq_centre, 0.5/pw_freq_width, 0, 5/pw_freq_width);      /* Time-domain definition of source */
	volume src_line(vec(0,h_PML+h_sep),vec(size_x,h_PML+h_sep));

	f0.add_volume_source(c,src,src_line,src_spatial_modulator,1.0);
	f.add_volume_source(c,src,src_line,src_spatial_modulator,1.0);
	master_printf("# Line source(s) added ...\n");

	/* Fluxes for Transmission, Reflection */
	dft_flux f_t0 = f0.add_dft_flux_plane(flux_line_trans,min2(freq_min,freq_max),max2(freq_min,freq_max),num_freqs);
	dft_flux f_t = f.add_dft_flux_plane(flux_line_trans,min2(freq_min,freq_max),max2(freq_min,freq_max),num_freqs);
	dft_flux f_r0 = f0.add_dft_flux_plane(flux_line_refl,min2(freq_min,freq_max),max2(freq_min,freq_max),num_freqs);
	dft_flux f_r = f.add_dft_flux_plane(flux_line_refl,min2(freq_min,freq_max),max2(freq_min,freq_max),num_freqs);

	angleResolvedDetectors2D *ard = new angleResolvedDetectors2D(h_PML+4*h_sep, h_PML+2*h_sep, size_x, a, angle_res_degrees, freq_min, freq_max, num_freqs, theta_degrees, n_air, n_air, degree);

	master_printf("# Simulating reference structure ...\n");
	double t_final_src_0=f0.last_source_time(), t_final_sim_0=t_final_src_0+duration_factor*num_freqs/pw_freq_width/2;
	master_printf("\tparameter__user_inaccessible:\tt_final_src_0 = %f\n",t_final_src_0);
	master_printf("\tparameter__user_inaccessible:\tt_final_sim_0 = %f\n",t_final_sim_0);
	while(f0.time() < t_final_sim_0){ /* Time-stepping -- reference structure */
		f0.step(); 
		double t=f0.time();
		ard->update(t,f0,reference);
	}
	f_r0.save_hdf5(f0, flux_file_name, "reflection");
	ard->finalize_update(reference);

	master_printf("# Simulating test structure ...\n");
	double t_final_src=f.last_source_time(), t_final_sim=t_final_src+duration_factor*num_freqs/pw_freq_width/2;
	master_printf("\tparameter__user_inaccessible:\tt_final_src = %f\n",t_final_src);
	master_printf("\tparameter__user_inaccessible:\tt_final_sim = %f\n",t_final_sim);
	f_r.load_hdf5(f, flux_file_name, "reflection");
	f_r.scale_dfts(-1.0);
	while(f.time() < t_final_sim){  /* Time-stepping -- simulated structure */
		f.step();
		double t=f.time();
		ard->update(t,f,simulation);
	}
	f.output_hdf5(c, v.surroundings());     /* Outputting electric field as .h5 file; <fields>.output_hdf5(<field_type>,<?>) */
	ard->finalize_update(simulation);

	double *flux_t = f_t.flux();    /* Calculating flux -- integrating? */
	double *flux_t0 = f_t0.flux();  /* Calculating flux -- integrating? */
	double *flux_r = f_r.flux();    /* Calculating flux -- integrating? */
	double *flux_r0 = f_r0.flux();  /* Calculating flux -- integrating? */

	double *T;      /* Array to store transmission coefficients (frequency-dependent) */
	double *R;      /* Array to store reflection coefficients (frequency-dependent) */
	T = new double[num_freqs];
	R = new double[num_freqs];
	for (int i=0; i<num_freqs; ++i){	/* Calculating transmission, reflection coefficients */
		T[i] = flux_t[i] / flux_t0[i];
		R[i] = -flux_r[i] / flux_r0[i];
	}
	double dfreq = pw_freq_width / (num_freqs-1);

	master_printf("transmission:, omega, T\n");
	master_printf("reflection:, omega, R\n");
	master_printf("addition_check:, omega, R+T\n");
	for (int l=0; l<num_freqs; ++l){	/* Printing transmission coefficient values */
		master_printf("transmission:, %f, %f\n",freq_min+l*dfreq,T[l]);
		master_printf("reflection:, %f, %f\n",freq_min+l*dfreq,R[l]);
		master_printf("addition_check:, %f, %f\n",freq_min+l*dfreq,T[l]+R[l]);
	}

	ard->print_angle_unresolved_T();
	ard->print_angle_unresolved_R();
	ard->print_angle_resolved_T(file_name_prefix);
	ard->print_angle_resolved_R(file_name_prefix);

	delete [] eps_file_name;
	delete [] flux_file_name;


	delete [] flux_t;       /* "Garbage collection" at end of code execution */
	delete [] flux_t0;      /* "Garbage collection" at end of code execution */
	delete [] flux_r;       /* "Garbage collection" at end of code execution */
	delete [] flux_r0;      /* "Garbage collection" at end of code execution */

	delete [] T;    /* "Garbage collection" at end of code execution */
	delete [] R;    /* "Garbage collection" at end of code execution */

	delete ard;
}
Example #2
0
T newton_raphson_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter)
{
   BOOST_MATH_STD_USING

   T f0(0), f1, last_f0(0);
   T result = guess;

   T factor = static_cast<T>(ldexp(1.0, 1 - digits));
   T delta = 1;
   T delta1 = tools::max_value<T>();
   T delta2 = tools::max_value<T>();

   boost::uintmax_t count(max_iter);

   do{
      last_f0 = f0;
      delta2 = delta1;
      delta1 = delta;
      std::tr1::tie(f0, f1) = f(result);
      if(0 == f0)
         break;
      if(f1 == 0)
      {
         // Oops zero derivative!!!
#ifdef BOOST_MATH_INSTRUMENT
         std::cout << "Newton iteration, zero derivative found" << std::endl;
#endif
         detail::handle_zero_derivative(f, last_f0, f0, delta, result, guess, min, max);
      }
      else
      {
         delta = f0 / f1;
      }
#ifdef BOOST_MATH_INSTRUMENT
      std::cout << "Newton iteration, delta = " << delta << std::endl;
#endif
      if(fabs(delta * 2) > fabs(delta2))
      {
         // last two steps haven't converged, try bisection:
         delta = (delta > 0) ? (result - min) / 2 : (result - max) / 2;
      }
      guess = result;
      result -= delta;
      if(result <= min)
      {
         delta = 0.5F * (guess - min);
         result = guess - delta;
         if((result == min) || (result == max))
            break;
      }
      else if(result >= max)
      {
         delta = 0.5F * (guess - max);
         result = guess - delta;
         if((result == min) || (result == max))
            break;
      }
      // update brackets:
      if(delta > 0)
         max = guess;
      else
         min = guess;
   }while(--count && (fabs(result * factor) < fabs(delta)));

   max_iter -= count;

#ifdef BOOST_MATH_INSTRUMENT
   std::cout << "Newton Raphson iteration, final count = " << max_iter << std::endl;

   static boost::uintmax_t max_count = 0;
   if(max_iter > max_count)
   {
      max_count = max_iter;
      std::cout << "Maximum iterations: " << max_iter << std::endl;
   }
#endif

   return result;
}
Example #3
0
int f0_Skel(int *argTypes, void **args) {
  *(int *)args[0] = f0(*(int *)args[1], *(int *)args[2]);
  return 0;
}
Example #4
0
int main(void)
{

	double y, m, day, h, latit, longit;
	float inlat, inlon, intz;
	double tzone, d, lambda;
	double obliq, alpha, delta, LL, equation, ha, hb, twx;
	double twam, altmax, noont, settm, riset, twpm;
	time_t sekunnit;
	struct tm *p;

	degs = 180.0 / pi;
	rads = pi / 180.0;
	//  get the date and time from the user
	// read system date and extract the year

	/** First get time **/
	time(&sekunnit);

	/** Next get localtime **/

	p = localtime(&sekunnit);

	y = p->tm_year;
	// this is Y2K compliant method
	y += 1900;
	m = p->tm_mon + 1;

	day = p->tm_mday;

	h = 12;

	printf("year %4d month %2d\n", (int) y, (int) m);
	printf("Input latitude, longitude and timezone\n");
	//iscanf("%f", &inlat);
	//scanf("%f", &inlon);
	//scanf("%f", &intz);
	latit = test_longitude; //(double) inlat;
	longit = test_latitude; //(double) inlon;
	tzone = (double)2; // intz;

	printf("Latitude %f\n", latit );
	printf("Longitude %f\n", longit );
	
	// testing
	// m=6; day=10;


	d = FNday(y, m, day, h);
	printf("d %f\n", d );
	//   Use FNsun to find the ecliptic longitude of the
	//   Sun

	lambda = FNsun(d);

	//   Obliquity of the ecliptic

	obliq = 23.439 * rads - .0000004 * rads * d;

	//   Find the RA and DEC of the Sun

	alpha = atan2(cos(obliq) * sin(lambda), cos(lambda));
	delta = asin(sin(obliq) * sin(lambda));

	// Find the Equation of Time
	// in minutes
	// Correction suggested by David Smith
	LL = L - alpha;
	if (L < pi) LL += 2.0 * pi;
	equation = 1440.0 * (1.0 - LL / pi / 2.0);
	ha = f0(latit, delta);
	hb = f1(latit, delta);
	twx = hb - ha; // length of twilight in radians
	twx = 12.0 * twx / pi; // length of twilight in hours
	printf("ha= %.2f   hb= %.2f \n", ha, hb);
	// Conversion of angle to hours and minutes //
	daylen = degs * ha / 7.5;
	if (daylen < 0.0001) {
		daylen = 0.0;
	}
	// arctic winter     //

	riset = 12.0 - 12.0 * ha / pi + tzone - longit / 15.0 + equation / 60.0;
	settm = 12.0 + 12.0 * ha / pi + tzone - longit / 15.0 + equation / 60.0;
	noont = riset + 12.0 * ha / pi;
	altmax = 90.0 + delta * degs - latit;
	// Correction for S HS suggested by David Smith
	// to express altitude as degrees from the N horizon
	if (latit < delta * degs) altmax = 180.0 - altmax;

	twam = riset - twx; // morning twilight begin
	twpm = settm + twx; // evening twilight end

	if (riset > 24.0) riset -= 24.0;
	if (settm > 24.0) settm -= 24.0;

	puts("\n Sunrise and set");
	puts("===============");

	printf("  year  : %d \n", (int) y);
	printf("  month : %d \n", (int) m);
	printf("  day   : %d \n\n", (int) day);
	printf("Days since Y2K :  %d \n", (int) d);

	printf("Latitude :  %3.1f, longitude: %3.1f, timezone: %3.1f \n", (float) latit, (float) longit, (float) tzone);
	printf("Declination   :  %.2f \n", delta * degs);
	printf("Daylength     : ");
	showhrmn(daylen);
	puts(" hours \n");
	printf("Civil twilight: ");
	showhrmn(twam);
	puts("");
	printf("Sunrise       : ");
	showhrmn(riset);
	puts("");

	printf("Sun altitude ");
	// Amendment by D. Smith
	printf(" %.2f degr", altmax);
	printf(latit >= 0.0 ? " South" : " North");
	printf(" at noontime ");
	showhrmn(noont);
	puts("");
	printf("Sunset        : ");
	showhrmn(settm);
	puts("");
	printf("Civil twilight: ");
	showhrmn(twpm);
	puts("\n");

	return 0;
}
Example #5
0
 void test_f0(NonDefaultConstructible NDC) {
   f0(NDC);
 }
Example #6
0
/**
 * Calculates all sun-related important times
 * depending on time of year and location
 * @param location Location to be used in calculation
 * @param GPS_INFO GPS_INFO for current date
 * @param CALCULATED_INFO CALCULATED_INFO (not yet used)
 * @param tzone Timezone
 * @return Always 0
 */
int SunEphemeris::CalcSunTimes(const GEOPOINT &location,
                               const NMEA_INFO &GPS_INFO,
                               const DERIVED_INFO &CALCULATED_INFO,
                               const double tzone)
{
    //    float intz;
    double d,lambda;
    double obliq,alpha,delta,LL,equation,ha,hb,twx;
    int y, m, day, h;

    // testing

    // JG Removed simulator conditional code, since GPS_INFO now set up
    // from system time.

    m = GPS_INFO.Month;
    y = GPS_INFO.Year;
    day = GPS_INFO.Day;
    h = ((int)GPS_INFO.Time)/3600;
    h = (h % 24);

    d = FNday(y, m, day, (float) h);

    // Use FNsun to find the ecliptic longitude of the Sun
    lambda = FNsun(d);

    // Obliquity of the ecliptic
    obliq = 23.439 * DEG_TO_RAD - .0000004 * DEG_TO_RAD * d;

    //   Find the RA and DEC of the Sun
    alpha = atan2(cos(obliq) * sin(lambda), cos(lambda));
    delta = asin(sin(obliq) * sin(lambda));

    // Find the Equation of Time in minutes
    // Correction suggested by David Smith
    LL = L - alpha;
    if (L < PI) LL += 2.0*PI;
    equation = 1440.0 * (1.0 - LL / PI/2.0);
    ha = f0(location.Latitude,delta);
    hb = f1(location.Latitude,delta);
    twx = hb - ha;  // length of twilight in radians
    twx = 12.0*twx/PI;              // length of twilight in hours

    //  printf("ha= %.2f   hb= %.2f \n",ha,hb);

    // Conversion of angle to hours and minutes //
    daylen = RAD_TO_DEG*ha/7.5;
    if (daylen<0.0001) {
        daylen = 0.0;
    }
    // arctic winter     //

    riset = 12.0 - 12.0 * ha/PI + tzone - location.Longitude/15.0 + equation/60.0;
    settm = 12.0 + 12.0 * ha/PI + tzone - location.Longitude/15.0 + equation/60.0;
    noont = riset + 12.0 * ha/PI;
    altmax = 90.0 + delta * RAD_TO_DEG - location.Latitude;

    // Correction for S HS suggested by David Smith
    // to express altitude as degrees from the N horizon
    if (location.Latitude < delta * RAD_TO_DEG) {
        altmax = 180.0 - altmax;
    }

    twam = riset - twx;     // morning twilight begin
    twpm = settm + twx;     // evening twilight end

    if (riset > 24.0) riset-= 24.0;
    if (settm > 24.0) settm-= 24.0;

    /*
        puts("\n Sunrise and set");
        puts("===============");

        printf("  year  : %d \n",(int)y);
        printf("  month : %d \n",(int)m);
        printf("  day   : %d \n\n",(int)day);
        printf("Days since Y2K :  %d \n",(int)d);

        printf("Latitude :  %3.1f, longitude: %3.1f, timezone: %3.1f \n",(float)latit,(float)longit,(float)tzone);
        printf("Declination   :  %.2f \n",delta * RAD_TO_DEG);
        printf("Daylength     : "); showhrmn(daylen); puts(" hours \n");
        printf("Civil twilight: ");
        showhrmn(twam); puts("");
        printf("Sunrise       : ");
        showhrmn(riset); puts("");

        printf("Sun altitude ");
        // Amendment by D. Smith
        printf(" %.2f degr",altmax);
        printf(latit>=0.0 ? " South" : " North");
        printf(" at noontime "); showhrmn(noont); puts("");
        printf("Sunset        : ");
        showhrmn(settm);  puts("");
        printf("Civil twilight: ");
        showhrmn(twpm);  puts("\n");
    */
    // QUESTION TB: why not just void?

    return 0;
}
Example #7
0
void test_f0(int *ip, float const *cfp) {
  A<int> a0 = f0(ip);
  A<const float> a1 = f0(cfp);
}
Example #8
0
void f1() { f0(); }
Example #9
0
void test_implicit_conversions(bool Cond, char16 c16, longlong16 ll16,
                               char16_e c16e, longlong16_e ll16e,
                               convertible_to<char16> to_c16,
                               convertible_to<longlong16> to_ll16,
                               convertible_to<char16_e> to_c16e,
                               convertible_to<longlong16_e> to_ll16e,
                               convertible_to<char16&> rto_c16,
                               convertible_to<char16_e&> rto_c16e) {
    f0(to_c16);
    f0(to_ll16);
    f0(to_c16e);
    f0(to_ll16e);
    f2(to_c16);
    f2(to_ll16);
    f2(to_c16e);
    f2(to_ll16e); // expected-error{{no matching function}}

    (void)(c16 == c16e);
    (void)(c16 == to_c16);
    (void)+to_c16;
    (void)-to_c16;
    (void)~to_c16;
    (void)(to_c16 == to_c16e);
    (void)(to_c16 != to_c16e);
    (void)(to_c16 <  to_c16e);
    (void)(to_c16 <= to_c16e);
    (void)(to_c16 >  to_c16e);
    (void)(to_c16 >= to_c16e);
    (void)(to_c16 + to_c16);
    (void)(to_c16 - to_c16);
    (void)(to_c16 * to_c16);
    (void)(to_c16 / to_c16);
    (void)(rto_c16 = to_c16); // expected-error{{no viable overloaded '='}}
    (void)(rto_c16 += to_c16);
    (void)(rto_c16 -= to_c16);
    (void)(rto_c16 *= to_c16);
    (void)(rto_c16 /= to_c16);

    (void)+to_c16e;
    (void)-to_c16e;
    (void)~to_c16e;
    (void)(to_c16e == to_c16e);
    (void)(to_c16e != to_c16e);
    (void)(to_c16e <  to_c16e);
    (void)(to_c16e <= to_c16e);
    (void)(to_c16e >  to_c16e);
    (void)(to_c16e >= to_c16e);
    (void)(to_c16e + to_c16);
    (void)(to_c16e - to_c16);
    (void)(to_c16e * to_c16);
    (void)(to_c16e / to_c16);
    (void)(rto_c16e = to_c16); // expected-error{{no viable overloaded '='}}
    (void)(rto_c16e += to_c16);
    (void)(rto_c16e -= to_c16);
    (void)(rto_c16e *= to_c16);
    (void)(rto_c16e /= to_c16);

    (void)+to_c16;
    (void)-to_c16;
    (void)~to_c16;
    (void)(to_c16 == to_c16e);
    (void)(to_c16 != to_c16e);
    (void)(to_c16 <  to_c16e);
    (void)(to_c16 <= to_c16e);
    (void)(to_c16 >  to_c16e);
    (void)(to_c16 >= to_c16e);
    (void)(to_c16 + to_c16e);
    (void)(to_c16 - to_c16e);
    (void)(to_c16 * to_c16e);
    (void)(to_c16 / to_c16e);
    (void)(rto_c16 = c16e); // expected-error{{no viable overloaded '='}}
    (void)(rto_c16 += to_c16e);
    (void)(rto_c16 -= to_c16e);
    (void)(rto_c16 *= to_c16e);
    (void)(rto_c16 /= to_c16e);

    (void)(Cond? to_c16 : to_c16e);
    (void)(Cond? to_ll16e : to_ll16);

    // These 2 are convertable with -flax-vector-conversions (default)
    (void)(Cond? to_c16 : to_ll16);
    (void)(Cond? to_c16e : to_ll16e);
}
Example #10
0
 void TypeOfFE_RTmodif::FB(const bool * whatd,const Mesh & Th,const Triangle & K,const R2 & PHat,RNMK_ & val) const
{ //  
//  const Triangle & K(FE.T);
  R2 P(K(PHat));
  R2 A(K[0]), B(K[1]),C(K[2]);
  R la=1-PHat.x-PHat.y,lb=PHat.x,lc=PHat.y; 
  R2 Dla(K.H(0)), Dlb(K.H(1)), Dlc(K.H(2));
  if (val.N() <3) 
   throwassert(val.N() >=3);
  throwassert(val.M()==2 );

  R2 AB(A,B),AC(A,C),BA(B,A),BC(B,C),CA(C,A),CB(C,B);

  R aa0= 1./(((AB,Dlb) + (AC,Dlc))*K.area);
  R aa1= 1./(((BA,Dla) + (BC,Dlc))*K.area);
  R aa2= 1./(((CA,Dla) + (CB,Dlb))*K.area);
  int i=0;
  R a0=   &K[ (i+1)%3] < &K[ (i+2)%3] ? aa0 : -aa0 ;
  i=1;
  R a1=   &K[ (i+1)%3] < &K[ (i+2)%3] ? aa1 : -aa1 ;
  i=2;
  R a2=   &K[ (i+1)%3] < &K[ (i+2)%3] ? aa2 : -aa2 ;
 // if (Th(K)< 2) cout << Th(K) << " " <<  A << " "  << B << " " << C << "; " <<  a0 << " " << a1 << " "<< a2 << endl;;
 
  R2 Va= AB*(lb*a0) + AC*(lc*a0);
  R2 Vb= BA*(la*a1) + BC*(lc*a1);
  R2 Vc= CA*(la*a2) + CB*(lb*a2);
  R2 Va_x= AB*(Dlb.x*a0) + AC*(Dlc.x*a0);
  R2 Vb_x= BA*(Dla.x*a1) + BC*(Dlc.x*a1);
  R2 Vc_x= CA*(Dla.x*a2) + CB*(Dlb.x*a2);
  R2 Va_y= AB*(Dlb.y*a0) + AC*(Dlc.y*a0);
  R2 Vb_y= BA*(Dla.y*a1) + BC*(Dlc.y*a1);
  R2 Vc_y= CA*(Dla.y*a2) + CB*(Dlb.y*a2);
 
 if( whatd[op_id])
  {
    RN_ f0(val('.',0,0)); 
    RN_ f1(val('.',1,0)); 
    
    f0[0] = Va.x;
    f1[0] = Va.y;
    
    f0[1] = Vb.x;
    f1[1] = Vb.y;
    
    f0[2] = Vc.x;
    f1[2] = Vc.y;
  }
 // ----------------
 if( whatd[op_dx])
   {
     val(0,0,1) =  Va_x.x;  
     val(0,1,1) =  Va_x.y;  
     
     val(1,0,1) =  Vb_x.x;  
     val(1,1,1) =  Vb_x.y;  
     
     val(2,0,1) =  Vc_x.x;  
     val(2,1,1) =  Vc_x.y;
   }
 
 if( whatd[op_dy])
   {
     val(0,0,2) =  Va_y.x;  
     val(0,1,2) =  Va_y.y;  

     val(1,0,2) =  Vb_y.x;  
     val(1,1,2) =  Vb_y.y;  
     
  val(2,0,2) =  Vc_y.x;  
  val(2,1,2) =  Vc_y.y;  
   }
 
}
Example #11
0
 void TypeOfFE_P2ttdc::FB(const bool *whatd,const Mesh & ,const Triangle & K,const R2 & P1,RNMK_ & val) const
{
    R2 P=Shrink1(P1);  
   
//  const Triangle & K(FE.T);
  R2 A(K[0]), B(K[1]),C(K[2]);
  R l0=1-P.x-P.y,l1=P.x,l2=P.y; 
  R l4_0=(4*l0-1),l4_1=(4*l1-1),l4_2=(4*l2-1); 
  
//  throwassert(FE.N == 1);  
  throwassert( val.N()>=6);
  throwassert(val.M()==1);
//  throwassert(val.K()==3 );
  
  val=0; 
// --     
 if (whatd[op_id])
  {
   RN_ f0(val('.',0,op_id)); 
  f0[0] = l0*(2*l0-1);
  f0[1] = l1*(2*l1-1);
  f0[2] = l2*(2*l2-1);
  f0[3] = 4*l1*l2; // oppose au sommet 0
  f0[4] = 4*l0*l2; // oppose au sommet 1
  f0[5] = 4*l1*l0; // oppose au sommet 3
  }
 if(  whatd[op_dx] || whatd[op_dy] || whatd[op_dxx] || whatd[op_dyy] ||  whatd[op_dxy])
 {
   R2 Dl0(K.H(0)*cshrink1), Dl1(K.H(1)*cshrink1), Dl2(K.H(2)*cshrink1);
  if (whatd[op_dx])
  {
    RN_ f0x(val('.',0,op_dx)); 
  f0x[0] = Dl0.x*l4_0;
  f0x[1] = Dl1.x*l4_1;
  f0x[2] = Dl2.x*l4_2;
  f0x[3] = 4*(Dl1.x*l2 + Dl2.x*l1) ;
  f0x[4] = 4*(Dl2.x*l0 + Dl0.x*l2) ;
  f0x[5] = 4*(Dl0.x*l1 + Dl1.x*l0) ;
  }

 if (whatd[op_dy])
  {  
    RN_ f0y(val('.',0,op_dy)); 
  f0y[0] = Dl0.y*l4_0;
  f0y[1] = Dl1.y*l4_1;
  f0y[2] = Dl2.y*l4_2;
  f0y[3] = 4*(Dl1.y*l2 + Dl2.y*l1) ;
  f0y[4] = 4*(Dl2.y*l0 + Dl0.y*l2) ;
  f0y[5] = 4*(Dl0.y*l1 + Dl1.y*l0) ;
  }
 
 if (whatd[op_dxx])
  {  
    RN_ fxx(val('.',0,op_dxx)); 

    fxx[0] = 4*Dl0.x*Dl0.x;
    fxx[1] = 4*Dl1.x*Dl1.x;
    fxx[2] = 4*Dl2.x*Dl2.x;
    fxx[3] =  8*Dl1.x*Dl2.x;
    fxx[4] =  8*Dl0.x*Dl2.x;
    fxx[5] =  8*Dl0.x*Dl1.x;
  }

 if (whatd[op_dyy])
  {  
    RN_ fyy(val('.',0,op_dyy)); 
    fyy[0] = 4*Dl0.y*Dl0.y;
    fyy[1] = 4*Dl1.y*Dl1.y;
    fyy[2] = 4*Dl2.y*Dl2.y;
    fyy[3] =  8*Dl1.y*Dl2.y;
    fyy[4] =  8*Dl0.y*Dl2.y;
    fyy[5] =  8*Dl0.y*Dl1.y;
  }
 if (whatd[op_dxy])
  {  
    assert(val.K()>op_dxy);
    RN_ fxy(val('.',0,op_dxy)); 
  
    fxy[0] = 4*Dl0.x*Dl0.y;
    fxy[1] = 4*Dl1.x*Dl1.y;
    fxy[2] = 4*Dl2.x*Dl2.y;
    fxy[3] =  4*(Dl1.x*Dl2.y + Dl1.y*Dl2.x);
    fxy[4] =  4*(Dl0.x*Dl2.y + Dl0.y*Dl2.x);
    fxy[5] =  4*(Dl0.x*Dl1.y + Dl0.y*Dl1.x);
  }
 
 }
 
}
Example #12
0
static void sha1_process(sha1_context_t *ctx, const uint8_t *in)
{
	const uint32_t k[] = {
		0x5A827999,
		0x6ED9EBA1,
		0x8F1BBCDC,
		0xCA62C1D6,
	};
	uint32_t w[80], temp, a, b, c, d, e;
	int i, j;

	for (i = 0, j = 0; i < 16; i++, j += 4)
		w[i] = (in[j] << 24) | (in[j+1] << 16) |
			(in[j+2] << 8) | in[j+3];
	for (; i < 80; i++)
		w[i] = rol32(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1);

	a = ctx->h[0];
	b = ctx->h[1];
	c = ctx->h[2];
	d = ctx->h[3];
	e = ctx->h[4];

	for (i = 0; i < 20; i++) {
		temp = rol32(a, 5) + f0(b, c, d) + e + w[i] + k[0];

		e = d;
		d = c;
		c = rol32(b, 30);
		b = a;
		a = temp;
	}
	for (; i < 40; i++) {
		temp = rol32(a, 5) + f1(b, c, d) + e + w[i] + k[1];

		e = d;
		d = c;
		c = rol32(b, 30);
		b = a;
		a = temp;
	}
	for (; i < 60; i++) {
		temp = rol32(a, 5) + f2(b, c, d) + e + w[i] + k[2];

		e = d;
		d = c;
		c = rol32(b, 30);
		b = a;
		a = temp;
	}
	for (; i < 80; i++) {
		temp = rol32(a, 5) + f1(b, c, d) + e + w[i] + k[3];

		e = d;
		d = c;
		c = rol32(b, 30);
		b = a;
		a = temp;
	}

	ctx->h[0] += a;
	ctx->h[1] += b;
	ctx->h[2] += c;
	ctx->h[3] += d;
	ctx->h[4] += e;
}
Example #13
0
T schroeder_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter)
{
   BOOST_MATH_STD_USING

   T f0(0), f1, f2, last_f0(0);
   T result = guess;

   T factor = static_cast<T>(ldexp(1.0, 1 - digits));
   T delta = 0;
   T delta1 = tools::max_value<T>();
   T delta2 = tools::max_value<T>();

#ifdef BOOST_MATH_INSTRUMENT
   std::cout << "Schroeder iteration, limit = " << factor << std::endl;
#endif

   boost::uintmax_t count(max_iter);

   do{
      last_f0 = f0;
      delta2 = delta1;
      delta1 = delta;
      std::tr1::tie(f0, f1, f2) = f(result);
      if(0 == f0)
         break;
      if((f1 == 0) && (f2 == 0))
      {
         // Oops zero derivative!!!
#ifdef BOOST_MATH_INSTRUMENT
         std::cout << "Halley iteration, zero derivative found" << std::endl;
#endif
         detail::handle_zero_derivative(f, last_f0, f0, delta, result, guess, min, max);
      }
      else
      {
         T ratio = f0 / f1;
         if(ratio / result < 0.1)
         {
            delta = ratio + (f2 / (2 * f1)) * ratio * ratio;
            // check second derivative doesn't over compensate:
            if(delta * ratio < 0)
               delta = ratio;
         }
         else
            delta = ratio;  // fall back to Newton iteration.
      }
      if(fabs(delta * 2) > fabs(delta2))
      {
         // last two steps haven't converged, try bisection:
         delta = (delta > 0) ? (result - min) / 2 : (result - max) / 2;
      }
      guess = result;
      result -= delta;
#ifdef BOOST_MATH_INSTRUMENT
      std::cout << "Halley iteration, delta = " << delta << std::endl;
#endif
      if(result <= min)
      {
         delta = 0.5F * (guess - min);
         result = guess - delta;
         if((result == min) || (result == max))
            break;
      }
      else if(result >= max)
      {
         delta = 0.5F * (guess - max);
         result = guess - delta;
         if((result == min) || (result == max))
            break;
      }
      // update brackets:
      if(delta > 0)
         max = guess;
      else
         min = guess;
   }while(--count && (fabs(result * factor) < fabs(delta)));

   max_iter -= count;

#ifdef BOOST_MATH_INSTRUMENT
   std::cout << "Schroeder iteration, final count = " << max_iter << std::endl;

   static boost::uintmax_t max_count = 0;
   if(max_iter > max_count)
   {
      max_count = max_iter;
      std::cout << "Maximum iterations: " << max_iter << std::endl;
   }
#endif

   return result;
}
Example #14
0
T halley_iterate(F f, T guess, T min, T max, int digits, boost::uintmax_t& max_iter)
{
   BOOST_MATH_STD_USING

   T f0(0), f1, f2;
   T result = guess;

   T factor = static_cast<T>(ldexp(1.0, 1 - digits));
   T delta = (std::max)(10000000 * guess, T(10000000));  // arbitarily large delta
   T last_f0 = 0;
   T delta1 = delta;
   T delta2 = delta;

   bool out_of_bounds_sentry = false;

#ifdef BOOST_MATH_INSTRUMENT
   std::cout << "Halley iteration, limit = " << factor << std::endl;
#endif

   boost::uintmax_t count(max_iter);

   do{
      last_f0 = f0;
      delta2 = delta1;
      delta1 = delta;
      std::tr1::tie(f0, f1, f2) = f(result);
      if(0 == f0)
         break;
      if((f1 == 0) && (f2 == 0))
      {
         // Oops zero derivative!!!
#ifdef BOOST_MATH_INSTRUMENT
         std::cout << "Halley iteration, zero derivative found" << std::endl;
#endif
         detail::handle_zero_derivative(f, last_f0, f0, delta, result, guess, min, max);
      }
      else
      {
         if(f2 != 0)
         {
            T denom = 2 * f0;
            T num = 2 * f1 - f0 * (f2 / f1);
            if((fabs(num) < 1) && (fabs(denom) >= fabs(num) * tools::max_value<T>()))
            {
               // possible overflow, use Newton step:
               delta = f0 / f1;
            }
            else
               delta = denom / num;
            if(delta * f1 / f0 < 0)
            {
               // probably cancellation error, try a Newton step instead:
               delta = f0 / f1;
            }
         }
         else
            delta = f0 / f1;
      }
#ifdef BOOST_MATH_INSTRUMENT
      std::cout << "Halley iteration, delta = " << delta << std::endl;
#endif
      T convergence = fabs(delta / delta2);
      if((convergence > 0.8) && (convergence < 2))
      {
         // last two steps haven't converged, try bisection:
         delta = (delta > 0) ? (result - min) / 2 : (result - max) / 2;
         // reset delta2 so that this branch will *not* be taken on the
         // next iteration:
         delta2 = delta * 3;
      }
      guess = result;
      result -= delta;

      // check for out of bounds step:
      if(result < min)
      {
         T diff = ((fabs(min) < 1) && (fabs(result) > 1) && (tools::max_value<T>() / fabs(result) < fabs(min))) ? 1000  : result / min;
         if(fabs(diff) < 1)
            diff = 1 / diff;
         if(!out_of_bounds_sentry && (diff > 0) && (diff < 3))
         {
            // Only a small out of bounds step, lets assume that the result
            // is probably approximately at min:
            delta = 0.99f * (guess  - min);
            result = guess - delta;
            out_of_bounds_sentry = true; // only take this branch once!
         }
         else
         {
            delta = (guess - min) / 2;
            result = guess - delta;
            if((result == min) || (result == max))
               break;
         }
      }
      else if(result > max)
      {
         T diff = ((fabs(max) < 1) && (fabs(result) > 1) && (tools::max_value<T>() / fabs(result) < fabs(max))) ? 1000  : result / max;
         if(fabs(diff) < 1)
            diff = 1 / diff;
         if(!out_of_bounds_sentry && (diff > 0) && (diff < 3))
         {
            // Only a small out of bounds step, lets assume that the result
            // is probably approximately at min:
            delta = 0.99f * (guess  - max);
            result = guess - delta;
            out_of_bounds_sentry = true; // only take this branch once!
         }
         else
         {
            delta = (guess - max) / 2;
            result = guess - delta;
            if((result == min) || (result == max))
               break;
         }
      }
      // update brackets:
      if(delta > 0)
         max = guess;
      else
         min = guess;
   }while(--count && (fabs(result * factor) < fabs(delta)));

   max_iter -= count;

#ifdef BOOST_MATH_INSTRUMENT
   std::cout << "Halley iteration, final count = " << max_iter << std::endl;

   static boost::uintmax_t max_count = 0;
   if(max_iter > max_count)
   {
      max_count = max_iter;
      std::cout << "Maximum iterations: " << max_iter << std::endl;
   }
#endif

   return result;
}
Example #15
0
//程序假设所有的值不可能超过65535,所有大于等于65535的值都视为无效或者空。
//对于测试数据做了确定了专门的范围,保证65535这个假设对整个程序没有影响
int _tmain(int argc, _TCHAR* argv[])
{

    Foo a = f0();
    std::cout << a.a << std::endl;

    float ln = 0, tn = 0,en =0;
    rb::rb_timer_t timer;
    timer.init();

    std::vector<Circle*> circles;
    std::vector<Vector> ps;
    std::vector<Vector> dirs;

    std::vector<int> data1;
    data1.resize(20);


    float max_times = 0;
    float avg_times = 0;
    float total_times = 0;
    int ntimes = 0;


    while (true)
    {

        circles.clear();
        ps.clear();
        dirs.clear();

        //生成极端情况的圆
        //Util::generate_circles(circles, 1000, 10, 1.f, 2000.f, 2000.f);
        //生成均匀分布的圆
        Util::generate_circles(circles, 1, 10, 1.f);
        //生成聚合圆
        //Util::generate_circles(circles, 1000, 10, 1000);
        Util::generate_dirs(dirs, 1);

        Grid g;
        g.init(circles, sqrt(100));

        Util::generate_os(&g, ps);

        float a1, b1, dx, dy;
        std::vector<Vector>::iterator it1 = ps.begin();
        for (; it1 != ps.end(); ++it1)
        {
            Vector vo = *it1;
            std::vector<Vector>::iterator it2 = dirs.begin();
            for (; it2 != dirs.end(); ++it2)
            {
                Vector vd = *it2;
                a1 = vo.x;
                b1 = vo.y;
                Vector o(a1, b1);
                dx = vd.x;
                dy = vd.y;
                Vector dir(dx, dy);
                bool b = false;
                timer.begin();
                Vector vv = Util::get_first_intersection(circles, o, dir, b);
                timer.end();
                double t1 = timer.get_time();
                timer.begin();
                Vector v = g.hit(dir, o);
                timer.end();
                double t2 = timer.get_time();

                //统计数据
                tn++;
                if (t1 < t2)
                {
                    ln++;
                }
                else
                {
                    int times;
                    ntimes++;

                    if (t2 < 0.00001)
                        times = 10000;
                    else
                        times = t1 / t2;

                    if (times > max_times)
                        max_times = times;

                    total_times += times;

                    if (t2<0.0001)
                        data1[19]++;
                    else
                        data1[times / 100]++;
                }

                //输出错误
                if (!Vector::is_nearly_eq(v, vv))
                {
                    en++;
                    vv.out();
                    v.out();
                    std::cout << "Wrong!\n";
                    getchar();
                }
            }


        }
        std::cout << "Done!\n" << ln<<","<< tn <<","<<ln / tn << std::endl;
        std::cout << "max:" << max_times << std::endl << "avg:" << total_times / ntimes << std::endl;
        for (int i = 0; i<20; i++)
        {
            std::cout << data1[i] << " ";
            data1[i] = 0;
        }
        //data1.clear();
        max_times = 0;
        avg_times = 0;
        total_times = 0;
        ntimes = 0;
        std::cout << std::endl;



        ln = 0;
        tn = 0;
        en = 0;

        std::vector<Circle*>::iterator it = circles.begin();
        for (; it!=circles.end(); ++it)
        {
            Circle* c = *it;
            delete c;
        }
        std::vector<Circle*>().swap(circles);
        std::vector<Vector>().swap(ps);
        std::vector<Vector>().swap(dirs);
        g.clear();
    }
    std::vector<int>().swap(data1);
    getchar();
    return 0;




}
Example #16
0
void f0_test(char16 c16, longlong16 ll16, char16_e c16e, longlong16_e ll16e) {
    f0(c16);
    f0(ll16);
    f0(c16e);
    f0(ll16e);
}
Example #17
0
int main(void) {
        f0();
    f1();
    f2();
    f3();
    f4();
    f5();
    f6();
    f7();
    f8();
    f9();
    f10();
    f11();
    f12();
    f13();
    f14();
    f15();
    f16();
    f17();
    f18();
    f19();
    f20();
    f21();
    f22();
    f23();
    f24();
    f25();
    f26();
    f27();
    f28();
    f29();
    f30();
    f31();
    f32();
    f33();
    f34();
    f35();
    f36();
    f37();
    f38();
    f39();
    f40();
    f41();
    f42();
    f43();
    f44();
    f45();
    f46();
    f47();
    f48();
    f49();
    f50();
    f51();
    f52();
    f53();
    f54();
    f55();
    f56();
    f57();
    f58();
    f59();
    f60();
    f61();
    f62();
    f63();
    f64();
    f65();
    f66();
    f67();
    f68();
    f69();
    f70();
    f71();
    f72();
    f73();
    f74();
    f75();
    f76();
    f77();
    f78();
    f79();
    f80();
    f81();
    f82();
    f83();
    f84();
    f85();
    f86();
    f87();
    f88();
    f89();
    f90();
    f91();
    f92();
    f93();
    f94();


    return 0;
}
void g0() {
  f0(); // okay!
} 
//// EPS09LO, EPS09NLO, nCTEQ15
void comp_RpPb_pt_Lansberg(double ptmax=32, bool isLine=true, bool isSmoothened=false, TString szPDF= "nCTEQ15")
{
	gROOT->Macro("./tdrstyle_kyo.C");
	int isPA = 10;  // 0:pp, 1:pPb, 10 : pp & pPb together for RpPb plot
	int iPos=0;

  bool isPrompt=true;
	
  ///////////////////////////////////////////////////
	///////// from Ramona
	const int nRapRpPb = 7;
	//const int nPtRpPb = 49;
	const int nPtRpPb = 7; // 4, 5, 6.5, 7.5, 8.5, 10, 14,  30 GeV
  Double_t theory_px[nRapRpPb][nPtRpPb]; 
	Double_t theory_py[nRapRpPb][nPtRpPb];
	Double_t theory_exlow_tmp[nRapRpPb][nPtRpPb];
	Double_t theory_exhigh_tmp[nRapRpPb][nPtRpPb];
  Double_t theory_exlow[nRapRpPb][nPtRpPb];
  Double_t theory_exhigh[nRapRpPb][nPtRpPb];
	Double_t theory_eylow_tmp[nRapRpPb][nPtRpPb];
	Double_t theory_eyhigh_tmp[nRapRpPb][nPtRpPb];
  Double_t theory_eylow[nRapRpPb][nPtRpPb];
	Double_t theory_eyhigh[nRapRpPb][nPtRpPb];
  Double_t ptlimit[nRapRpPb] = {4.0, 6.5, 6.5, 6.5, 6.5, 5.0, 4.0};
  int ipt_init[nRapRpPb] = {0, 2, 2, 2, 2, 1, 0}; // take into acount different pT limit for each rapidity bin (0=4.0, 1=5.0, 2=6.5 GeV)
  
  ///////////////////////////////////////////////////////////////////
  //// read-in txt
  ///////////////////////////////////////////////////////////////////
  
  /// iy=0 (1.5 < y < 1.93) 
  TString inText[nRapRpPb];
  for (int iy=0; iy<nRapRpPb; iy++) {
    inText[iy] = Form("./fromLansberg/pt_%1d_%s.dat",iy+1,szPDF.Data());
    cout << "inText["<<iy<<"] = " << inText[iy] << endl;
  }
  
  string headers;
  TString pxmindum, pxmaxdum, ppbdum, eylow_tmpdum, eyhigh_tmpdum, ppdum;
  int counts=0;
  
  for (int iy=0; iy<nRapRpPb; iy++) {
    cout << endl << " ************* iy = " << iy << endl;
    std::ifstream f0(inText[iy].Data(),std::ios::in);
    getline(f0, headers); // remove prefix
    getline(f0, headers); // remove prefix
    counts=0;
    while(!f0.eof()) {
      f0 >> pxmindum >> pxmaxdum >> ppbdum >> eylow_tmpdum >> eyhigh_tmpdum >> ppdum;
      //cout << pxmindum <<"\t"<< pxmaxdum <<"\t"<< ppbdum <<"\t"<< eylow_tmpdum <<"\t"<< eyhigh_tmpdum<<"\t"<< ppdum << endl;
      theory_px[iy][counts+ipt_init[iy]] =(atof(pxmindum) + atof(pxmaxdum))/2.;
      theory_py[iy][counts+ipt_init[iy]] = (atof(ppbdum) / atof(ppdum) );
      theory_exlow_tmp[iy][counts+ipt_init[iy]] = atof(pxmindum);
      theory_exhigh_tmp[iy][counts+ipt_init[iy]] = atof(pxmaxdum);
      theory_eylow_tmp[iy][counts+ipt_init[iy]] = ( atof(eylow_tmpdum) / atof(ppdum) );
      theory_eyhigh_tmp[iy][counts+ipt_init[iy]] = ( atof(eyhigh_tmpdum) / atof(ppdum) );
      counts++;
      //cout << "counts = " << counts << endl;
    } //end of while file open
  } 
 
  /////////////////////////////////////////////////////////////////////////////////
  
  //// set unused values as zero 
  for (int iy = 0 ; iy < nRapRpPb; iy ++ ) {
    for (Int_t ipt=nPtRpPb-1; ipt>=0; ipt--) {
      if (ipt <ipt_init[iy]) {
        theory_px[iy][ipt] = theory_px[iy][ipt+1];
        theory_py[iy][ipt] = theory_py[iy][ipt+1];
        theory_exlow_tmp[iy][ipt] = theory_exlow_tmp[iy][ipt+1];
        theory_exhigh_tmp[iy][ipt] = theory_exhigh_tmp[iy][ipt+1];
        theory_eylow_tmp[iy][ipt] = theory_eylow_tmp[iy][ipt+1];
        theory_eyhigh_tmp[iy][ipt] = theory_eyhigh_tmp[iy][ipt+1];
      }
    }
  }

  //// set proper ex and ey
  for (int iy = 0 ; iy < nRapRpPb; iy ++ ) {
    cout << endl << " ************* iy = " << iy << endl;
    for (Int_t ipt=0; ipt<nPtRpPb; ipt++) {
		  theory_exlow[iy][ipt] = fabs(theory_px[iy][ipt] - theory_exlow_tmp[iy][ipt]);
		  theory_exhigh[iy][ipt] = fabs(theory_px[iy][ipt] - theory_exhigh_tmp[iy][ipt]);
      //theory_exlow[iy][ipt] = 0.5;
      //theory_exhigh[iy][ipt] = 0.5;
		  theory_eylow[iy][ipt] = fabs(theory_py[iy][ipt] - theory_eylow_tmp[iy][ipt]);
		  theory_eyhigh[iy][ipt] = fabs(theory_py[iy][ipt] - theory_eyhigh_tmp[iy][ipt]);
      cout << "theory_px = " << theory_px[iy][ipt] << ", theory_py = " << theory_py[iy][ipt] << endl; 	
      cout << "theory_eylow_tmp = " << theory_eylow_tmp[iy][ipt] <<", theory_eyhigh_tmp = " << theory_eyhigh_tmp[iy][ipt] << endl; 	
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////////////
  
  TGraphAsymmErrors* g_RpPb_theory[nRapRpPb];
  for (int iy = 0 ; iy < nRapRpPb; iy ++ ) {
    g_RpPb_theory[iy]= new TGraphAsymmErrors(nPtRpPb, theory_px[iy], theory_py[iy], theory_exlow[iy], theory_exhigh[iy], theory_eylow[iy], theory_eyhigh[iy]);	
    g_RpPb_theory[iy]->SetName(Form("g_RpPb_theory_%d",iy));
  }
 /* 
  for (int iy=0; iy<nRapRpPb; iy++) {
	  g_RpPb_theory_dummy[iy]->GetXaxis()->SetLimits(0.,ptmax);
	  g_RpPb_theory_dummy[iy]->SetMinimum(0.0);
	  g_RpPb_theory_dummy[iy]->SetMaximum(1.8);
    g_RpPb_theory_dummy[iy]->GetXaxis()->SetTitle("p_{T} [GeV/c]");
    g_RpPb_theory_dummy[iy]->GetXaxis()->CenterTitle();
    g_RpPb_theory_dummy[iy]->GetYaxis()->SetTitle("R_{FB}");
    g_RpPb_theory_dummy[iy]->GetYaxis()->CenterTitle();
    //g_RpPb_theory_dummy[iy]->SetFillColorAlpha(kYellow,0.5);
    g_RpPb_theory_dummy[iy]->SetFillColorAlpha(kWhite,0.5);
	  //g_RpPb_theory_dummy[iy]->SetLineColor(kOrange+7);
	  //g_RpPb_theory_dummy[iy]->SetFillStyle(3004);
    if(!isLine) g_RpPb_theory_dummy[iy]->SetLineWidth(0);
  }
 */ 
  
	///////////////////////////////////////////////////
  //////// experimental points	
  TFile *inFile = new TFile("../DrawFinalPlot/plot_RpPb/RpPb_pt_isPrompt1.root");
  
  TGraphAsymmErrors* g_RpPb_sys[nRapRpPb];
  TGraphAsymmErrors* g_RpPb[nRapRpPb];
  for (int iy = 0 ; iy < nRapRpPb; iy ++ ) {
    g_RpPb_sys[iy] = (TGraphAsymmErrors*)inFile->Get(Form("g_RpPb_sys_%d",iy));
    g_RpPb[iy] = (TGraphAsymmErrors*)inFile->Get(Form("g_RpPb_%d",iy));
  } 
  
	///////////////////////////////////////////////////
	//// Draw
  ///////////////////////////////////////////////////
  
  TCanvas* c_all = new TCanvas("c_all","c_all",1200,680);
  //CMS_lumi( c_all, isPA, iPos );
  c_all->Divide(5,2);
  const int nPad = 10;
  double xmargin = 0.00;
  double ymargin = 0.00;
  double xpad0 = 0.060;
  double xpadw = 0.233;
  TVirtualPad* pad_all[nPad]; // 2 pads for y axis, 8 pads for actual plots
  pad_all[0] = new TPad("pad_all_0", "",0, 0.506, xpad0, 1.0);
  pad_all[1] = new TPad("pad_all_1", "",xpad0, 0.506, xpad0+xpadw, 1.0);
  pad_all[2] = new TPad("pad_all_2", "",xpad0+xpadw, 0.506, xpad0+2*xpadw, 1.0);
  pad_all[3] = new TPad("pad_all_3", "",xpad0+2*xpadw, 0.506, xpad0+3*xpadw, 1.0);
  pad_all[4] = new TPad("pad_all_4", "",xpad0+3*xpadw, 0.506, xpad0+4*xpadw, 1.0);
  pad_all[5] = new TPad("pad_all_5", "",0, 0.0, xpad0, 0.506);
  pad_all[6] = new TPad("pad_all_6", "",xpad0, 0.0, xpad0+xpadw, 0.506);
  pad_all[7] = new TPad("pad_all_7", "",xpad0+xpadw, 0.0, xpad0+2*xpadw, 0.506);
  pad_all[8] = new TPad("pad_all_8", "",xpad0+2*xpadw, 0.0, xpad0+3*xpadw, 0.506);
  pad_all[9] = new TPad("pad_all_9", "",xpad0+3*xpadw, 0.0, xpad0+4*xpadw, 0.506);
  
  double topmargin = 0.14;
  double bottommargin = 0.161;
  for (Int_t iy = 0; iy < nPad; iy++) { 
    pad_all[iy]->Draw();
    if (iy<=4) { 
      pad_all[iy]->SetTopMargin(topmargin); 
      pad_all[iy]->SetBottomMargin(0.0); 
    }
    else { 
      pad_all[iy]->SetTopMargin(0.0); 
      pad_all[iy]->SetBottomMargin(bottommargin); 
    }
    pad_all[iy]->SetLeftMargin(0.0);
    pad_all[iy]->SetRightMargin(0.0);
  }
  
  for (int iy=0; iy<nRapRpPb; iy++) {
    if (iy==0) pad_all[3]->cd();
    else if (iy==1) pad_all[2]->cd();
    else if (iy==2) pad_all[1]->cd();
    else pad_all[iy+3]->cd();
    g_RpPb_sys[iy]->Draw("A5");
	  g_RpPb_theory[iy]->GetXaxis()->SetLimits(ptlimit[iy],ptmax);
	  //g_RpPb_theory[iy]->SetRange(ptlimit[iy],ptmax);
    //g_RpPb_theory[iy]->SetFillColorAlpha(kGray,0.5);
    g_RpPb_theory[iy]->SetFillColorAlpha(kYellow,0.5);
	  g_RpPb_theory[iy]->SetLineColor(kOrange+7);
    g_RpPb[iy]->Draw("p");
    if (isSmoothened) g_RpPb_theory[iy]->Draw("3");
    else g_RpPb_theory[iy]->Draw("5");
    dashedLine(0.,1.,32.,1.,1,1);
  }
    
  c_all->SaveAs(Form("plot_theory/comp_RpPb_pt_isSmoothened%d_Lansberg_%s.pdf",(int)isSmoothened,szPDF.Data()));
  c_all->SaveAs(Form("plot_theory/comp_RpPb_pt_isSmoothened%d_Lansberg_%s.png",(int)isSmoothened,szPDF.Data()));
 
  ///////////////////////////////////////////////////////////////////
  // save as a root file
  TFile* outFile = new TFile(Form("plot_theory/comp_RpPb_pt_isSmoothened%d_Lansberg_%s.root",(int)isSmoothened,szPDF.Data()),"RECREATE");
  outFile->cd();
  for (int iy = 0 ; iy < nRapRpPb; iy ++ ) {
    g_RpPb_theory[iy]->Write();
  } 
  
  return;
}
Example #20
0
int f1(int a, int b) {
  // f0 is called on line 48
  return f0(a, b);
}
Example #21
0
int main(void) {
        f0();


    return 0;
}
void test() {
  f0(1); // expected-error {{'f0' is unavailable: not available on}}
  f1(1); // expected-error {{'f1' is unavailable}}
}
Example #23
0
void
IntlTestNumberFormatAPI::testRegistration()
{
#if !UCONFIG_NO_SERVICE
    UErrorCode status = U_ZERO_ERROR;

    LocalPointer<NumberFormat> f0(NumberFormat::createInstance(SWAP_LOC, status));
    LocalPointer<NumberFormat> f1(NumberFormat::createInstance(SRC_LOC, status));
    LocalPointer<NumberFormat> f2(NumberFormat::createCurrencyInstance(SRC_LOC, status));
    URegistryKey key = NumberFormat::registerFactory(new NFTestFactory(), status);
    LocalPointer<NumberFormat> f3(NumberFormat::createCurrencyInstance(SRC_LOC, status));
    LocalPointer<NumberFormat> f3a(NumberFormat::createCurrencyInstance(SRC_LOC, status));
    LocalPointer<NumberFormat> f4(NumberFormat::createInstance(SRC_LOC, status));

    StringEnumeration* locs = NumberFormat::getAvailableLocales();

    LocalUNumberFormatPointer uf3(unum_open(UNUM_CURRENCY, NULL, 0, SRC_LOC.getName(), NULL, &status));
    LocalUNumberFormatPointer uf4(unum_open(UNUM_DEFAULT, NULL, 0, SRC_LOC.getName(), NULL, &status));

    const UnicodeString* res;
    for (res = locs->snext(status); res; res = locs->snext(status)) {
        logln(*res); // service is still in synch
    }

    NumberFormat::unregister(key, status); // restore for other tests
    LocalPointer<NumberFormat> f5(NumberFormat::createCurrencyInstance(SRC_LOC, status));
    LocalUNumberFormatPointer uf5(unum_open(UNUM_CURRENCY, NULL, 0, SRC_LOC.getName(), NULL, &status));

    if (U_FAILURE(status)) {
        dataerrln("Error creating instnaces.");
        return;
    } else {
        float n = 1234.567f;
        UnicodeString res0, res1, res2, res3, res4, res5;
        UChar ures3[50];
        UChar ures4[50];
        UChar ures5[50];

        f0->format(n, res0);
        f1->format(n, res1);
        f2->format(n, res2);
        f3->format(n, res3);
        f4->format(n, res4);
        f5->format(n, res5);

        unum_formatDouble(uf3.getAlias(), n, ures3, 50, NULL, &status);
        unum_formatDouble(uf4.getAlias(), n, ures4, 50, NULL, &status);
        unum_formatDouble(uf5.getAlias(), n, ures5, 50, NULL, &status);

        logln((UnicodeString)"f0 swap int: " + res0);
        logln((UnicodeString)"f1 src int: " + res1);
        logln((UnicodeString)"f2 src cur: " + res2);
        logln((UnicodeString)"f3 reg cur: " + res3);
        logln((UnicodeString)"f4 reg int: " + res4);
        logln((UnicodeString)"f5 unreg cur: " + res5);
        log("uf3 reg cur: ");
        logln(ures3);
        log("uf4 reg int: ");
        logln(ures4);
        log("uf5 ureg cur: ");
        logln(ures5);

        if (f3.getAlias() == f3a.getAlias()) {
            errln("did not get new instance from service");
            f3a.orphan();
        }
        if (res3 != res0) {
            errln("registered service did not match");
        }
        if (res4 != res1) {
            errln("registered service did not inherit");
        }
        if (res5 != res2) {
            errln("unregistered service did not match original");
        }

        if (res0 != ures3) {
            errln("registered service did not match / unum");
        }
        if (res1 != ures4) {
            errln("registered service did not inherit / unum");
        }
        if (res2 != ures5) {
            errln("unregistered service did not match original / unum");
        }
    }

    for (res = locs->snext(status); res; res = locs->snext(status)) {
        errln(*res); // service should be out of synch
    }

    locs->reset(status); // now in synch again, we hope
    for (res = locs->snext(status); res; res = locs->snext(status)) {
        logln(*res);
    }

    delete locs;
#endif
}
Example #24
0
void test() {
  int &ir = f0(1.0); // okay: f0() from 'right' is not visible
}
bool AnchoredRectangleHandler::initFeature(const std::string& sensor,
    const Eigen::VectorXd& z, ROAMestimation::PoseVertexWrapper_Ptr pv,
    long int id) {

  const Eigen::VectorXd &anchor_frame = pv->getEstimate();
  Eigen::VectorXd dim0(2), f0(7), foq0(4), fohp0(3);

  initRectangle(anchor_frame, _lambda, z, dim0, fohp0, foq0);

  _filter->addSensor(sensor, AnchoredRectangularObject, false, false);
  _filter->shareSensorFrame("Camera", sensor);
  _filter->shareParameter("Camera_CM", sensor + "_CM");

  _filter->addConstantParameter(Euclidean2D, sensor + "_Dim", 0.0, dim0, false);

  _filter->poseVertexAsParameter(pv, sensor + "_F");

  _filter->addConstantParameter(Quaternion, sensor + "_FOq", pv->getTimestamp(),
      foq0, false);

  _filter->addConstantParameter(Euclidean3D, sensor + "_FOhp",
      pv->getTimestamp(), fohp0, false);

  // add the sensor for the first edge only

  std::string sensor_first = sensor + "_first";

  _filter->addSensor(sensor_first, AnchoredRectangularObjectFirst, false,
      false);
  _filter->shareSensorFrame("Camera", sensor_first);

  _filter->shareParameter("Camera_CM", sensor_first + "_CM");
  _filter->shareParameter(sensor + "_Dim", sensor_first + "_Dim");
  _filter->shareParameter(sensor + "_FOq", sensor_first + "_FOq");
  _filter->shareParameter(sensor + "_FOhp", sensor_first + "_FOhp");

  /* prior on homogeneous point
   const double sigma_pixel = 1;

   Eigen::MatrixXd prior_cov(3, 3);

   prior_cov << sigma_pixel / pow(_fx, 2), 0, 0, 0, sigma_pixel / pow(_fy, 2), 0, 0, 0, pow(
   _lambda / 3.0, 2);

   _filter->addPriorOnConstantParameter(Euclidean3DPrior, sensor + "_FOhp",
   fohp0, prior_cov);
   //*/

  //add to current track list
  ObjectTrackDescriptor &d = _objects[id];

  d.anchorFrame = pv;
  d.isInitialized = false;
  d.initStrategy = new ObjectSufficientParallax(0.2, d.zHistory, _K.data());

  //_filter->setRobustKernel(sensor, true, 3.0);

  cerr << "[AnchoredRectangleHandler] New rectangle, id " << id << endl;

  return true;
}
Example #26
0
int mri(
		float* img, 
		float complex* f, 
		float* mask, 
		float lambda,
		int N1,
		int N2)
{
	int i, j;

    // Use this to check the output of each API call
    cl_int status;

    // Retrieve the number of platforms
    cl_uint numPlatforms = 0;
    status = clGetPlatformIDs(0, NULL, &numPlatforms);

    // Allocate enough space for each platform
    cl_platform_id *platforms = NULL;
    platforms = (cl_platform_id*)malloc(
        numPlatforms*sizeof(cl_platform_id));

    // Fill in the platforms
    status = clGetPlatformIDs(numPlatforms, platforms, NULL);
    // Retrieve the number of devices
    cl_uint numDevices = 0;
    status = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_ALL, 0,
        NULL, &numDevices);

    // Allocate enough space for each device
    cl_device_id *devices;
    devices = (cl_device_id*)malloc(
        numDevices*sizeof(cl_device_id));

    // Fill in the devices
    status = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_ALL,
        numDevices, devices, NULL);

    // Create a context and associate it with the devices
    cl_context context;
    context = clCreateContext(NULL, numDevices, devices, NULL,
        NULL, &status);

    // Create a command queue and associate it with the device
    cl_command_queue cmdQueue;
    cmdQueue = clCreateCommandQueue(context, devices[0], 0,
        &status);

    // Create a buffer object that will contain the data
    // from the host array A
        
	float complex* f0	    = (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* dx	    = (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* dy	    = (float complex*) calloc(N1*N2,sizeof(float complex));

	float complex* dx_new   = (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* dy_new   = (float complex*) calloc(N1*N2,sizeof(float complex));

	float complex* dtildex	= (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* dtildey	= (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* u_fft2	= (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* u		= (float complex*) calloc(N1*N2,sizeof(float complex));

	float complex* fftmul	= (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* Lap		= (float complex*) calloc(N1*N2,sizeof(float complex));
	float complex* diff		= (float complex*) calloc(N1*N2,sizeof(float complex));
    float complex *w1 = (float complex*)malloc(((N2-1)*(N2-1)+1)*sizeof(float complex));
	float complex *w2 = (float complex*)malloc(((N1-1)*(N1-1)+1)*sizeof(float complex));
	float complex *buff = (float complex*)malloc(N2*N1*sizeof(float complex));
       
    Lap(N1-1, N2-1)	= 0.f;
	Lap(N1-1, 0)	= 1.f; 
	Lap(N1-1, 1)	= 0.f;
	Lap(0, N2-1)	= 1.f;
	Lap(0, 0)		= -4.f; 
	Lap(0, 1)		= 1.f;
	Lap(1, N2-1)	= 0.f;
	Lap(1, 0)		= 1.f; 
	Lap(1, 1)		= 0.f;

    cl_mem cl_img = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(float), NULL, &status);
    cl_mem cl_mask = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(float), NULL, &status);
    cl_mem cl_f = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
    cl_mem cl_f0 = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_dx = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_dy = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);

	cl_mem cl_dx_new = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_dy_new = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);

	cl_mem cl_dtildex = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_dtildey = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_u_fft2 = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_u = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);

	cl_mem cl_fftmul = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_Lap = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
	cl_mem cl_diff = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);
    
    cl_mem cl_w1 = clCreateBuffer(context, CL_MEM_READ_WRITE, (N2*N2)*sizeof(cl_float2), NULL, &status);
    cl_mem cl_w2 = clCreateBuffer(context, CL_MEM_READ_WRITE, (N1*N1)*sizeof(cl_float2), NULL, &status);
    cl_mem cl_buff = clCreateBuffer(context, CL_MEM_READ_WRITE, N1*N2*sizeof(cl_float2), NULL, &status);

    status = clEnqueueWriteBuffer(cmdQueue, cl_mask, CL_FALSE, 0, N1*N2*sizeof(float), mask, 0, NULL, NULL);
    status = clEnqueueWriteBuffer(cmdQueue, cl_f, CL_FALSE, 0, N1*N2*sizeof(cl_float2), f, 0, NULL, NULL);
    status = clEnqueueWriteBuffer(cmdQueue, cl_Lap, CL_FALSE, 0, N1*N2*sizeof(cl_float2), Lap, 0, NULL, NULL);
        
	cl_program program = clCreateProgramWithSource(context, 1, 
        (const char**)&kernel, NULL, &status);
        
    status = clBuildProgram(program, numDevices, devices, NULL, NULL, NULL);
	cl_kernel ker;
	size_t globalWorkSize[2]={N1,N2};
	
	float sum = 0;

	for(i=0; i<N1; i++)
		for(j=0; j<N2; j++)
			sum += (SQR(crealf(f(i,j))/N1) + SQR(cimagf(f(i,j))/N1));
            
	float normFactor = 1.f/sqrtf(sum);
	float scale		 = sqrtf(N1*N2);

    ker = clCreateKernel(program, "loop1", &status);

    
    status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_f);
    status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_f0);
    status = clSetKernelArg(ker, 2, sizeof(cl_float2), &normFactor);
    status = clSetKernelArg(ker, 3, sizeof(int), &N1);
    status = clSetKernelArg(ker, 4, sizeof(int), &N2);
    
    
    
    
    status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
    w1[0] = 1;
	w2[0] = 1;
	dft_init(&w1, &w2, &buff, N1, N2);
    status = clEnqueueWriteBuffer(cmdQueue, cl_w1, CL_FALSE, 0, ((N2-1)*(N2-1)+1)*sizeof(cl_float2), w1, 0, NULL, NULL);
    status = clEnqueueWriteBuffer(cmdQueue, cl_w2, CL_FALSE, 0, ((N1-1)*(N1-1)+1)*sizeof(cl_float2), w2, 0, NULL, NULL);
    status = clEnqueueWriteBuffer(cmdQueue, cl_buff, CL_FALSE, 0, N1*N2*sizeof(cl_float2), buff, 0, NULL, NULL);

    ker = clCreateKernel(program, "dft1", &status);
    status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_Lap);
    status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_Lap);
    status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_w1);
    status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_w2);
    status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_buff);
    status = clSetKernelArg(ker, 5, sizeof(int), &N1);
    status = clSetKernelArg(ker, 6, sizeof(int), &N2);
    status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
                   if (status != CL_SUCCESS)
            	printf("error: %d\n", status); 
    ker = clCreateKernel(program, "dft2", &status);
    status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_Lap);
    status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_Lap);
    status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_w1);
    status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_w2);
    status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_buff);
    status = clSetKernelArg(ker, 5, sizeof(int), &N1);
    status = clSetKernelArg(ker, 6, sizeof(int), &N2);
    status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL); 
               if (status != CL_SUCCESS)
            	printf("error: %d\n", status); 
    ker = clCreateKernel(program, "loop2", &status);
    status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_fftmul);
    status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_Lap);
    status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_mask);
    status = clSetKernelArg(ker, 3, sizeof(float), &lambda);
    status = clSetKernelArg(ker, 4, sizeof(int), &N1);
    status = clSetKernelArg(ker, 5, sizeof(int), &N2);
    status = clEnqueueNDRangeKernel(cmdQueue, ker,2, NULL, globalWorkSize, NULL, 0, NULL, NULL);    
    
    float complex *tmp = (float complex*)malloc(N2*N1*sizeof(float complex));
    float complex *tmp2 = (float complex*)malloc(N2*N1*sizeof(float complex));
    
    
    
	int OuterIter,iter;
	for(OuterIter= 0; OuterIter<MaxOutIter; OuterIter++) {
		for(iter = 0; iter<MaxIter; iter++) {
            ker = clCreateKernel(program, "loop3", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_diff);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_dtildex);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_dtildey);
            status = clSetKernelArg(ker, 3, sizeof(int), &N1);
            status = clSetKernelArg(ker, 4, sizeof(int), &N2);

            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL); 

            ker = clCreateKernel(program, "dft1", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_diff);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_diff);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_w1);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_w2);
            status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_buff);
            status = clSetKernelArg(ker, 5, sizeof(int), &N1);
            status = clSetKernelArg(ker, 6, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
             if (status != CL_SUCCESS)
            	printf("error: %d\n", status);
            	
            ker = clCreateKernel(program, "dft2", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_diff);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_diff);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_w1);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_w2);
            status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_buff);
            status = clSetKernelArg(ker, 5, sizeof(int), &N1);
            status = clSetKernelArg(ker, 6, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL); 
            if (status != CL_SUCCESS)
            	printf("error: %d\n", status);
			//dft(diff, diff, w1, w2, buff, N1, N2);

            
            ker = clCreateKernel(program, "loop4", &status);
            int more = (iter == MaxIter - 1);

            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_fftmul);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_f);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_diff);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_u_fft2);
            status = clSetKernelArg(ker, 4, sizeof(int), &N1);
            status = clSetKernelArg(ker, 5, sizeof(int), &N2);
            status = clSetKernelArg(ker, 6, sizeof(float), &scale);
            status = clSetKernelArg(ker, 7, sizeof(float), &lambda);
            status= clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL); 
            
            ker = clCreateKernel(program, "idft1", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_u);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_u_fft2);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_w1);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_w2);
            status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_buff);
            status = clSetKernelArg(ker, 5, sizeof(int), &N1);
            status = clSetKernelArg(ker, 6, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
            
            ker = clCreateKernel(program, "idft2", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_u);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_u_fft2);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_w1);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_w2);
            status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_buff);
            status = clSetKernelArg(ker, 5, sizeof(int), &N1);
            status = clSetKernelArg(ker, 6, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
            
         
            ker = clCreateKernel(program, "loop5", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_dx);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_dy);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_u);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_dtildex);
            status = clSetKernelArg(ker, 4, sizeof(cl_mem), &cl_dtildey);
            status = clSetKernelArg(ker, 5, sizeof(cl_mem), &cl_dx_new);
            status = clSetKernelArg(ker, 6, sizeof(cl_mem), &cl_dy_new);
            status = clSetKernelArg(ker, 7, sizeof(int), &N1);
            status = clSetKernelArg(ker, 8, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);

            
		}
        /*
          ker = clCreateKernel(program, "last_loop", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_f);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_f0);
            status = clSetKernelArg(ker, 2, sizeof(cl_mem), &cl_mask);
            status = clSetKernelArg(ker, 3, sizeof(cl_mem), &cl_u_fft2);
            status = clSetKernelArg(ker, 4, sizeof(float), &scale);
            status = clSetKernelArg(ker, 5, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
          if (status != CL_SUCCESS)
            	printf("error: %d\n", status);
          
          */
        clEnqueueReadBuffer(cmdQueue, cl_f, CL_TRUE, 0, N1*N2*sizeof(float), f, 0, NULL, NULL);    
        clEnqueueReadBuffer(cmdQueue, cl_f0, CL_TRUE, 0, N1*N2*sizeof(float), f0, 0, NULL, NULL);
        clEnqueueReadBuffer(cmdQueue, cl_u_fft2, CL_TRUE, 0, N1*N2*sizeof(float), u_fft2, 0, NULL, NULL);
        
        for(i=0;i<N1;i++) {
			for(j=0;j<N2;j++) {
				f(i,j) += f0(i,j) - mask(i,j)*u_fft2(i,j)/scale;  
			}
		}
        
        clEnqueueWriteBuffer(cmdQueue, cl_f, CL_TRUE, 0, N1*N2*sizeof(float), f, 0, NULL, NULL);
        
       
	}
    
    
            ker = clCreateKernel(program, "loop7", &status);
            status = clSetKernelArg(ker, 0, sizeof(cl_mem), &cl_img);
            status = clSetKernelArg(ker, 1, sizeof(cl_mem), &cl_u);
            status = clSetKernelArg(ker, 2, sizeof(int), &N1);
            status = clSetKernelArg(ker, 3, sizeof(int), &N2);
            status = clEnqueueNDRangeKernel(cmdQueue, ker, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL); 


    clEnqueueReadBuffer(cmdQueue, cl_img, CL_TRUE, 0, N1*N2*sizeof(float), img, 0, NULL, NULL);
    clReleaseKernel(ker);
    clReleaseProgram(program);
    clReleaseCommandQueue(cmdQueue);
    clReleaseMemObject(cl_img);
    clReleaseMemObject(cl_mask);
    clReleaseMemObject(cl_f);
    clReleaseMemObject(cl_f0);
    clReleaseMemObject(cl_dx);
    clReleaseMemObject(cl_dy);
    clReleaseMemObject(cl_dx_new);
    clReleaseMemObject(cl_dy_new);
    clReleaseMemObject(cl_dtildex);
    clReleaseMemObject(cl_dtildey);
    clReleaseMemObject(cl_u_fft2);
    clReleaseMemObject(cl_u);
    clReleaseMemObject(cl_fftmul);
    clReleaseMemObject(cl_Lap);
    clReleaseMemObject(cl_diff);
    clReleaseMemObject(cl_w1);
    clReleaseMemObject(cl_w2);
    clReleaseMemObject(cl_buff);
    
    clReleaseContext(context);
    free(platforms);
    free(devices);
	free(w1);
	free(w2);
	free(buff);
	return 0;
}
Example #27
0
int main(void) {
        f0();
    f1();
    f2();
    f3();
    f4();
    f5();
    f6();
    f7();
    f8();
    f9();
    f10();
    f11();
    f12();
    f13();
    f14();
    f15();
    f16();
    f17();
    f18();
    f19();
    f20();
    f21();
    f22();
    f23();
    f24();
    f25();
    f26();
    f27();
    f28();
    f29();
    f30();
    f31();
    f32();
    f33();
    f34();
    f35();
    f36();
    f37();
    f38();
    f39();
    f40();
    f41();
    f42();
    f43();
    f44();
    f45();
    f46();
    f47();
    f48();
    f49();
    f50();
    f51();
    f52();
    f53();
    f54();
    f55();
    f56();
    f57();
    f58();
    f59();
    f60();
    f61();
    f62();
    f63();
    f64();
    f65();
    f66();
    f67();
    f68();
    f69();
    f70();
    f71();
    f72();
    f73();
    f74();
    f75();
    f76();
    f77();
    f78();
    f79();
    f80();
    f81();
    f82();
    f83();
    f84();
    f85();
    f86();
    f87();
    f88();
    f89();
    f90();
    f91();
    f92();
    f93();
    f94();
    f95();
    f96();
    f97();
    f98();
    f99();
    f100();
    f101();
    f102();
    f103();
    f104();
    f105();
    f106();
    f107();
    f108();
    f109();
    f110();
    f111();
    f112();
    f113();
    f114();
    f115();
    f116();
    f117();
    f118();
    f119();
    f120();
    f121();
    f122();
    f123();
    f124();
    f125();
    f126();
    f127();
    f128();
    f129();
    f130();
    f131();
    f132();
    f133();
    f134();
    f135();
    f136();
    f137();
    f138();
    f139();
    f140();
    f141();
    f142();
    f143();
    f144();
    f145();
    f146();
    f147();
    f148();
    f149();
    f150();
    f151();
    f152();
    f153();
    f154();
    f155();
    f156();
    f157();
    f158();
    f159();
    f160();
    f161();
    f162();
    f163();
    f164();
    f165();
    f166();
    f167();
    f168();
    f169();
    f170();
    f171();
    f172();
    f173();
    f174();
    f175();
    f176();
    f177();
    f178();
    f179();
    f180();
    f181();
    f182();
    f183();
    f184();
    f185();
    f186();
    f187();
    f188();
    f189();
    f190();
    f191();
    f192();
    f193();
    f194();
    f195();
    f196();
    f197();
    f198();
    f199();


    return 0;
}
Example #28
0
bool
WavFileWriter::writeModel(DenseTimeValueModel *source,
                          MultiSelection *selection)
{
    if (source->getChannelCount() != m_channels) {
        std::cerr << "WavFileWriter::writeModel: Wrong number of channels ("
                  << source->getChannelCount()  << " != " << m_channels << ")"
                  << std::endl;
        m_error = QString("Failed to write model to audio file '%1'")
                  .arg(m_path);
        return false;
    }

    if (!m_file) {
        m_error = QString("Failed to write model to audio file '%1': File not open")
                  .arg(m_path);
        return false;
    }

    bool ownSelection = false;
    if (!selection) {
        selection = new MultiSelection;
        selection->setSelection(Selection(source->getStartFrame(),
                                          source->getEndFrame()));
        ownSelection = true;
    }

    size_t bs = 2048;
    float *ub = new float[bs]; // uninterleaved buffer (one channel)
    float *ib = new float[bs * m_channels]; // interleaved buffer

    for (MultiSelection::SelectionList::iterator i =
                selection->getSelections().begin();
            i != selection->getSelections().end(); ++i) {

        size_t f0(i->getStartFrame()), f1(i->getEndFrame());

        for (size_t f = f0; f < f1; f += bs) {

            size_t n = std::min(bs, f1 - f);

            for (int c = 0; c < int(m_channels); ++c) {
                source->getData(c, f, n, ub);
                for (size_t i = 0; i < n; ++i) {
                    ib[i * m_channels + c] = ub[i];
                }
            }

            sf_count_t written = sf_writef_float(m_file, ib, n);

            if (written < n) {
                m_error = QString("Only wrote %1 of %2 frames at file frame %3")
                          .arg(written).arg(n).arg(f);
                break;
            }
        }
    }

    delete[] ub;
    delete[] ib;
    if (ownSelection) delete selection;

    return isOK();
}
Example #29
0
File: sha1.c Project: VVer/opal
void
sha1_final(sha1_ctx_t *ctx, uint32_t *output) {
  uint32_t A, B, C, D, E, TEMP;
  uint32_t W[80];  
  int i, t;

  /*
   * process the remaining octets_in_buffer, padding and terminating as
   * necessary
   */
  {
    int tail = ctx->octets_in_buffer % 4;
    
    /* copy/xor message into array */
    for (i=0; i < (ctx->octets_in_buffer+3)/4; i++) 
      W[i]  = be32_to_cpu(ctx->M[i]);

    /* set the high bit of the octet immediately following the message */
    switch (tail) {
    case (3):
      W[i-1] = (be32_to_cpu(ctx->M[i-1]) & 0xffffff00) | 0x80;
      W[i] = 0x0;
      break;
    case (2):      
      W[i-1] = (be32_to_cpu(ctx->M[i-1]) & 0xffff0000) | 0x8000;
      W[i] = 0x0;
      break;
    case (1):
      W[i-1] = (be32_to_cpu(ctx->M[i-1]) & 0xff000000) | 0x800000;
      W[i] = 0x0;
      break;
    case (0):
      W[i] = 0x80000000;
      break;
    }
    
    /* zeroize remaining words */
    for (i++   ; i < 15; i++)
      W[i] = 0x0;

    /* 
     * if there is room at the end of the word array, then set the
     * last word to the bit-length of the message; otherwise, set that
     * word to zero and then we need to do one more run of the
     * compression algo.
     */
    if (ctx->octets_in_buffer < 56) 
      W[15] = ctx->num_bits_in_msg;
    else if (ctx->octets_in_buffer < 60)
      W[15] = 0x0;

    /* process the word array */    for (t=16; t < 80; t++) {
      TEMP = W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16];
      W[t] = S1(TEMP);
    }

    A = ctx->H[0]; 
    B = ctx->H[1]; 
    C = ctx->H[2]; 
    D = ctx->H[3]; 
    E = ctx->H[4];

    for (t=0; t < 20; t++) {
      TEMP = S5(A) + f0(B,C,D) + E + W[t] + SHA_K0;
      E = D; D = C; C = S30(B); B = A; A = TEMP;
    }
    for (   ; t < 40; t++) {
      TEMP = S5(A) + f1(B,C,D) + E + W[t] + SHA_K1;
      E = D; D = C; C = S30(B); B = A; A = TEMP;
    }
    for (   ; t < 60; t++) {
      TEMP = S5(A) + f2(B,C,D) + E + W[t] + SHA_K2;
      E = D; D = C; C = S30(B); B = A; A = TEMP;
    }
    for (   ; t < 80; t++) {
      TEMP = S5(A) + f3(B,C,D) + E + W[t] + SHA_K3;
      E = D; D = C; C = S30(B); B = A; A = TEMP;
    }

    ctx->H[0] += A;
    ctx->H[1] += B;
    ctx->H[2] += C;
    ctx->H[3] += D;
    ctx->H[4] += E;

  }

  debug_print(mod_sha1, "(final) running sha1_core()", NULL);

  if (ctx->octets_in_buffer >= 56) {

    debug_print(mod_sha1, "(final) running sha1_core() again", NULL);

    /* we need to do one final run of the compression algo */

    /* 
     * set initial part of word array to zeros, and set the 
     * final part to the number of bits in the message
     */
    for (i=0; i < 15; i++)
      W[i] = 0x0;
    W[15] = ctx->num_bits_in_msg;

    /* process the word array */
    for (t=16; t < 80; t++) {
      TEMP = W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16];
      W[t] = S1(TEMP);
    }

    A = ctx->H[0]; 
    B = ctx->H[1]; 
    C = ctx->H[2]; 
    D = ctx->H[3]; 
    E = ctx->H[4];

    for (t=0; t < 20; t++) {
      TEMP = S5(A) + f0(B,C,D) + E + W[t] + SHA_K0;
      E = D; D = C; C = S30(B); B = A; A = TEMP;
    }
    for (   ; t < 40; t++) {
      TEMP = S5(A) + f1(B,C,D) + E + W[t] + SHA_K1;
      E = D; D = C; C = S30(B); B = A; A = TEMP;
    }
    for (   ; t < 60; t++) {
      TEMP = S5(A) + f2(B,C,D) + E + W[t] + SHA_K2;
      E = D; D = C; C = S30(B); B = A; A = TEMP;
    }
    for (   ; t < 80; t++) {
      TEMP = S5(A) + f3(B,C,D) + E + W[t] + SHA_K3;
      E = D; D = C; C = S30(B); B = A; A = TEMP;
    }

    ctx->H[0] += A;
    ctx->H[1] += B;
    ctx->H[2] += C;
    ctx->H[3] += D;
    ctx->H[4] += E;
  }

  /* copy result into output buffer */
  output[0] = be32_to_cpu(ctx->H[0]);
  output[1] = be32_to_cpu(ctx->H[1]);
  output[2] = be32_to_cpu(ctx->H[2]);
  output[3] = be32_to_cpu(ctx->H[3]);
  output[4] = be32_to_cpu(ctx->H[4]);

  /* indicate that message buffer in context is empty */
  ctx->octets_in_buffer = 0;

  return;
}
void regionalSegmentationModule::completeBlobs(std::vector<Blob> &blobs,
                                               QImage *fg, QImage *current) {

    int nbins = 256/m_bins;
    int i, j, w = fg->width(), h = fg->height();
    int i0, j0, w0, h0;
    double maxVal;

    QImage curr888 = current->convertToFormat(QImage::Format_RGB888);
    cv::Mat c(h, w, CV_8UC3), c_yuv(h, w, CV_8UC3),
            f(h, w, CV_8UC1), f0(h, w, CV_8UC1), r(h, w, CV_8UC3);

    int bl = fg->bytesPerLine(), bl2 = curr888.bytesPerLine();
    std::vector<Blob>::iterator it, it_end = blobs.end();
    uchar d1, d2, d3,
          *fg_p = fg->bits(),
          *c_p = curr888.bits();

    memcpy(c.data, c_p, h*bl2);
    memcpy(f.data, fg_p, h*bl);
    memset(c_yuv.data, 0, h*bl2);
    memset(r.data, 0, h*bl2);

    f.copyTo(f0);

    cv::Rect roi;
    //Histogram parameters
    int channels[] = {1, 2};
    int histSize[] = {nbins, nbins};
    float pranges[] = { 0, 256 };
    const float* ranges[] = { pranges, pranges };

    //Rectangular structuring element
    cv::Mat element = cv::getStructuringElement( cv::MORPH_RECT,
                                           cv::Size( 3, 3 ),
                                           cv::Point( 1, 1 ) );

    //Set local window pixel histogram for comparison
    cv::Rect wroi;
    wroi.width = wroi.height = w_size/2;

    m_data->hulls.clear();

    //Start blobs processing for hulls calculation
    for(it=blobs.begin(); it!=it_end; it++) {
        Blob &b = (*it);
        i0 = b.bbox.ytop, j0 = b.bbox.xleft,
        h0 = b.bbox.height, w0 = b.bbox.width;
        //Con la misma Mat f .....

        //Apertura en blob
        roi.x = j0;
        roi.y = i0;
        roi.width = w0;
        roi.height = h0;

        //Restrict operations to blob zone
        cv::Mat aux(f, roi);
        cv::Mat aux0(f0, roi);

        //Reduce bad detections, in general near borders
        cv::erode(aux, aux, element, cv::Point(-1,-1), 1);

        //Reduce bad detections, in general near borders and recover shape
        cv::erode(aux0, aux0, element, cv::Point(-1,-1), 1);
        cv::dilate(aux0, aux0, element, cv::Point(-1,-1), 1);

        //Border detection
        cv::Mat border_aux(aux.size(), CV_8UC1);
        cv::Canny(aux,border_aux, 50,100, 3);

#ifdef RSEG_DEBUG
        cv::namedWindow( "Canny", 1 );
        cv::imshow( "Canny", border_aux );
#endif

        //Find confining convex hull (Note: used border_copy as findContours modifies the image)
        std::vector<std::vector<cv::Point> > contours;
        std::vector<cv::Vec4i> hierarchy;
        cv::Mat border_copy(border_aux.size(), CV_8UC1);
        border_aux.copyTo(border_copy);
        cv::findContours(border_copy, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );

#ifdef RSEG_DEBUG
        cv::Scalar color = cv::Scalar( 255, 255, 255);
        cv::Mat drawing = cv::Mat::zeros( border_aux.size(), CV_8UC3);
        for(i = 0; i< contours.size(); i++ )
            cv::drawContours( drawing, contours, i, color, 1, 8, hierarchy, 0, cv::Point() );
        cv::namedWindow( "Contours", CV_WINDOW_AUTOSIZE );
        cv::imshow( "Contours", drawing );
#endif

        //One contour to confine all detected contours
        std::vector<cv::Point> big_contour;
        std::vector<cv::Point> hull;
        if(contours.size() > 0) {
            //Group found contours in one big contour
            for(i=0;i<contours.size(); i++) {
                if(hierarchy[i][2] < 0) { // No parent, so it's parent
                    if(big_contour.empty())
                        big_contour = contours[i];
                    else
                        big_contour.insert( big_contour.end(), contours[i].begin(), contours[i].end());
                }
            }
            //Get initial convex hull
            cv::convexHull( big_contour, hull, false );

#ifdef RSEG_DEBUG
            //Print contour and hull
            /*std::cout << "Hull" << std::endl;
            for(i=0; i<hull.size(); i++)
                std::cout << hull[i].x << "," << hull[i].y << std::endl;*/
            cv::Mat drawing2 = cv::Mat::zeros( border_aux.size(), CV_8UC3);
            cv::Scalar color = cv::Scalar( 255, 0, 255 );
            std::vector<std::vector<cv::Point> > drawc, drawh;
            drawc.push_back(big_contour);
            drawh.push_back(hull);
            color = cv::Scalar( 0, 0, 255 );
            cv::drawContours( drawing2, drawh, 0, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point() );
            color = cv::Scalar( 255, 0, 255 );
            cv::drawContours( drawing2, drawc, 0, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point() );
            cv::namedWindow( "Contour and Hull", CV_WINDOW_AUTOSIZE );
            cv::imshow( "Contour and Hull", drawing2 );
#endif
        } else
            continue;
        if(hull.size() == 0)
            continue;

        //Confine current image to blob, and get inverted foreground mask
        cv::Mat caux(c, roi), aux2 = 255 - aux;

        //COLOR HISTOGRAM
        //Get YCrCb image
        cv::Mat c_yuvaux(c_yuv, roi);
        cv::cvtColor(caux, c_yuvaux, CV_BGR2YCrCb);

        //Calculate foreground and background chroma histograms
        cv::MatND hist, hist2;
        //Foreground
        cv::calcHist( &c_yuvaux, 1, channels, aux, // do not use mask
                  hist, 2, histSize, ranges,
                 true, // the histogram is uniform
                 false );
        maxVal=0;
        cv::minMaxLoc(hist, 0, &maxVal, 0, 0);
        hist = hist/maxVal;
        //Background
        cv::calcHist( &c_yuvaux, 1, channels, aux2, // do not use mask
                    hist2, 2, histSize, ranges,
                   true, // the histogram is uniform
                   false );
        maxVal=0;
        cv::minMaxLoc(hist2, 0, &maxVal, 0, 0);
        hist2 = hist2/maxVal;

        //Check correlation between color histograms:
        cv::MatND pixhist;
        for(i = i0; i < i0 + h0; i++ ) {
            if(i==710)
                i=710;
            for(j = j0; j < j0 + w0; j++ ) {
                //Just for points inside the convex hull and a little offset
                if(j==257)
                    j=257;
                if(cv::pointPolygonTest(hull, cv::Point2f(j-j0,i-i0), true) > - m_hullOffset) {
                    if(f.data[i*bl+j]) { //Movement point
                       //Set augmented segmentation image
                       r.data[i*bl2+3*j] = r.data[i*bl2+3*j+1] = r.data[i*bl2+3*j+2] = 255; //White
                    } else { //Non-movement
                        //Check neighborhood for movement.
                       if(    j + w_size/2 >= w || i + w_size/2 >= h
                           || j - w_size/2 < 0  || i - w_size/2 < 0 )
                            continue;
                        wroi.x = j - w_size/2;
                        wroi.y = i - w_size/2;
                        if(movementFound(f, w_size, i, j, roi)) {
                            //Generate local histogram for comparison
                            cv::Mat c_yuvpix(c_yuv, wroi);
                            cv::calcHist( &c_yuvpix, 1, channels, cv::Mat(), // do not use mask
                                        pixhist, 2, histSize, ranges,
                                        true, // the histogram is uniform
                                        false );
                            maxVal = 0;
                            cv::minMaxLoc(pixhist, 0, &maxVal, 0, 0);
                            pixhist = pixhist/maxVal;

                            //Decide if background or foreground, comparing histograms
                            if(histogramDistance(hist,pixhist) < histogramDistance(hist2,pixhist)) {
                                r.data[i*bl2+3*j] = 255; //Red
                            }
                        }
                    }
                }
            }
        }
        //Integrate results with original mask
        for(i = i0; i < i0 + h0; i++ )
            for(j = j0; j < j0 + w0; j++ )
                if(f0.data[i*bl+j] != 0 || r.data[i*bl2+3*j] != 0 || r.data[i*bl2+3*j+1] != 0 || r.data[i*bl2+3*j+2] != 0) {
                    f.data[i*bl+j] = 255;
                    if(f0.data[i*bl+j] != 0)
                        r.data[i*bl2+3*j] = r.data[i*bl2+3*j+1] = r.data[i*bl2+3*j+2] = 255;
                }
        //Opening and Closing
        cv::erode(aux, aux, element);
        cv::dilate(aux, aux, element,cv::Point(-1,-1),2);
        cv::erode(aux, aux, element);

        //Recalculate Convex Hull
        cv::Canny(aux,border_aux, 50,100, 3);
        contours.clear();
        hierarchy.clear();
        big_contour.clear();
        hull.clear();
        cv::findContours(border_aux, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );
        for(i=0;i<contours.size(); i++) {
            if(hierarchy[i][2] < 0) { // No parent, so it's parent
                if(big_contour.empty())
                    big_contour = contours[i];
                else
                    big_contour.insert( big_contour.end(), contours[i].begin(), contours[i].end());
            }
        }
        cv::convexHull( big_contour, hull, false );

        //Get main/minor axis
        std::vector<cv::Point2f> data_aux(h0*w0);
        float mean_x = 0, mean_y = 0;
        int count = 0;

        for(i=0; i<h0; i++)
            for(j=0; j<w0; j++)
                if(cv::pointPolygonTest(hull, cv::Point2f(j, i), true) > - m_hullOffset) {
                    data_aux[count++] = cv::Point2f(j, i);
                    mean_x += j;
                    mean_y += i;
                }
        //data_aux.resize(count);
        //cv::Mat data(2, count, CV_32FC1, &data_aux.front());
        cv::Mat data(2, count, CV_32FC1);
        cv::Point2f x;
        for(i=0; i<count; i++) {
            data.at<float>(0,i) = data_aux[i].x;
            data.at<float>(1,i) = data_aux[i].y;
        }

        //cv::Mat data();
        mean_x /= count;
        mean_y /= count;
        cv::Mat mean(2, 1, CV_32FC1);
        mean.at<float>(0) = mean_x;
        mean.at<float>(1) = mean_y;

        //2. perform PCA
        cv::PCA pca(data, mean, CV_PCA_DATA_AS_COL, maxComponents);
        //result is contained in pca.eigenvectors (as row vectors)
        //std::cout << pca.eigenvectors << std::endl;

        //3. get angle of principal axis
        float dx = pca.eigenvectors.at<float>(0, 0),
              dy = pca.eigenvectors.at<float>(0, 1),
              scale = 40.0;
        cv::Point3f rline;
        cv::Point2f r1, r2;

        //Get line general form from principal component
        getGeneralLineForm(cv::Point2f(mean_x, mean_y),
                           cv::Point2f(mean_x + dx*scale, mean_y + dy*scale),
                           rline);
        //Get segment from line
        int n1, n2;
        //getContourToLineIntersection(hull, rline, r1, r2, &n1, &n2);

        //Get pixel intersections for normals
        std::vector< segment2D<float> > segs;
        //getNormalIntersections(aux, roi, hull, r1, r2, n1, n2, dx, dy, segs);

        //Get the pixel distance function
        std::vector<float> dfunction;
        //dfunction.resize((int)D_axis + 1); //

                //First and last are zero for sure (axis intersects contour).
        //dfunction[0] = 0.0;
        //dfunction[(int)D_axis] = 0.0;
        //for

#ifdef RSEG_DEBUG
        std::cout << "Final Hull" << std::endl;
        for(i=0; i<hull.size(); i++)
            std::cout << i << " : " << hull[i].x << " ; " << hull[i].y << std::endl;

/*        std::cout << "Distances" << std::endl;
        for(i=0; i<segs.size(); i++) {
            double dx = segs[i].first.x - segs[i].last.x;
            double dy = segs[i].first.y - segs[i].last.y;
            std::cout << i << " : " << sqrt(dx*dx+dy*dy) << std::endl;

        }*/
        color = cv::Scalar( 0, 255, 255 );
        std::vector<std::vector<cv::Point> > drawc;
        drawc.push_back(hull);
        cv::Mat raux(r, roi);
        cv::drawContours( raux, drawc, 0, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point() );
        color = cv::Scalar( 0, 255, 0 );
        cv::line(raux, r1, r2, color);
        //cv::line(raux, cv::Point(mean_x - dx*scale, mean_y - dy*scale),
        //               cv::Point(mean_x + dx*scale, mean_y + dy*scale), color);
        cv::namedWindow( "Final", CV_WINDOW_AUTOSIZE );
        cv::imshow( "Final", raux );

        /*std::cout << "Background:" << std::endl;
        std:







:cout << "\tRows:" << hist2.rows << ", Cols:" << hist2.cols << std::endl;
        std::cout << "\tChannels:" << hist2.channels() << ", Depth:" << hist2.depth() << std::endl;
        for(j=0; j<hist2.cols; j++)
          std::cout << "\t" << j;
        std::cout << std::endl;
        for(i=0; i<hist2.rows; i++) {
            for(j=0; j<hist2.cols; j++) {
                std::cout << "\t" << hist2.at<float>(i,j);
            }
            std::cout << std::endl;
        }*/
#endif
    }
    //Set datapool images
    memcpy(fg_p, f.data, h*bl);
    memcpy(m_data->rFgImage->bits(), r.data, h*bl2);

}