Exemple #1
0
int main()
{
    float integral(float(*p)(float),float a,float b,int n);
    float fsin(float x);
    float fcos(float x);
    float fexp(float x);

    float a1,b1,a2,b2,a3,b3,c,(*p)(float);
    int n;
    printf("Input the num:");
    scanf("%d",&n);
    printf("input a1,b1:");
    scanf("%f,%f",&a1,&b1);
    printf("input a2,b2:");
    scanf("%f,%f",&a2,&b2);
    printf("input a3,b3:");
    scanf("%f,%f",&a3,&b3);

    p = fsin;
    c = integral(p,a1,b1,n);//求出sin(n)的定积分
    printf("The integral of sin(n) is :%f\n",c);

    p = fcos;
    c = integral(p,a2,b2,n);//求出cos(n)的定积分
    printf("The integral of cos(n) is :%f\n",c);

    p = fexp;
    c = integral(p,a3,b3,n);//求出exp(n)的定积分
    printf("The integral of exp(n) is :%f\n",c);

    return 0;
}
	void dumpMoment(const Everything& e, const char* filename, int moment, vector3<> origin)
	{	const GridInfo& g = e.gInfo;
		
		FILE* fp = fopen(filename, "w");
		if(!fp) die("Error opening %s for writing.\n", filename);	
		
		// Calculates the electronic moment about origin
		ScalarField r0, r1, r2;
		nullToZero(r0, g); 	nullToZero(r1, g); 	nullToZero(r2, g);
		applyFunc_r(g, rn_pow_x, 0, g.R, moment, origin, r0->data());
		applyFunc_r(g, rn_pow_x, 1, g.R, moment, origin, r1->data());
		applyFunc_r(g, rn_pow_x, 2, g.R, moment, origin, r2->data());
		vector3<> elecMoment;
		elecMoment[0] = integral(e.eVars.n[0]*r0);
		elecMoment[1] = integral(e.eVars.n[0]*r1);
		elecMoment[2] = integral(e.eVars.n[0]*r2);
		fprintf(fp, "Electron moment of order %i: %f\t%f\t%f", moment, elecMoment[0], elecMoment[1], elecMoment[2]);
		
		// Calculates the ionic moment about the origin
		vector3<> ionMoment(0., 0., 0.);
		for(auto sp: e.iInfo.species)
			for(unsigned n=0; n < sp->atpos.size(); n++)
			{	vector3<> cartesianCoord = g.R * map_to_interval(sp->atpos[n]);
				for(int j=0; j<3; j++)
					ionMoment[j] += -sp->Z * pow(cartesianCoord[j], moment); 
			}
		fprintf(fp, "\nIon moment of order %i: %f\t%f\t%f", moment, ionMoment[0], ionMoment[1], ionMoment[2]);

		
		// Calculates the total (elec+ion) dipole moment
		fprintf(fp, "\nTotal moment of order %i: %f\t%f\t%f", moment, ionMoment[0]+elecMoment[0], ionMoment[1]+elecMoment[1], ionMoment[2]+elecMoment[2]);		
	}
float filteredpulsetrain (float edge,float period,float x,float dx)
{
	/* First, normalize so period == 1 and our domain of interest is > 0 */
    float w = dx/period;
    float x0 = x/period - w/2.0f;
    float x1 = x0+w;
    float nedge = edge / period;



	float result;
	if( x0 == x1 )
	{
		/* Trap the unfiltered case so it doesn't return 0 (when dx << x). */
		result = (x0 - floor(x0) < nedge) ? 0.0f : 1.0f;
	}
	else
	{
    	result = (integral(x1, nedge) - integral(x0, nedge)) / w;

		/*
			The above integral is subject to its own aliasing as we go beyond
			where the pattern should be extinct. We try to avoid that by
			switching to a constant value.
		*/
		float extinct = smoothstep( 0.4f, 0.5f, w );
		result = result + extinct * (1.0f - nedge - result);
	}

	return result;
}
Exemple #4
0
int main()
{
  double r0 = integral( &sqr, -1, 1 );
  printf( "> %lf\n", r0 );
  double r1 = integral( &cub, -1, 2 );
  printf( "> %lf\n", r1 );

  return 0;
}
int main(int argc, char *argv[]) {
  double result;
  int rank;

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  result = integral(0, pi, .0000000001, f1);
  if (rank == 0) { printf("%4.20lf\n", result); }
  result = integral(0, pi, .0000000001, f2);
  if (rank == 0) { printf("%4.20lf\n", result); }
  MPI_Finalize();

  return 0;
}
int main() {

	float N, result;
	
	N = 100;
	result = integral(N);
	printf("%f\n",result);
	
	for(N = 1E3; N < 10E3; N += 1E3) {
		result = integral(N);
		printf("%f\n",result);
	}
	
	return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
     try
     {
          ProviderInfo provInfo;
          provInfo.Name( VPN_DEF_PROV );
          provInfo.Type( VPN_PROV_TYPE );
          provInfo.SessionKeyAlgId( CPCSP_ENCRYPT_ID );

          CmdLineInput cmd( argc, argv );

          Settings settings( cmd, provInfo );
          
          IntegralTest integral( settings );
          //integral.AddTest( new KeyGeneration );
          //integral.AddTest( new Encryption );
          //integral.AddTest( new Exportation );
          integral.AddTest( new Hash );
          integral.AddTest( new Signing );
          //integral.AddTest( new DiffieHellman );
          //integral.AddTest( new EncryptMessage );
          //integral.AddTest( new SignMessage );
          //integral.AddTest( new Multithread );
          //integral.AddTest( new Stress );
          //integral.AddTest( new ContainerOnTheDevice );
          integral.Run();
     }
     catch( std::exception& e )
     {
          std::cerr <<"\n" <<e.what() <<"\n";          
     }
     return 0; 
}
Exemple #8
0
/***********************************************************************//**
 * @brief Radial profile
 *
 * @param[in] theta Angular distance from DMBurkert centre (radians).
 * @return Profile value.
 ***************************************************************************/
