Example #1
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;
}
Example #2
0
static void tst1(unsigned n1) {
    typedef fvi<data, to_feature_vector, data_hash> data_set;
    data_set index1(NUM_FEATURES, to_feature_vector(NUM_FEATURES));
    ptr_vector<data> index2;
    
    for (unsigned i = 0; i < n1; i++) {
        int op = rand()%6;
        if (op < 3) {
            data * d = mk_random_data();
            if (!index1.contains(d)) {
                // TRACE("fvi", tout << "inserting: " << *d << "\n";);
                index1.insert(d);
                index2.push_back(d);
                SASSERT(std::find(index2.begin(), index2.end(), d) != index2.end());
                SASSERT(index1.contains(d));
            }
        }
        else if (op < 4) {
            if (!index2.empty()) {
                unsigned idx = rand() % index2.size();
                if (index2[idx]) {
                    SASSERT(index1.contains(index2[idx]));
                }
            }
        }
        else if (op < 5) {
            if (!index2.empty()) {
                unsigned idx = rand() % index2.size();
                if (index2[idx]) {
                    // TRACE("fvi", tout << "erasing: " << *(index2[idx]) << "\n";);
                    index1.erase(index2[idx]);
                    SASSERT(!index1.contains(index2[idx]));
                    index2[idx] = 0;
                }
            }
        }
        else {
            if (!index2.empty()) {
                unsigned idx = rand() % index2.size();
                data * d = index2[idx];
                if (d)
                    index1.visit(d, le_visitor(d));
            }
        }
    }

    TRACE("fvi",
          data_set::statistics s;
          index1.stats(s);
          tout << "size:           " << s.m_size << "\n";
          tout << "num. nodes:     " << s.m_num_nodes << "\n";
          tout << "num. leaves:    " << s.m_num_leaves << "\n";
          tout << "min. leaf size: " << s.m_min_leaf_size << "\n";
          tout << "max. leaf size: " << s.m_max_leaf_size << "\n";
          );
Example #3
0
void SqliteTests::initTestCase()
{
    verifyCreateTable();
    foreignKey();

    DQConnection defaultConnection = DQConnection::defaultConnection();

    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName( "tests.db" );

    QVERIFY( db.open() );

    QVERIFY( !defaultConnection.isOpen());
    QVERIFY (connect.open(db) );

    QVERIFY(defaultConnection.isOpen()); // connect become default connection

    DQSql sql = connect.sql();


    QVERIFY( sql.createTableIfNotExists<Model1>() );

    QVERIFY( sql.exists(dqMetaInfo<Model1>() ) );

    QVERIFY( sql.dropTable(dqMetaInfo<Model1>()) );

    QVERIFY( !sql.exists(dqMetaInfo<Model1>() ) );

    QVERIFY( sql.createTableIfNotExists<Model1>() );

    QVERIFY ( connect.addModel<Model1>() );
    QVERIFY ( connect.addModel<Model2>() );
    QVERIFY (!connect.addModel<Model1>() );
    QVERIFY (!connect.addModel<Model3>() );
    QVERIFY ( connect.addModel<Model4>() );
    QVERIFY ( connect.addModel<User>() );
    QVERIFY ( connect.addModel<Config>() );
    QVERIFY ( connect.addModel<ExamResult>() );
    QVERIFY ( connect.addModel<AllType>() );
    QVERIFY ( connect.addModel<HealthCheck>());

    QVERIFY( connect.dropTables() );

    QVERIFY( connect.createTables() ); // recreate table

    /* Create index */

    DQIndex<Model1> index1("index1");
    index1 << "key" << "value";

    QVERIFY(connect.createIndex(index1));

    // drop the index
    QVERIFY(connect.dropIndex(index1.name()));
}
Example #4
0
void index1(int i, int f)
{
    struct item* p;
    int j, k;

    if (i >= idx.rank) {
        switch (f) {

        case 0:
            p = sp[-2];
            p->index = access();
            putdat(sp[-1], getdat(p));
            return;

        case 1:
            datum = getdat(sp[-idx.rank - 3]);

        case 2:
            p = ((SymTabEntry*)sp[-2])->itemp;
            p->index = access();
            putdat(p, datum);
            return;
        }
    }
    p = sp[-i - 3];
    if (p->itemType == EL) {
        for (j = 0; j < idx.dim[i]; j++) {
            idx.idx[i] = j;
            index1(i + 1, f);
        }
        return;
    }
    p->index = 0;
    for (j = 0; j < p->size; j++) {
        k = fix(getdat(p)) - iorigin;
        if (k < 0 || k >= idx.dim[i])
            error(ERR_index, "");
        idx.idx[i] = k;
        index1(i + 1, f);
    }
}
Example #5
0
index1(i, f)
{
	struct item *p;
	int j, k;

	if(i >= idx.rank) {
		switch(f) {

		case 0:
			p = sp[-2];
			p->index = access_();
			putdat(sp[-1], getdat(p));
			return;

		case 1:
			datum = getdat(sp[-idx.rank-3]);

		case 2:
			p = ((struct nlist *)sp[-2])->itemp;
			p->index = access_();
			putdat(p, datum);
			return;
		}
	}
	p = sp[-i-3];
	if(p->type == EL) {
		for(j=0; j<idx.dim[i]; j++) {
			idx.idx[i] = j;
			index1(i+1, f);
		}
		return;
	}
	p->index = 0;
	for(j=0; j<p->size; j++) {
		k = fix(getdat(p)) - thread.iorg;
		if(k < 0 || k >= idx.dim[i]) error("subscript X");
		idx.idx[i] = k;
		index1(i+1, f);
	}
}
Example #6
0
/*** Parse a slice/select assign statement ***/
Node* Parser::parseSliceSelectAssign()
{
	if(!hasTokens() || peekToken().getType() != T_IDENTIFIER)
		throw ParserSyntaxException(getToken(), "Expected variable identifier!");

	// Store the variable
	std::auto_ptr<Variable> target(new Variable(getToken()));

	if(!hasTokens() || peekToken().getType() != T_LBRACKET)
		throw ParserSyntaxException(getToken(), "Expected '['!");
	Token tok = getToken();

	std::auto_ptr<Object> index1(parseExpression());

	if(hasTokens() && peekToken().getType() == T_RBRACKET)
	{
		getToken();

		if(!hasTokens() || peekToken().getType() != T_ASSIGN)
			throw ParserSyntaxException(getToken(), "Expected ':='!");
		getToken();

		std::auto_ptr<Object> expr(parseExpression());

		SelectAssign* result = new SelectAssign(target.release(), index1.release(), expr.release());
		result->setLineNumber(tok.getLineNumber());
		result->setColumnNumber(tok.getColumnNumber());
		return result;
	}

	if(!hasTokens() || peekToken().getType() != T_COLON)
		throw ParserSyntaxException(getToken(), "Expected ':' or ']'!");
	getToken();

	std::auto_ptr<Object> index2(parseExpression());

	if(!hasTokens() || peekToken().getType() != T_RBRACKET)
		throw ParserSyntaxException(getToken(), "Expected ']'!");
	getToken();

	if(!hasTokens() || peekToken().getType() != T_ASSIGN)
		throw ParserSyntaxException(getToken(), "Expected ':='!");
	getToken();

	std::auto_ptr<Object> expr(parseExpression());

	SliceAssign* result = new SliceAssign(target.release(), index1.release(), index2.release(), expr.release());
	result->setLineNumber(tok.getLineNumber());
	result->setColumnNumber(tok.getColumnNumber());
	return result;
}
Example #7
0
/***********************************************************************//**
 * @brief Update Monte Carlo pre computation cache
 *
 * Updates the precomputation cache for Monte Carlo simulations.
 ***************************************************************************/
void GModelSpectralSmoothBrokenPlaw::update_mc_cache(void) const
{
    // Check if we need to update the cache
    if (prefactor()         != m_mc_prefactor ||
        index1()            != m_mc_index1    ||
        index2()            != m_mc_index2    ||
        pivot().MeV()       != m_mc_pivot     ||
        breakenergy().MeV() != m_mc_breakenergy) {

        // Set parameters for which Monte Carlo cache was computed
        m_mc_prefactor = prefactor();
        m_mc_index1      = index1();
        m_mc_index2      = index2();
        m_mc_pivot       = pivot().MeV();
        m_mc_breakenergy = breakenergy().MeV();

        // Compute prefactor at pivot energy
        double pre = prefactor() *
                     std::pow(breakenergy().MeV()/pivot().MeV(), index1());

        // Find out which index is harder. This is important since the smoothly
        // broken power law follows the hard index below the break energy and
        // the softer index above the break energy.
        double index1 = (m_mc_index1 > m_mc_index2) ? m_mc_index1 : m_mc_index2;
        double index2 = (m_mc_index1 > m_mc_index2) ? m_mc_index2 : m_mc_index1;

        // Set broken power law for Monte Carlo simulations
        m_mc_brokenplaw = GModelSpectralBrokenPlaw(pre,
                                                   index1,
                                                   breakenergy(),
                                                   index2);
        
    } // endif: Update was required
    
    // Return
    return;
}
	std::vector<Real> power_spread_note(Date evaluationDate,
		Real notional,
		Schedule schedule,
		DayCounter dayCounter,
		BusinessDayConvention bdc,
		std::vector<Real> gearing,
		std::vector<Real> spread,
		std::vector<Real> caps,
		std::vector<Real> floors,
		bool isAvg,
		Date firstCallDate,
		Real pastFixing,
		boost::shared_ptr<StochasticProcess1D> obs1Process,
		boost::shared_ptr<StochasticProcess1D> obs2Process,
		boost::shared_ptr<HullWhiteProcess> discProcess,
		Real rho12,
		Real rho1disc,
		Real rho2disc,
		Size numSimulation,
		Size numCalibration) {

			Date todaysDate = evaluationDate;
			Settings::instance().evaluationDate() = todaysDate;

			boost::shared_ptr<IborIndex> index1(new Euribor3M(Handle<YieldTermStructure>( discProcess->yieldTermStructure() )));
			boost::shared_ptr<SpreadIndex> index(new SpreadIndex(index1, index1));

			boost::shared_ptr<Callability> callability(new 
				Callability(Callability::Price(notional, Callability::Price::Clean), Callability::Call, firstCallDate));
			CallabilitySchedule callSchedule;
			callSchedule.push_back(callability);

			/***********************************************************************************/


			PowerSpreadNote testProduct(0, notional, schedule, index, dayCounter, bdc, Null<Natural>(), 
				gearing, spread, caps, floors, isAvg, 100.0, Date(), 
				callSchedule, Exercise::Bermudan);


			/*****Pricing Engine*****/
			std::vector<boost::shared_ptr<StochasticProcess1D> > pros;
			pros.push_back(discProcess);
			pros.push_back(obs1Process);
			pros.push_back(obs2Process);
			Matrix corr(3,3,1.0);
			corr[0][1] = corr[1][0] = rho1disc;
			corr[0][2] = corr[2][0] = rho2disc;
			corr[1][2] = corr[2][1] = rho12;

			boost::shared_ptr<StochasticProcessArray> processes(new StochasticProcessArray(pros, corr));

			boost::shared_ptr<PricingEngine> engine_lsmc(new MC_PowerSpread_Engine_LSMC<>(processes,
				0.0, //pastAccrual
				256, //seed 
				numSimulation, //required samples
				numCalibration, //calibration samples
				true, //antithetic
				false,  //control variate
				false //brownian bridge
				));
			testProduct.setPricingEngine(engine_lsmc);

			std::vector<Real> rst;
			rst.push_back(testProduct.NPV());
			rst.push_back(testProduct.errorEstimate());
			return rst;

	}
Example #9
0
/*
   TODO
   - label_contour is called two times; only once suffices
*/
AnimalExport ImgPUInt32 *
msskl_difference(ann_img *aimg)
{
   ImgPUInt32 *imcont, *immsskel, *imseed, *imperim;
   puint32 *seed, *cont, *perim, *pred, *label, *msskel,
            maxd1, maxd2, MaxD;
   int r,c,i,j,k,qx,qy,p,q, d1,d2,
       *idxlut,n;

   r = aimg->label->rows; 
   c = aimg->label->cols;
   n = r*c;
   idxlut   = aimg->label->lut;
   imcont   = label_contour(aimg->img);  
   imperim  = perimeter(aimg->img);
   immsskel = new_img_puint32(r,c);
   imseed   = root_map(aimg->pred);

   seed     = imseed->data;
   cont     = imcont->data;
   perim    = imperim->data;
   msskel   = immsskel->data;
   pred     = aimg->pred->data;
   label    = aimg->label->data;

   MaxD = 0;
   for (i=0; i<r; i++) 
         for (j=0; j<c; j++) {
            p = index1(i,j,idxlut);
            // @@@ why eliminate the contours??
            if (pred[p] != (unsigned)p) {/* Eliminates the contours and
                                            considers the side option */
               maxd1 = maxd2 = 0;
               for (k=0; k < 4; k++) {
                  qy = n4[k][0] + i;
                  qx = n4[k][1] + j;
                  if (valid_pixel(r,c,qx,qy)) {
                     q = index1(qy,qx,idxlut);
                     if (cont[seed[p]] == cont[seed[q]]) { // not a SKIZ
                        d2 = label[q] - label[p];
                        if (d2 > (int)perim[seed[p]]-d2)
                           d2 = (int)perim[seed[p]]-d2;
                        if (d2 > (int)maxd2)
                           maxd2 = (unsigned)d2;
                     } else { // a SKIZ
                        d1 = cont[seed[q]] - cont[seed[p]];
                        if (d1 > (int)maxd1)
                           maxd1 = (unsigned)d1;
                     }
                  }
               }
               if (maxd1 > 0)
                  msskel[p] = UINT_MAX;
               else {
                  msskel[p] = maxd2;
                  if (msskel[p] > MaxD)
                     MaxD = msskel[p];
               }
            }
         }

   for (p=0; p < n; p++)
      if (msskel[p] == UINT_MAX)
         msskel[p] = MaxD + 1;

   imfree_puint32(&imcont);
   imfree_puint32(&imperim);
   imfree_puint32(&imseed);
   return immsskel;
}
Example #10
0
ex_index()
{
	struct item *p, *q;
	int i, j, f, n, lv;

	n = *pcp++;
	f = *pcp;
	p = sp[-1];
	if(f == ASGN) {
		pcp++;
		if(p->type != LV) error("indexed assign value");
		if(((struct nlist *)p)->use != DA) fetch1();		/* error("used before set"); */
		q = ((struct nlist *)p)->itemp;
	}
	else q = fetch1();
	if(q->rank != n) error("subscript C");
	idx.rank = 0;
	for(i=0; i<n; i++) {
		p = sp[-i-2];
		if(p->type == EL) {
			idx.dim[idx.rank++] = q->dim[i];
			continue;
		}
		p = fetch(p);
		sp[-i-2] = p;
		for(j=0; j<p->rank; j++) idx.dim[idx.rank++] = p->dim[j];
	}
	size();
	if(f == ASGN) {
		p = fetch(sp[-n-2]);
		sp[-n-2] = p;
		if (p->size > 1) {
			if(idx.size != p->size) error("assign C");
			f = 1; /* v[i] <- v */
		}
		else {
			if (idx.size && !p->size) error("assign C");
			/* Note -- for idx.size = 0, no assign occurs
			 * anyway, so it is safe to set "datum" to 0
			 */
			datum = p->size ? getdat(p) : 0;
			f = 2; /* v[i] <- s */
		}
		ex_elid();
	}
	else {
		p = newdat(q->type, idx.rank, idx.size);
		copy(IN, idx.dim, p->dim, idx.rank);
		*sp++ = p;
		f = 0; /* v[i] */
	}
	bidx(q);
	index1(0, f);
	if(f == 0) {
		p = sp[-1];
		sp--;
		for(i=0; i<=n; i++) pop();
		*sp++ = p;
	}
	else {
		pop();		/* pop ELID */
		sp--;		/* skip over LV */
		for(i=0; i<n; i++) pop();
	}
}
Example #11
0
void ex_index()
{
    struct item *p, *q;
    int i, j, f, n;

    n = *gsip->ptr++;
    f = *gsip->ptr;
    p = sp[-1];
    if (f == ASGN) {
        gsip->ptr++;
        if (p->itemType != LV)
            error(ERR_value, "not a local variable");
        if (((SymTabEntry*)p)->entryUse != DA)
            fetch1();
        q = ((SymTabEntry*)p)->itemp;
    }
    else
        q = fetch1();
    if (q->rank != n)
        error(ERR_index, "");
    idx.rank = 0;
    for (i = 0; i < n; i++) {
        p = sp[-i - 2];
        if (p->itemType == EL) {
            idx.dim[idx.rank++] = q->dim[i];
            continue;
        }
        p = fetch(p);
        sp[-i - 2] = p;
        for (j = 0; j < p->rank; j++)
            idx.dim[idx.rank++] = p->dim[j];
    }
    size();
    if (f == ASGN) {
        p = fetch(sp[-n - 2]);
        sp[-n - 2] = p;
        if (p->size > 1) {
            if (idx.size != p->size)
                error(ERR_length, "");
            f = 1; /* v[i] <- v */

        } else {
            if (idx.size && !p->size)
                error(ERR_length, "");
            /* Note -- for idx.size = 0, no assign occurs
          * anyway, so it is safe to set "datum" to 0
          */
            datum = p->size ? getdat(p) : 0;
            f = 2; /* v[i] <- s */
        }
        ex_elid();

    } else {
        p = newdat(q->itemType, idx.rank, idx.size);
        copy(IN, (char*)idx.dim, (char*)p->dim, idx.rank);
        *sp++ = p;
        f = 0; /* v[i] */
    }
    bidx(q);
    index1(0, f);
    if (f == 0) {
        p = sp[-1];
        sp--;
        for (i = 0; i <= n; i++)
            pop();
        *sp++ = p;
    }
    else {
        pop(); /* pop ELID */
        sp--;  /* skip over LV */
        for (i = 0; i < n; i++)
            pop();
    }
}
Example #12
0
	std::vector<Real> power_spread_swap(Date evaluationDate,
		Real notional,
		PowerSpreadSwap::Side side,
		Rate alpha,
		Schedule floatingSchedule,
		Schedule fixedSchedule,
		DayCounter dayCounter,
		BusinessDayConvention bdc,
		std::vector<Real> gearing,
		std::vector<Real> spread,
		std::vector<Real> caps,
		std::vector<Real> floors,
		bool isAvg,
		Date firstCallDate,
		Real pastFixing,
		Rate floatingFixingRate,
		Real floatingGearing,
		DayCounter floatingDayCounter,
		boost::shared_ptr<StochasticProcess1D> obs1Process,
		boost::shared_ptr<StochasticProcess1D> obs2Process,
		YieldCurveParams disc,
		Real rho12,
		Real rho1disc,
		Real rho2disc,
		Size numSimulation,
		Size numCalibration) {

			Date todaysDate = evaluationDate;
			Settings::instance().evaluationDate() = todaysDate;

			boost::shared_ptr<IborIndex> index1(new Euribor3M(Handle<YieldTermStructure>( disc.yts )));
			boost::shared_ptr<SpreadIndex> index(new SpreadIndex(index1, index1));

			boost::shared_ptr<Callability> callability(new 
				Callability(Callability::Price(notional, Callability::Price::Clean), Callability::Call, firstCallDate));
			CallabilitySchedule callSchedule;
			callSchedule.push_back(callability);

			boost::shared_ptr<StochasticProcess1D> discProcess(new 
				HullWhiteProcess(Handle<YieldTermStructure>(disc.yts), disc.hwParams.a, disc.hwParams.sigma));
			/***********************************************************************************/

			
			Leg floatingcashflows = IborLeg(floatingSchedule, index1)
				.withNotionals(notional)
				.withPaymentDayCounter(floatingDayCounter)
				.withPaymentAdjustment(bdc)
				.withSpreads(alpha)
				.withGearings(floatingGearing)
				.withPaymentAdjustment(bdc);
			
			
			PowerSpreadSwap testProduct(0, notional, side, floatingSchedule, floatingcashflows,
				alpha, 
				fixedSchedule, index, dayCounter, bdc, Null<Natural>(),
				gearing, spread, caps, floors, isAvg, 100.0, Date(), 
				callSchedule, Exercise::Bermudan);


			/*****Pricing Engine*****/
			std::vector<boost::shared_ptr<StochasticProcess1D> > pros;
			pros.push_back(discProcess);
			pros.push_back(obs1Process);
			pros.push_back(obs2Process);
			Matrix corr(3,3,1.0);
			corr[0][1] = corr[1][0] = rho1disc;
			corr[0][2] = corr[2][0] = rho2disc;
			corr[1][2] = corr[2][1] = rho12;

			boost::shared_ptr<StochasticProcessArray> processes(new StochasticProcessArray(pros, corr));

			boost::shared_ptr<PricingEngine> engine_lsmc(new MC_PowerSpread_Swap_Engine_LSMC<>(processes,
				0.03, //pastFixing
				0.03,
				256, //seed 
				numSimulation, //required samples
				numCalibration, //calibration samples
				true, //antithetic
				false,  //control variate
				false //brownian bridge
				));
			testProduct.setPricingEngine(engine_lsmc);

			std::vector<Real> rst;
			rst.push_back(testProduct.NPV());
			rst.push_back(testProduct.errorEstimate());
			return rst;

	}