double GModelSpatialRadialProfileDMBurkert::profile_value(const double& theta) const
{
    // Update precompuation cache
    update();

    // Initialize integral value
    double value = 0.0;
    
    // Set up integration limits
    double los_min = m_halo_distance.value() - m_mass_radius;
    double los_max = m_halo_distance.value() + m_mass_radius;
    
    // Handle case where observer is within halo mass radius
    if (los_min < 0.0) {
        los_min = 0.0;
    }
    
    // Set up integral
    halo_kernel_los integrand(m_scale_radius.value(),
                              m_halo_distance.value(),
                              theta,
                              m_core_radius.value());
    GIntegral integral(&integrand);
    
    // Compute value
    value = integral.romberg(los_min, los_max) * m_scale_density_squared;
    
    // Return value
    return value;
}
Exemple #9
0
inline void rotatedIntegralImage(double descriptor_dir,
                                 const cv::KeyPoint& kpt,
                                 const cv::Mat& img,
								 const int& patch_size,
                                 cv::Mat& win_integral_image)
{

	//* Nearest neighbour version (faster) */
	descriptor_dir *= (float)(CV_PI/180);
	float sin_dir = sin(descriptor_dir);
	float cos_dir = cos(descriptor_dir);
	float win_offset = (int)(patch_size/2);
    cv::Mat win(patch_size, patch_size, CV_8U);
	//******************************************************//
	// faster version: xin yang @ 2012-07-05 11:22am
	//******************************************************//
	float start_x = kpt.pt.x - win_offset*cos_dir + win_offset*sin_dir;
	float start_y = kpt.pt.y - win_offset*sin_dir - win_offset*cos_dir;

	for(int i = 0; i < patch_size; i++, start_x -= sin_dir, start_y += cos_dir){
		float pixel_x = start_x;
		float pixel_y = start_y;
		for(int j = 0; j < patch_size; j++, pixel_x += cos_dir, pixel_y += sin_dir){
			int x = (int)(pixel_x + 0.5);
			int y = (int)(pixel_y + 0.5);
			win.at<unsigned char>(i, j) = img.at<unsigned char>(y, x);
		}
	}
	integral(win, win_integral_image, CV_32S);
}
Exemple #10
0
/***********************************************************************//**
 * @brief Integrate function
 *
 * This code illustrates the integration of a function.
 ***************************************************************************/
int main(void) {

    // Create instance of function
    function fct(3.0);

    // Create an integral object based on the function
    GIntegral integral(&fct);

    // Set relative integration precision
    integral.eps(1.0e-8);

    // Integrate over the interval [-10,10]
    double result = integral.romberg(-15.0, +15.0);

    // Print result (should be basically 1)
    std::cout << "Integral:       " << result << std::endl;

    // Create a derivative object based on the function
    GDerivative derivative(&fct);

    // Print derivatives
    std::cout << "Derivative(0):  " << derivative.value(0.0) << std::endl;
    std::cout << "Derivative(3):  " << derivative.value(3.0) << std::endl;
    std::cout << "Derivative(-3): " << derivative.value(-3.0) << std::endl;

    // Exit
    return 0;
}
std::unique_ptr<typename ElementaryPotentialOperator<
    BasisFunctionType, KernelType, ResultType>::LocalAssembler>
ElementaryPotentialOperator<BasisFunctionType, KernelType, ResultType>::
    makeAssembler(const Space<BasisFunctionType> &space,
                  const arma::Mat<CoordinateType> &evaluationPoints,
                  const QuadratureStrategy &quadStrategy,
                  const EvaluationOptions &options) const {
  // Collect the standard set of data necessary for construction of
  // assemblers
  typedef Fiber::RawGridGeometry<CoordinateType> RawGridGeometry;
  typedef std::vector<const Fiber::Shapeset<BasisFunctionType> *>
  ShapesetPtrVector;
  typedef std::vector<std::vector<ResultType>> CoefficientsVector;
  typedef LocalAssemblerConstructionHelper Helper;

  shared_ptr<RawGridGeometry> rawGeometry;
  shared_ptr<GeometryFactory> geometryFactory;
  shared_ptr<Fiber::OpenClHandler> openClHandler;
  shared_ptr<ShapesetPtrVector> shapesets;

  shared_ptr<const Grid> grid = space.grid();
  Helper::collectGridData(space, rawGeometry, geometryFactory);
  Helper::makeOpenClHandler(options.parallelizationOptions().openClOptions(),
                            rawGeometry, openClHandler);
  Helper::collectShapesets(space, shapesets);

  // Now create the assembler
  return quadStrategy.makeAssemblerForPotentialOperators(
      evaluationPoints, geometryFactory, rawGeometry, shapesets,
      make_shared_from_ref(kernels()),
      make_shared_from_ref(trialTransformations()),
      make_shared_from_ref(integral()), openClHandler,
      options.parallelizationOptions(), options.verbosityLevel());
}
/***********************************************************************//**
 * @brief Returns model energy flux between [emin, emax] (units: erg/cm2/s)
 *
 * @param[in] emin Minimum photon energy.
 * @param[in] emax Maximum photon energy.
 * @return Energy flux (erg/cm2/s).
 *
 * Computes
 *
 * \f[
 *    \int_{\tt emin}^{\tt emax} S_{\rm E}(E | t) E \, dE
 * \f]
 *
 * where
 * - [@p emin, @p emax] is an energy interval, and
 * - \f$S_{\rm E}(E | t)\f$ is the spectral model (ph/cm2/s/MeV).
 * The integration is done numerically.
 ***************************************************************************/
double GModelSpectralExpPlaw::eflux(const GEnergy& emin,
                                    const GEnergy& emax) const
{
    // Initialise flux
    double eflux = 0.0;
    
    // Compute only if integration range is valid
    if (emin < emax) {

        // Setup integration kernel
        eflux_kernel integrand(m_norm.value(),  m_index.value(),
                               m_pivot.value(), m_ecut.value());
        GIntegral integral(&integrand);

        // Get integration boundaries in MeV
        double e_min = emin.MeV();
        double e_max = emax.MeV();

        // Perform integration
        eflux = integral.romberg(e_min, e_max);

        // Convert from MeV/cm2/s to erg/cm2/s
        eflux *= gammalib::MeV2erg;

    } // endif: integration range was valid

    // Return
    return eflux;
}
/***********************************************************************//**
 * @brief Kernel for offset angle integration of background model
 *
 * @param[in] theta Offset angle from ROI centre (radians).
 *
 * Computes
 *
 * \f[
 *    K(\rho | E, t) = \sin \theta \times
 *                     \int_{0}^{2\pi}
 *                     B(\theta,\phi | E, t) d\phi
 * \f]
 *
 * where \f$B(\theta,\phi | E, t)\f$ is the background model for a specific
 * observed energy \f$E\f$ and time \f$t\f$.
 ***************************************************************************/
double GCTAModelIrfBackground::npred_roi_kern_theta::eval(const double& theta)
{
    // Initialise value
    double value = 0.0;

    // Continue only if offset angle is positive
    if (theta > 0.0) {

        // Setup phi integration kernel
        GCTAModelIrfBackground::npred_roi_kern_phi integrand(m_bgd,
                m_logE,
                theta);

        // Integrate over phi
        GIntegral integral(&integrand);
        integral.eps(g_cta_inst_background_npred_phi_eps);
        value = integral.romberg(0.0, gammalib::twopi) * std::sin(theta);

        // Debug: Check for NaN
#if defined(G_NAN_CHECK)
        if (gammalib::is_notanumber(value) || gammalib::is_infinite(value)) {
            std::string origin  = "GCTAModelIrfBackground::npred_roi_kern_theta::eval"
                                  "(" + gammalib::str(theta) + ")";
            std::string message = " NaN/Inf encountered (value=" +
                                  gammalib::str(value) + ")";
            gammalib::warning(origin, message);
        }
#endif

    } // endif: offset angle was positive

    // Return value
    return value;
}
/***********************************************************************//**
 * @brief Evaluate function
 *
 * @param[in] srcEng True photon energy.
 * @param[in] srcTime True photon arrival time.
 * @return Model value (ph/cm2/s/MeV).
 *
 * Computes
 *
 * \f[
 *    S_{\rm E}(E | t) = {\tt m\_integral}
 *    \frac{{\tt m\_index}+1}
 *         {{\tt e\_max}^{{\tt m\_index}+1} -
 *          {\tt e\_min}^{{\tt m\_index}+1}}
 *    E^{\tt m\_index}
 * \f]
 *
 * for \f${\tt m\_index} \ne -1\f$ and
 *
 * \f[
 *    S_{\rm E}(E | t) = 
 *    \frac{{\tt m\_integral}}
 *         {\log {\tt e\_max} - \log {\tt e\_min}}
 *    E^{\tt m\_index}
 * \f]
 *
 * for \f${\tt m\_index} = -1\f$, where
 * - \f${\tt e\_min}\f$ is the minimum energy of an interval,
 * - \f${\tt e\_max}\f$ is the maximum energy of an interval,
 * - \f${\tt m\_integral}\f$ is the integral flux between 
 *   \f${\tt e\_min}\f$ and \f${\tt e\_max}\f$, and
 * - \f${\tt m\_index}\f$ is the spectral index.
 ***************************************************************************/
double GModelSpectralPlaw2::eval(const GEnergy& srcEng,
                                 const GTime&   srcTime) const
{
    // Update precomputed values
    update(srcEng);

    // Compute function value
    double value = m_integral.value() * m_norm * m_power;

    // Compile option: Check for NaN/Inf
    #if defined(G_NAN_CHECK)
    if (gammalib::is_notanumber(value) || gammalib::is_infinite(value)) {
        std::cout << "*** ERROR: GModelSpectralPlaw2::eval";
        std::cout << "(srcEng=" << srcEng;
        std::cout << ", srcTime=" << srcTime << "):";
        std::cout << " NaN/Inf encountered";
        std::cout << " (value=" << value;
        std::cout << ", integral=" << integral();
        std::cout << ", m_norm=" << m_norm;
        std::cout << ", m_power=" << m_power;
        std::cout << ")" << std::endl;
    }
    #endif

    // Return
    return value;
}
std::unique_ptr<typename ElementaryLocalOperator<BasisFunctionType,
                                                 ResultType>::LocalAssembler>
ElementaryLocalOperator<BasisFunctionType, ResultType>::makeAssembler(
    const QuadratureStrategy &quadStrategy,
    const AssemblyOptions &options) const {
  typedef Fiber::RawGridGeometry<CoordinateType> RawGridGeometry;
  typedef std::vector<const Fiber::Shapeset<BasisFunctionType> *>
      ShapesetPtrVector;

  shared_ptr<RawGridGeometry> testRawGeometry, trialRawGeometry;
  shared_ptr<GeometryFactory> testGeometryFactory, trialGeometryFactory;
  shared_ptr<Fiber::OpenClHandler> openClHandler;
  shared_ptr<ShapesetPtrVector> testShapesets, trialShapesets;
  bool cacheSingularIntegrals;

  this->collectDataForAssemblerConstruction(
      options, testRawGeometry, trialRawGeometry, testGeometryFactory,
      trialGeometryFactory, testShapesets, trialShapesets, openClHandler,
      cacheSingularIntegrals);
  assert(testRawGeometry == trialRawGeometry);
  assert(testGeometryFactory == trialGeometryFactory);

  return quadStrategy.makeAssemblerForLocalOperators(
      testGeometryFactory, testRawGeometry, testShapesets, trialShapesets,
      make_shared_from_ref(testTransformations()),
      make_shared_from_ref(trialTransformations()),
      make_shared_from_ref(integral()), openClHandler);
}
Exemple #16
0
/***********************************************************************//**
 * @brief Returns model energy flux between [emin, emax] (units: erg/cm2/s)
 *
 * @param[in] emin Minimum photon energy.
 * @param[in] emax Maximum photon energy.
 * @return Energy flux (erg/cm2/s).
 *
 * Computes
 *
 * \f[
 *    \int_{\tt emin}^{\tt emax} S_{\rm E}(E | t) E \, dE
 * \f]
 *
 * where
 * - [@p emin, @p emax] is an energy interval, and
 * - \f$S_{\rm E}(E | t)\f$ is the spectral model (ph/cm2/s/MeV).
 * The integration is done numerically.
 ***************************************************************************/
double GModelSpectralSmoothBrokenPlaw::eflux(const GEnergy& emin,
                                             const GEnergy& emax) const
{
    // Initialise flux
    double eflux = 0.0;
    
    // Compute only if integration range is valid
    if (emin < emax) {
        
        // Initialise function to integrate
        eflux_kern kernel(prefactor(), index1(), pivot(),
                          index2(), breakenergy(), beta());
        
        // Initialise integral class with function
        GIntegral integral(&kernel);
        
        // Set integration precision
        integral.eps(1.0e-8);
        
        // Calculate integral between emin and emax
        eflux = integral.romberg(emin.MeV(), emax.MeV());
        
        // Convert from MeV/cm2/s to erg/cm2/s
        eflux *= gammalib::MeV2erg;
        
    } // endif: integration range was valid
    
    // Return flux
    return eflux;
}
Exemple #17
0
/***********************************************************************//**
 * @brief Temporally integrates spatially and spectrally integrated Npred
 *        kernel
 *
 * @param[in] model Gamma-ray source model.
 *
 * @exception GException::gti_invalid
 *            Good Time Interval is invalid.
 *
 * Computes
 * \f[N_{\rm pred} = \int_{\rm GTI} \int_{E_{\rm bounds}} \int_{\rm ROI}
 *    S(\vec{p}, E, t) PSF(\vec{p'}, E', t' | \vec{d}, \vec{p}, E, t) \,
 *    {\rm d}\vec{p'} {\rm d}E' {\rm d}t'\f]
 * where
 * \f$S(\vec{p}, E, t)\f$ is the source model,
 * \f$PSF(\vec{p'}, E', t' | \vec{d}, \vec{p}, E, t)\f$ is the point
 * spread function,
 * \f$\vec{p'}\f$ is the measured photon direction,
 * \f$E'\f$ is the measured photon energy,
 * \f$t'\f$ is the measured photon arrival time,
 * \f$\vec{p}\f$ is the true photon arrival direction,
 * \f$E\f$ is the true photon energy,
 * \f$t\f$ is the true photon arrival time, and
 * \f$d\f$ is the instrument pointing.
 *
 * \f${\rm GTI}\f$ are the Good Time Intervals that are stored in the
 * GObservation::m_gti member.
 * Note that MET is used for the time integration interval. This, however,
 * is no specialisation since npred_grad_kern_spec::eval() converts the
 * argument back in a GTime object by assuming that the argument is in MET,
 * hence the correct time system will be used at the end by the method.
 ***************************************************************************/
double GObservation::npred_temp(const GModel& model) const
{
    // Initialise result
    double result = 0.0;

    // Loop over GTIs
    for (int i = 0; i < events()->gti().size(); ++i) {

        // Set integration interval in seconds
        double tstart = events()->gti().tstart(i).secs();
        double tstop  = events()->gti().tstop(i).secs();

        // Throw exception if time interval is not valid
        if (tstop <= tstart) {
            throw GException::gti_invalid(G_NPRED_TEMP, events()->gti().tstart(i),
                                          events()->gti().tstop(i));
        }

        // Setup integration function
        GObservation::npred_temp_kern integrand(this, &model);
        GIntegral                     integral(&integrand);

        // Do Romberg integration
        result += integral.romb(tstart, tstop);

    } // endfor: looped over GTIs

    // Return result
    return result;
}
Exemple #18
0
 /**
  * Integrate down the centre of this unknown
  * This will not take into account changes
  * in the jacobian across the extent of the basis
  * function
  */
 static
 typename UnknownT::NumberT
 integrate(
     const UnknownT& unknown,
     const CoordinatesInterface<DIM,
         typename UnknownT::NumberT>& geom,
     const int direction)
 {
     GaussLegendre<UnknownT::ORDER, NumberT> quad;
     ValueT integral(0.0);
     for (auto interval1D :
          unknown.linearIntervals1D(direction)) {
         NumberT intervalMin = interval1D.minimum(0);
         NumberT intervalMax = interval1D.maximum(0);
         auto nodes = quad.nodes(intervalMin, intervalMax);
         auto weights = quad.weights(intervalMin, intervalMax);
         auto location = unknown.centres();
         for (std::size_t j = 0; j < nodes.size(); ++j) {
             location[direction] = nodes[j];
             integral += weights[j] *
                     unknown.value(direction, nodes[j]) *
                     geom.jacobian(direction, nodes[j]);
         }
     }
     return integral;
 }
Exemple #19
0
static bool matchTemplate_CCOEFF(InputArray _image, InputArray _templ, OutputArray _result)
{
    matchTemplate(_image, _templ, _result, CV_TM_CCORR);

    UMat image_sums, temp;
    integral(_image, image_sums, CV_32F);

    int type = image_sums.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);

    ocl::Kernel k("matchTemplate_Prepared_CCOEFF", ocl::imgproc::match_template_oclsrc,
                  format("-D CCOEFF -D T=%s -D T1=%s -D cn=%d", ocl::typeToStr(type), ocl::typeToStr(depth), cn));
    if (k.empty())
        return false;

    UMat templ  = _templ.getUMat();
    UMat result = _result.getUMat();

    if (cn==1)
    {
        Scalar templMean = mean(templ);
        float templ_sum = (float)templMean[0];

        k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols, templ_sum);
    }
    else
    {
        Vec4f templ_sum = Vec4f::all(0);
        templ_sum = (Vec4f)mean(templ);

       k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols, templ_sum);    }

    size_t globalsize[2] = { result.cols, result.rows };
    return k.run(2, globalsize, NULL, false);
}
/***********************************************************************//**
 * @brief Kernel for zenith angle Npred integration of background model
 *
 * @param[in] theta Offset angle from ROI centre (radians).
 *
 * Computes
 *
 * \f[
 *    K(\rho | E, t) = \sin \theta \times
 *                     \int_{\phi_{\rm min}}^{\phi_{\rm max}}
 *                     S_{\rm p}(\theta,\phi | E, t) \,
 *                     N_{\rm pred}(\theta,\phi) d\phi
 * \f]
 *
 * The azimuth angle integration range
 * \f$[\phi_{\rm min}, \phi_{\rm max}\f$
 * is limited to an arc around the vector connecting the model centre to
 * the ROI centre. This limitation assures proper converges properly.
 ***************************************************************************/
double GCTAModelBackground::npred_roi_kern_theta::eval(const double& theta)
{
    // Initialise value
    double value = 0.0;

    // Continue only if offset angle is positive
    if (theta > 0.0) {

        // Compute sine of offset angle
        double sin_theta = std::sin(theta);
        #if defined(G_NPRED_AROUND_ROI)
        double dphi = gammalib::pi;
        #else
        double dphi = 0.5 * gammalib::cta_roi_arclength(theta,
                                                        m_dist,
                                                        m_cosdist,
                                                        m_sindist,
                                                        m_roi,
                                                        m_cosroi);
        #endif

        // Continue only if arc length is positive
        if (dphi > 0.0) {

		   // Compute phi integration range
		   double phi_min = m_omega0 - dphi;
		   double phi_max = m_omega0 + dphi;

			// Setup phi integration kernel
            GCTAModelBackground::npred_roi_kern_phi integrand(m_model,
												              m_obsEng,
												              m_obsTime,
												              m_rot,
												              theta,
												              sin_theta);

			// Integrate over phi
			GIntegral integral(&integrand);
	        integral.eps(1e-3);
			value = integral.romb(phi_min, phi_max) * sin_theta;

			// Debug: Check for NaN
			#if defined(G_NAN_CHECK)
			if (gammalib::is_notanumber(value) || gammalib::is_infinite(value)) {
				std::cout << "*** ERROR: GCTAModelBackground::npred_roi_kern_theta::eval";
				std::cout << "(theta=" << theta << "):";
				std::cout << " NaN/Inf encountered";
				std::cout << " (value=" << value;
				std::cout << ", sin_theta=" << sin_theta;
				std::cout << ")" << std::endl;
			}
			#endif

        } // endif: arc length was positive

    } // endif: offset angle was positive

    // Return value
    return value;
}
double Fex_H2O_FittedCorrelations::compute(const ScalarFieldTilde* Ntilde, ScalarFieldTilde* Phi_Ntilde) const
{	double PhiEx = 0.0;
	//Quadratic part:
	ScalarFieldTilde V_O = double(gInfo.nr)*(COO*Ntilde[0] + COH*Ntilde[1]); Phi_Ntilde[0] += V_O;
	ScalarFieldTilde V_H = double(gInfo.nr)*(COH*Ntilde[0] + CHH*Ntilde[1]); Phi_Ntilde[1] += V_H;
	PhiEx += 0.5*gInfo.dV*(dot(V_O,Ntilde[0]) + dot(V_H,Ntilde[1]));

	//Compute gaussian weighted densities:
	ScalarField NObar = I(fex_gauss*Ntilde[0]), Phi_NObar; nullToZero(Phi_NObar, gInfo);
	ScalarField NHbar = I(fex_gauss*Ntilde[1]), Phi_NHbar; nullToZero(Phi_NHbar, gInfo);
	//Evaluated weighted density functional:
	#ifdef GPU_ENABLED
	ScalarField fex(ScalarFieldData::alloc(gInfo,isGpuEnabled()));
	Fex_H20_FittedCorrelations_gpu(gInfo.nr, NObar->dataGpu(), NHbar->dataGpu(),
		 fex->dataGpu(), Phi_NObar->dataGpu(), Phi_NHbar->dataGpu());
	PhiEx += integral(fex);
	#else
	PhiEx += gInfo.dV*threadedAccumulate(Fex_H2O_FittedCorrelations_calc, gInfo.nr,
		 NObar->data(), NHbar->data(), Phi_NObar->data(), Phi_NHbar->data());
	#endif
	//Convert gradients:
	Phi_Ntilde[0] += fex_gauss*Idag(Phi_NObar);
	Phi_Ntilde[1] += fex_gauss*Idag(Phi_NHbar);
	return PhiEx;
}
Exemple #22
0
static bool matchTemplate_SQDIFF_NORMED(InputArray _image, InputArray _templ, OutputArray _result)
{
    matchTemplate(_image, _templ, _result, CV_TM_CCORR);

    int type = _image.type(), cn = CV_MAT_CN(type);

    ocl::Kernel k("matchTemplate_SQDIFF_NORMED", ocl::imgproc::match_template_oclsrc,
                  format("-D SQDIFF_NORMED -D T=%s -D cn=%d", ocl::typeToStr(type),  cn));
    if (k.empty())
        return false;

    UMat image = _image.getUMat(), templ = _templ.getUMat();
    _result.create(image.rows - templ.rows + 1, image.cols - templ.cols + 1, CV_32F);
    UMat result = _result.getUMat();

    UMat image_sums, image_sqsums;
    integral(image.reshape(1), image_sums, image_sqsums, CV_32F, CV_32F);

    UMat templ_sqsum;
    if (!sumTemplate(_templ, templ_sqsum))
        return false;

    k.args(ocl::KernelArg::ReadOnlyNoSize(image_sqsums), ocl::KernelArg::ReadWrite(result),
           templ.rows, templ.cols, ocl::KernelArg::PtrReadOnly(templ_sqsum));

    size_t globalsize[2] = { result.cols, result.rows };

    return k.run(2, globalsize, NULL, false);
}
Exemple #23
0
Mat CScale::get(const Mat &img, SqNeighbourhood nbhd)
{
	int	width		= img.cols;
	int	height		= img.rows;
	int	nChannels	= img.channels();

	Mat res(img.size(), img.type());
	vec_mat_t vChannels;
	split(img, vChannels);

	Mat integralImg;												
	for (byte c = 0; c < nChannels; c++) {		
		integral(vChannels[c], integralImg);

		for (int y = 0; y < height; y++) {
			int		 y0 = MAX(0, y - nbhd.upperGap);
			int	 	 y1 = MIN(y + nbhd.lowerGap, height - 1);
			byte	*pRes = res.ptr<byte>(y);
			int *pI0 = integralImg.ptr<int>(y0);
			int *pI1 = integralImg.ptr<int>(y1 + 1);
			for (int x = 0; x < width; x++) {
				int		x0 = MAX(0, x - nbhd.leftGap);
				int		x1 = MIN(x + nbhd.rightGap, width - 1);
				int		S = (x1 - x0 + 1) * (y1 - y0 + 1);
				float	med = static_cast<float>(pI1[x1 + 1] - pI1[x0] - pI0[x1 + 1] + pI0[x0]) / S;
				pRes[nChannels * x + c] = static_cast<byte>(med + 0.5f);
			} // x
		} // y
	} // c

	return res;	
}
Exemple #24
0
double integral_g_dx_dy(double xi, double xf, int n, double yi, double yf, int m){
	Param *p = (Param*) malloc(sizeof(Param));
	p->xi=xi;
	p->xf=xf;
	p->n=n;
	return integral(integral_g_dx_aux, p, yi, yf, m);
}
Exemple #25
0
void Predator::selectObject(Mat& img, BoundingBox& bb)
{

    this->nnClassifier->release();
    this->ffClassifier->release();


    this->detector->objW = bb.w;
    this->detector->objH = bb.h;


    this->ffClassifier->init(this->params->n_ferns, this->params->n_features, this->params->min_scale, this->params->max_scale);
    this->detector->init();



    this->currBB = bb;
    this->currBB.conf = 1.0f;
    this->currBB.valid = true;

    this->detectedBB = BoundingBox();

    cvtColor( img, this->currImg, CV_RGB2GRAY );
    integral( this->currImg, this->integralImg,this->integralImgSqr, CV_64F);



    this->initialLearning();
    this->initialized = true;
    


}
void CvLBPEvaluator::setImage( const Mat &img, uchar clsLabel, int idx )
{
  CV_DbgAssert( !sum.empty() );
  CvFeatureEvaluator::setImage( img, clsLabel, idx );
  Mat innSum( winSize.height + 1, winSize.width + 1, sum.type(), sum.ptr<int>( (int) idx ) );
  integral( img, innSum );
}
void Dump::dumpRsol(ScalarField nbound, string fname)
{	
	//Compute normalization factor for the partition:
	int nAtomsTot = 0; for(const auto& sp: e->iInfo.species) nAtomsTot += sp->atpos.size();
	const double nFloor = 1e-5/nAtomsTot; //lower cap on densities to prevent Nyquist noise in low density regions
	ScalarField nAtomicTot;
	for(const auto& sp: e->iInfo.species)
	{	RadialFunctionG nRadial;
		logSuspend(); sp->getAtom_nRadial(0,0, nRadial, true); logResume();
		for(unsigned atom=0; atom<sp->atpos.size(); atom++)
		{	ScalarField nAtomic = radialFunction(e->gInfo, nRadial, sp->atpos[atom]);
			double nMin, nMax; callPref(eblas_capMinMax)(e->gInfo.nr, nAtomic->dataPref(), nMin, nMax, nFloor);
			nAtomicTot += nAtomic;
		}
	}
	ScalarField nboundByAtomic = (nbound*nbound) * inv(nAtomicTot);

	ScalarField rInv0(ScalarFieldData::alloc(e->gInfo));
	{	logSuspend(); WignerSeitz ws(e->gInfo.R); logResume();
		threadLaunch(set_rInv, e->gInfo.nr, e->gInfo.S, e->gInfo.RTR, &ws, rInv0->data());
	}
	
	//Compute bound charge 1/r and 1/r^2 expectation values weighted by atom-density partition:
	FILE* fp = fopen(fname.c_str(), "w");
	fprintf(fp, "#Species   rMean +/- rSigma [bohrs]   (rMean +/- rSigma [Angstrom])   sqrt(Int|nbound^2|) in partition\n");
	for(const auto& sp: e->iInfo.species)
	{	RadialFunctionG nRadial;
		logSuspend(); sp->getAtom_nRadial(0,0, nRadial, true); logResume();
		for(unsigned atom=0; atom<sp->atpos.size(); atom++)
		{	ScalarField w = radialFunction(e->gInfo, nRadial, sp->atpos[atom]) * nboundByAtomic;
			//Get r centered at current atom:
			ScalarFieldTilde trans; nullToZero(trans, e->gInfo); initTranslation(trans, e->gInfo.R*sp->atpos[atom]);
			ScalarField rInv = I(trans * J(rInv0), true);
			//Compute moments:
			double wNorm = integral(w);
			double rInvMean = integral(w * rInv) / wNorm;
			double rInvSqMean = integral(w * rInv * rInv) / wNorm;
			double rInvSigma = sqrt(rInvSqMean - rInvMean*rInvMean);
			double rMean = 1./rInvMean;
			double rSigma = rInvSigma / (rInvMean*rInvMean);
			//Print stats:
			fprintf(fp, "Rsol %s    %.2lf +/- %.2lf    ( %.2lf +/- %.2lf A )   Qrms: %.1le\n", sp->name.c_str(),
				rMean, rSigma, rMean/Angstrom, rSigma/Angstrom, sqrt(wNorm));
		}
	}
	fclose(fp);
}
Exemple #28
0
void PCM::propagateCavityGradients(const ScalarField& A_shape, ScalarField& A_nCavity, ScalarFieldTilde& A_rhoExplicitTilde, bool electricOnly) const
{   if(fsp.pcmVariant == PCM_SGA13)
    {   //Propagate gradient w.r.t expanded cavities to nCavity:
        ((PCM*)this)->A_nc = 0;
        const ScalarField* A_shapeEx[2] = { &A_shape, &Acavity_shapeVdw };
        for(int i=0; i<2; i++)
        {   //First compute derivative w.r.t expanded electron density:
            ScalarField A_nCavityEx;
            ShapeFunction::propagateGradient(nCavityEx[i], *(A_shapeEx[i]), A_nCavityEx, fsp.nc, fsp.sigma);
            ((PCM*)this)->A_nc += (-1./fsp.nc) * integral(A_nCavityEx*nCavityEx[i]);
            //then propagate to original electron density:
            ScalarField nCavityExUnused; //unused return value below
            ShapeFunction::expandDensity(wExpand[i], Rex[i], nCavity, nCavityExUnused, &A_nCavityEx, &A_nCavity);
        }
    }
    else if(fsp.pcmVariant == PCM_CANDLE)
    {   ScalarField A_nCavityEx;
        ScalarFieldTilde A_phiExt;
        double A_pCavity=0.;
        ShapeFunction::propagateGradient(nCavityEx[0], coulomb(Sf[0]*rhoExplicitTilde), I(wExpand[0]*J(A_shape)) + Acavity_shapeVdw,
                                         A_nCavityEx, A_phiExt, A_pCavity, fsp.nc, fsp.sigma, fsp.pCavity);
        A_nCavity += fsp.Ztot * I(Sf[0] * J(A_nCavityEx));
        if(!electricOnly) A_rhoExplicitTilde += coulomb(Sf[0]*A_phiExt);
        ((PCM*)this)->A_nc = (-1./fsp.nc) * integral(A_nCavityEx*nCavityEx[0]);
        ((PCM*)this)->A_eta_wDiel = integral(A_shape * I(wExpand[1]*J(shapeVdw)));
        ((PCM*)this)->A_pCavity = A_pCavity;
    }
    else if(isPCM_SCCS(fsp.pcmVariant))
    {   //Electrostatic and volumetric combinations via shape:
        ShapeFunctionSCCS::propagateGradient(nCavity, A_shape - fsp.cavityPressure, A_nCavity, fsp.rhoMin, fsp.rhoMax, epsBulk);
        //Add surface contributions:
        ScalarField shapePlus, shapeMinus;
        ShapeFunctionSCCS::compute(nCavity+(0.5*fsp.rhoDelta), shapePlus, fsp.rhoMin, fsp.rhoMax, epsBulk);
        ShapeFunctionSCCS::compute(nCavity-(0.5*fsp.rhoDelta), shapeMinus, fsp.rhoMin, fsp.rhoMax, epsBulk);
        VectorField Dn = gradient(nCavity);
        ScalarField DnLength = sqrt(lengthSquared(Dn));
        ScalarField A_shapeMinus = (fsp.cavityTension/fsp.rhoDelta) * DnLength;
        ScalarField A_DnLength = (fsp.cavityTension/fsp.rhoDelta) * (shapeMinus - shapePlus);
        A_nCavity -= divergence(Dn * (inv(DnLength) * A_DnLength));
        ShapeFunctionSCCS::propagateGradient(nCavity+(0.5*fsp.rhoDelta), -A_shapeMinus, A_nCavity, fsp.rhoMin, fsp.rhoMax, epsBulk);
        ShapeFunctionSCCS::propagateGradient(nCavity-(0.5*fsp.rhoDelta),  A_shapeMinus, A_nCavity, fsp.rhoMin, fsp.rhoMax, epsBulk);
    }
    else //All gradients are w.r.t the same shape function - propagate them to nCavity (which is defined as a density product for SaLSA)
    {   ShapeFunction::propagateGradient(nCavity, A_shape + Acavity_shape, A_nCavity, fsp.nc, fsp.sigma);
        ((PCM*)this)->A_nc = (-1./fsp.nc) * integral(A_nCavity*nCavity);
    }
}
Exemple #29
0
/***********************************************************************//**
 * @brief Remove thetacut
 *
 * @param[in] rsp CTA response.
 *
 * Removes thetacut from Aeff values read from a FITS file. Note that this
 * method should only be called once directly after loading all response
 * components.
 ***************************************************************************/
void GCTAAeffArf::remove_thetacut(const GCTAResponse& rsp)
{
    // Continue only if thetacut value has been set
    if (m_thetacut > 0.0) {

        // Get maximum integration radius
        double rmax = m_thetacut * gammalib::deg2rad;

        // Loop over Aeff array
        for (int i = 0; i < m_aeff.size(); ++i) {
    
            // Setup integration kernel for on-axis PSF
            cta_npsf_kern_rad_azsym integrand(rsp,
                                              rmax,
                                              0.0,
                                              m_logE[i],
                                              0.0,
                                              0.0,
                                              0.0,
                                              0.0);

            // Setup integration
            GIntegral integral(&integrand);
            integral.eps(rsp.eps());

            // Perform integration
            double fraction = integral.romb(0.0, rmax);

            // Set scale factor
            double scale = 1.0;
            if (fraction > 0.0) {
                scale /= fraction;
                #if defined(G_DEBUG_APPLY_THETACUT)
                std::cout << "GCTAAeffArf::apply_thetacut:";
                std::cout << " logE=" << m_logE[i];
                std::cout << " scale=" << scale;
                std::cout << " fraction=" << fraction;
                std::cout << std::endl;
                #endif
            }
            else {
                std::cout << "WARNING: GCTAAeffArf::apply_thetacut:";
                std::cout << " Non-positive integral occured in";
                std::cout << " PSF integration.";
                std::cout << std::endl;
            }

            // Apply scaling factor
            if (scale != 1.0) {
                m_aeff[i] *= scale;
            }

        } // endfor: looped over Aeff array

    } // endif: thetacut value was set

    // Return
    return;
}
Exemple #30
0
int main(int argc, char** argv) {
    float twopi = 2 * 3.14;
    float integral_of_f = integral(0.0, 1.0, square, 1e3);
    /*float integral_of_sin = integral(0.0, twopi, sin, 10);*/
    printf("Całka z funkjci f (0.0 - 1.0) = %g\n", integral_of_f);
    /*printf("Całka z sinus (0 - 2pi) = %g\n", integral_of_sin);*/
    return 0;
}