Exemple #1
0
bool rspfDtedInfo::open(const rspfFilename& file)
{
   bool result = false;

   // Test for extension, like dt0, dt1...
   rspfString ext = file.ext();
   rspfRegExp regExp("^[d|D][t|T][0-9]");
   
   if ( regExp.find( ext.c_str() ) )
   {
      rspfDtedVol vol(file, 0);
      rspfDtedHdr hdr(file, vol.stopOffset());
      rspfDtedUhl uhl(file, hdr.stopOffset());
      rspfDtedDsi dsi(file, uhl.stopOffset());
      rspfDtedAcc acc(file, dsi.stopOffset());
      
      //---
      // Check for errors.  Must have uhl, dsi and acc records.  vol and hdr
      // are for magnetic tape only; hence, may or may not be there.
      //---
      if ( (uhl.getErrorStatus() == rspfErrorCodes::RSPF_OK) &&
           (dsi.getErrorStatus() == rspfErrorCodes::RSPF_OK) &&
           (acc.getErrorStatus() == rspfErrorCodes::RSPF_OK) )
      {
         theFile = file;
         result = true;
      }
      else
      {
         theFile.clear();
      }
   }

   return result;
}
Exemple #2
0
std::ostream& rspfDtedInfo::print(std::ostream& out) const
{
   if ( theFile.size() )
   {
      std::string prefix = "dted.";
      
      rspfDtedVol vol(theFile, 0);
      rspfDtedHdr hdr(theFile, vol.stopOffset());
      rspfDtedUhl uhl(theFile, hdr.stopOffset());
      rspfDtedDsi dsi(theFile, uhl.stopOffset());
      rspfDtedAcc acc(theFile, dsi.stopOffset());
      if( vol.getErrorStatus() == rspfErrorCodes::RSPF_OK )
      {
         vol.print(out, prefix);
      }
      if( hdr.getErrorStatus() == rspfErrorCodes::RSPF_OK )
      {
         hdr.print(out, prefix);
      }
      if( uhl.getErrorStatus() == rspfErrorCodes::RSPF_OK )
      {
         uhl.print(out, prefix);
      }
      if( dsi.getErrorStatus() == rspfErrorCodes::RSPF_OK )
      {
         dsi.print(out, prefix);
      }
      if( acc.getErrorStatus() == rspfErrorCodes::RSPF_OK )
      {
         acc.print(out, prefix);
      }
   }
   return out;
}
Exemple #3
0
// [[Rcpp::export]]
Rcpp::List europeanOptionArraysEngine(std::string type, Rcpp::NumericMatrix par) {

    QuantLib::Option::Type optionType = getOptionType(type);
    int n = par.nrow();
    Rcpp::NumericVector value(n), delta(n), gamma(n), vega(n), theta(n), rho(n), divrho(n);

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

    QuantLib::DayCounter dc = QuantLib::Actual360();

    for (int i=0; i<n; i++) {

        double underlying    = par(i, 0);    // first column
        double strike        = par(i, 1);    // second column
        QuantLib::Spread dividendYield = par(i, 2);    // third column
        QuantLib::Rate riskFreeRate    = par(i, 3);    // fourth column
        QuantLib::Time maturity        = par(i, 4);    // fifth column
#ifdef QL_HIGH_RESOLUTION_DATE    
        // in minutes
        boost::posix_time::time_duration length = boost::posix_time::minutes(boost::uint64_t(maturity * 360 * 24 * 60)); 
#else
        int length           = int(maturity*360 + 0.5); // FIXME: this could be better
#endif
        double volatility    = par(i, 5);    // sixth column
    
        boost::shared_ptr<QuantLib::SimpleQuote> spot(new QuantLib::SimpleQuote( underlying ));
        boost::shared_ptr<QuantLib::SimpleQuote> vol(new QuantLib::SimpleQuote( volatility ));
        boost::shared_ptr<QuantLib::BlackVolTermStructure> volTS = flatVol(today, vol, dc);
        boost::shared_ptr<QuantLib::SimpleQuote> qRate(new QuantLib::SimpleQuote( dividendYield ));
        boost::shared_ptr<QuantLib::YieldTermStructure> qTS = flatRate(today, qRate, dc);
        boost::shared_ptr<QuantLib::SimpleQuote> rRate(new QuantLib::SimpleQuote( riskFreeRate ));
        boost::shared_ptr<QuantLib::YieldTermStructure> rTS = flatRate(today, rRate, dc);
        
#ifdef QL_HIGH_RESOLUTION_DATE
    QuantLib::Date exDate(today.dateTime() + length);
#else
    QuantLib::Date exDate = today + length;
#endif    
        boost::shared_ptr<QuantLib::Exercise> exercise(new QuantLib::EuropeanExercise(exDate));
        
        boost::shared_ptr<QuantLib::StrikedTypePayoff> payoff(new QuantLib::PlainVanillaPayoff(optionType, strike));
        boost::shared_ptr<QuantLib::VanillaOption> option = makeOption(payoff, exercise, spot, qTS, rTS, volTS);
        
        value[i]  = option->NPV();
        delta[i]  = option->delta();
        gamma[i]  = option->gamma();
        vega[i]   = option->vega();
        theta[i]  = option->theta();
        rho[i]    = option->rho();
        divrho[i] = option->dividendRho();
    }
    return Rcpp::List::create(Rcpp::Named("value")  = value,
                              Rcpp::Named("delta")  = delta,
                              Rcpp::Named("gamma")  = gamma,
                              Rcpp::Named("vega")   = vega,
                              Rcpp::Named("theta")  = theta,
                              Rcpp::Named("rho")    = rho,
                              Rcpp::Named("divRho") = divrho);
}
int LuaFilesystem::volumePayload(lua_State *L)
{
    /*
     * Given a volume block code, return the volume's payload data as a string.
     */

    FlashDevice::setStealthIO(1);

    unsigned code = luaL_checkinteger(L, 1);
    FlashVolume vol(FlashMapBlock::fromCode(code));
    if (!vol.isValid()) {
        FlashDevice::setStealthIO(-1);
        lua_pushfstring(L, "invalid volume");
        lua_error(L);
        return 0;
    }

    FlashBlockRef ref;
    FlashMapSpan span = vol.getPayload(ref);

    uint8_t *buffer = new uint8_t[span.sizeInBytes()];
    if (!span.copyBytes(0, buffer, span.sizeInBytes())) {
        delete buffer;
        FlashDevice::setStealthIO(-1);
        lua_pushfstring(L, "I/O error");
        lua_error(L);
        return 0;
    }

    lua_pushlstring(L, (const char *)buffer, span.sizeInBytes());
    FlashDevice::setStealthIO(-1);
    delete buffer;
    return 1;
}
	boost::shared_ptr<Lattice> Generalized_HullWhite::tree(const TimeGrid& grid) const {

		TermStructureFittingParameter phi(termStructure());
		boost::shared_ptr<ShortRateDynamics> numericDynamics(new Dynamics(phi, speed(), vol()));
		boost::shared_ptr<TrinomialTree> trinomial(new TrinomialTree(numericDynamics->process(), grid));
		boost::shared_ptr<ShortRateTree> numericTree(new ShortRateTree(trinomial, numericDynamics, grid));

		typedef TermStructureFittingParameter::NumericalImpl NumericalImpl;
		boost::shared_ptr<NumericalImpl> impl =	boost::dynamic_pointer_cast<NumericalImpl>(phi.implementation());
		impl->reset();
		for (Size i=0; i<(grid.size() - 1); i++) {
			Real discountBond = termStructure()->discount(grid[i+1]);
			const Array& statePrices = numericTree->statePrices(i);
			Size size = numericTree->size(i);
			Time dt = numericTree->timeGrid().dt(i);
			Real dx = trinomial->dx(i);
			Real x = trinomial->underlying(i,0);
			Real value = 0.0;
			for (Size j=0; j<size; j++) {
				value += statePrices[j]*std::exp(-x*dt);
				x += dx;
			}
			value = std::log(value/discountBond)/dt;
			impl->set(grid[i], value);
		}
		return numericTree;
	}
TEST( TriangleSplitter, bugTriangle )
{
   Triangle vol(Vector( 11, -29,  2), 
                Vector( 11, -29, -2), 
                Vector(  0, -29, -2));

   Array<Triangle*> frontSplit;
   Array<Triangle*> backSplit;
   Plane plane;
   plane.set( Float_0, Float_0, Float_1, Float_0 );

   vol.split(plane, frontSplit, backSplit);

   CPPUNIT_ASSERT_EQUAL((unsigned int)1, frontSplit.size());
   CPPUNIT_ASSERT_EQUAL((unsigned int)2, backSplit.size());

   COMPARE_VEC(Vector(  11, -29,  2),  frontSplit[0]->vertex(0));
   COMPARE_VEC(Vector(  11, -29,  0),  frontSplit[0]->vertex(1));
   COMPARE_VEC(Vector(5.5f, -29,  0),  frontSplit[0]->vertex(2));

   COMPARE_VEC(Vector(  11, -29,  0),  backSplit[0]->vertex(0));
   COMPARE_VEC(Vector(  11, -29, -2),  backSplit[0]->vertex(1));
   COMPARE_VEC(Vector(   0, -29, -2),  backSplit[0]->vertex(2));

   COMPARE_VEC(Vector(  11, -29,  0),  backSplit[1]->vertex(0));
   COMPARE_VEC(Vector(   0, -29, -2),  backSplit[1]->vertex(1));
   COMPARE_VEC(Vector(5.5f, -29,  0),  backSplit[1]->vertex(2));

   delete backSplit[0];
   delete backSplit[1];
   delete frontSplit[0];
}
TEST( TriangleSplitter, cuttingTriangleThroughTwoEdges )
{
   Triangle vol(Vector(-1, 0, 1), Vector(1, 0, 1), Vector(-1, 0, -1));

   Array<Triangle*> frontSplit;
   Array<Triangle*> backSplit;
   Plane plane;
   plane.set( Float_1, Float_0, Float_0, Float_0 );
   vol.split( plane, frontSplit, backSplit );

   CPPUNIT_ASSERT_EQUAL((unsigned int)1, frontSplit.size());
   CPPUNIT_ASSERT_EQUAL((unsigned int)2, backSplit.size());

   COMPARE_VEC(Vector( 0, 0,  1), frontSplit[0]->vertex(0));
   COMPARE_VEC(Vector( 1, 0,  1), frontSplit[0]->vertex(1));
   COMPARE_VEC(Vector( 0, 0,  0), frontSplit[0]->vertex(2));

   COMPARE_VEC(Vector(-1, 0,  1), backSplit[0]->vertex(0));
   COMPARE_VEC(Vector( 0, 0,  1), backSplit[0]->vertex(1));
   COMPARE_VEC(Vector( 0, 0,  0), backSplit[0]->vertex(2));

   COMPARE_VEC(Vector(-1, 0,  1), backSplit[1]->vertex(0));
   COMPARE_VEC(Vector( 0, 0,  0), backSplit[1]->vertex(1));
   COMPARE_VEC(Vector(-1, 0, -1), backSplit[1]->vertex(2));

   delete backSplit[0];
   delete backSplit[1];
   delete frontSplit[0];
}
	Real swaption(Date evaluationDate,
		VanillaSwap::Type type,
		Settlement::Type settlementType,
		Real strike,
		Real nominal,
		Date exerciseDate,
		Schedule fixedSchedule,
		DayCounter fixedDayCount,
		Schedule floatSchedule,
		DayCounter floatDayCount,
		Natural fixingDays,
		BusinessDayConvention convention,
		boost::shared_ptr<IborIndex> index,
		boost::shared_ptr<YieldTermStructure> termStructure,
		Volatility volatility) {

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

			boost::shared_ptr<VanillaSwap> swap(new 
				VanillaSwap(type, nominal, fixedSchedule, strike, fixedDayCount, floatSchedule, index, 0.0, floatDayCount, convention));

			Handle<Quote> vol(boost::shared_ptr<Quote>(new SimpleQuote(volatility)));
			boost::shared_ptr<PricingEngine> engine(new BlackSwaptionEngine(Handle<YieldTermStructure>(termStructure), vol));

			boost::shared_ptr<Swaption> testProduct(new
				Swaption(swap, boost::shared_ptr<Exercise>(new EuropeanExercise(exerciseDate)),	settlementType));

			testProduct->setPricingEngine(engine);

			return testProduct->NPV();
	}
TEST( TriangleSplitter, nonStandardTriangle )
{
   Triangle vol(Vector(-1.5f, 0, 1), 
                Vector( 2.5f, 0, 2.5f), 
                Vector( 0.5f, 0,-2.5f));

   Array<Triangle*> frontSplit;
   Array<Triangle*> backSplit;
   Plane plane;
   plane.set( Quad_1000, FastFloat::fromFloat( -1.5f ) );

   vol.split( plane, frontSplit, backSplit );

   CPPUNIT_ASSERT_EQUAL((unsigned int)1, frontSplit.size());
   CPPUNIT_ASSERT_EQUAL((unsigned int)2, backSplit.size());

   COMPARE_VEC(Vector(1.5f, 0, 2.125f),  frontSplit[0]->vertex(0));
   COMPARE_VEC(Vector(2.5f, 0, 2.5f),    frontSplit[0]->vertex(1));
   COMPARE_VEC(Vector(1.5f, 0, 0),       frontSplit[0]->vertex(2));

   COMPARE_VEC(Vector(-1.5f, 0, 1),      backSplit[0]->vertex(0));
   COMPARE_VEC(Vector( 1.5f, 0, 2.125f), backSplit[0]->vertex(1));
   COMPARE_VEC(Vector( 1.5f, 0, 0),      backSplit[0]->vertex(2));

   COMPARE_VEC(Vector(-1.5f, 0, 1),      backSplit[1]->vertex(0));
   COMPARE_VEC(Vector( 1.5f, 0, 0),      backSplit[1]->vertex(1));
   COMPARE_VEC(Vector( 0.5f, 0,-2.5f),   backSplit[1]->vertex(2));

   delete backSplit[0];
   delete backSplit[1];
   delete frontSplit[0];
}
Exemple #10
0
static rt_err_t codec_control(rt_device_t dev, rt_uint8_t cmd, void *args)
{
    switch (cmd)
    {
    case CODEC_CMD_RESET:
        codec_init(dev);
        break;

    case CODEC_CMD_VOLUME:
        vol(*((uint16_t*) args));
        break;

    case CODEC_CMD_SAMPLERATE:
        sample_rate(*((int*) args));
        break;

    case CODEC_CMD_EQ:
        eq((codec_eq_args_t) args);
        break;

    case CODEC_CMD_3D:
        eq3d(*((uint8_t*) args));
        break;

    default:
        return RT_ERROR;
    }
    return RT_EOK;
}
	boost::shared_ptr<Lattice> GeneralizedHullWhite::tree(
                                                  const TimeGrid& grid) const{

		TermStructureFittingParameter phi(termStructure());
		boost::shared_ptr<ShortRateDynamics> numericDynamics(
			new Dynamics(phi, speed(), vol()));
		boost::shared_ptr<TrinomialTree> trinomial(
			new TrinomialTree(numericDynamics->process(), grid));
		boost::shared_ptr<ShortRateTree> numericTree(
			new ShortRateTree(trinomial, numericDynamics, grid));
		typedef TermStructureFittingParameter::NumericalImpl NumericalImpl;
		boost::shared_ptr<NumericalImpl> impl =
			boost::dynamic_pointer_cast<NumericalImpl>(phi.implementation());

		impl->reset();
		Real value = 1.0;
		Real vMin = -50.0;
		Real vMax = 50.0;

		for (Size i=0; i<(grid.size() - 1); i++) {
			Real discountBond = termStructure()->discount(grid[i+1]);
			Real xMin = trinomial->underlying(i, 0);
			Real dx = trinomial->dx(i);
			Helper finder(i, xMin, dx, discountBond, numericTree);
			Brent s1d;
			s1d.setMaxEvaluations(1000);
			value = s1d.solve(finder, 1e-7, value, vMin, vMax);
			impl->set(grid[i], value);
		}

		return numericTree;
	}
Exemple #12
0
int main(int argc, char **argv)
{
  
  DataCube dc(2); // datacube of dimension 2

  Vector<int> size(2); 
  size[1] = 5; // range of datacube in x-direction
  size[2] = 5; // range of datacube in y-direction

  Vector<double> spaceing(2);
  spaceing[1]=1.0;
  spaceing[2]=1.0;

  dc.SetCubeSizeAndSpaceing(size,spaceing); 
  dc.MallocCube();

  // define the dataarray
  for ( int i = 0; i < size[1]; i++ ){
    for ( int j = 0; j < size[2]; j++ ){

      if (  ( i == 2 ) || ( ( i > 1 ) && ( j == 2 ) ) )
	dc(i,j) = 1.0;

    } 
  }

  // test the calculation of moments

  //define volume
  Volume vol(0, 0, 0, 5, 5, spaceing[1], spaceing[2]);

  Moments mom(&dc);

  Vector<double> fp(2);
  int code = mom.focal_point( fp, vol );
  if ( code ) cout << errorCode(code);

  cout << "focal point: ( " << fp[1] << " " << fp[2] << " )" << endl;

  // caluclulate inertian tensor
  Vector<double> i_t(4);
  code = mom.inertian_tensor(i_t, vol );
  if ( code ) cout << errorCode(code);

  cout << "inertian tensor: ( " << i_t[1] << " " << i_t[2] << " )" << endl;
  cout << "                 ( " << i_t[3] << " " << i_t[4] << " )" << endl;

   // calculate inertian values

  Vector<double> ew(2);
  Vector<double> ev(4);
  code = mom.inertian_values(ew,ev,vol);
  if ( code ) cout << errorCode(code);

  cout << "eigenvektor: ( " << ev[1] << " " << ev[2] << " )" << endl;
  cout << "dazu eigenwert: " << ew[1] << endl;
  cout << "eigenvektor: ( " << ev[3] << " " << ev[4] << " )" << endl;
  cout << "dazu eigenwert: " << ew[2] << endl;
 
}
int LuaFilesystem::volumeMap(lua_State *L)
{
    /*
     * Given a volume block code, return the volume's map
     * as an array of block codes.
     */

    FlashDevice::setStealthIO(1);

    unsigned code = luaL_checkinteger(L, 1);
    FlashVolume vol(FlashMapBlock::fromCode(code));
    if (!vol.isValid()) {
        FlashDevice::setStealthIO(-1);
        lua_pushfstring(L, "invalid volume");
        lua_error(L);
        return 0;
    }

    FlashBlockRef ref;
    FlashVolumeHeader *hdr = FlashVolumeHeader::get(ref, vol.block);
    const FlashMap *map = hdr->getMap();

    lua_newtable(L);

    for (unsigned I = 0, E = hdr->numMapEntries(); I != E; ++I) {
        lua_pushnumber(L, I + 1);
        lua_pushnumber(L, map->blocks[I].code);
        lua_settable(L, -3);
    }

    FlashDevice::setStealthIO(-1);
    return 1;
}
int LuaFilesystem::volumeEraseCounts(lua_State *L)
{
    /*
     * Given a volume block code, return the volume's array of erase counts.
     */

    FlashDevice::setStealthIO(1);

    unsigned code = luaL_checkinteger(L, 1);
    FlashVolume vol(FlashMapBlock::fromCode(code));
    if (!vol.isValid()) {
        FlashDevice::setStealthIO(-1);
        lua_pushfstring(L, "invalid volume");
        lua_error(L);
        return 0;
    }

    FlashBlockRef hdrRef, eraseRef;
    FlashVolumeHeader *hdr = FlashVolumeHeader::get(hdrRef, vol.block);
    unsigned numMapEntries = hdr->numMapEntries();

    lua_newtable(L);

    for (unsigned I = 0; I != numMapEntries; ++I) {
        lua_pushnumber(L, I + 1);
        lua_pushnumber(L, hdr->getEraseCount(eraseRef, vol.block, I, numMapEntries));
        lua_settable(L, -3);
    }

    FlashDevice::setStealthIO(-1);
    return 1;
}
int LuaFilesystem::writeObject(lua_State *L)
{
    /*
     * Write an LFS object. (volume, key, data) -> ()
     */

    size_t dataStrLen = 0;
    unsigned code = luaL_checkinteger(L, 1);
    unsigned key = luaL_checkinteger(L, 2);
    const uint8_t *dataStr = (const uint8_t*) lua_tolstring(L, 3, &dataStrLen);

    FlashVolume vol(FlashMapBlock::fromCode(code));
    if (code && !vol.isValid()) {
        lua_pushfstring(L, "invalid volume");
        lua_error(L);
        return 0;
    }

    if (FlashVolume::typeIsRecyclable(vol.getType())) {
        lua_pushinteger(L, -1);
        return 1;
    }

    if (!FlashLFSIndexRecord::isKeyAllowed(key)) {
        lua_pushfstring(L, "invalid key");
        lua_error(L);
        return 0;
    }

    if (!FlashLFSIndexRecord::isSizeAllowed(dataStrLen)) {
        lua_pushfstring(L, "invalid data size");
        lua_error(L);
        return 0;
    }

    CrcStream cs;
    cs.reset();
    cs.addBytes(dataStr, dataStrLen);
    uint32_t crc = cs.get(FlashLFSIndexRecord::SIZE_UNIT);

    FlashDevice::setStealthIO(1);

    FlashLFS &lfs = FlashLFSCache::get(vol);
    FlashLFSObjectAllocator allocator(lfs, key, dataStrLen, crc);

    if (!allocator.allocateAndCollectGarbage()) {
        FlashDevice::setStealthIO(-1);
        lua_pushfstring(L, "out of space");
        lua_error(L);
        return 0;
    }

    FlashBlock::invalidate(allocator.address(), allocator.address() + dataStrLen);
    FlashDevice::write(allocator.address(), dataStr, dataStrLen);

    FlashDevice::setStealthIO(-1);
    lua_pushinteger(L, 0);
    return 1;
}
// [[Rcpp::export]]
SEXP get_volume(std::string filename){
  MincVolume vol(filename);
  SEXP res = PROTECT(Rf_allocVector(REALSXP, vol.size()));
  double* real_res = REAL(res);
  vol.read_volume_to_buffer(real_res, MI_TYPE_DOUBLE);
  UNPROTECT(1);
  return(res);
}
// dumped core when we tried last
// no longer under 0.3.10 and g++ 4.0.1 (Aug 2005)
// [[Rcpp::export]]
double binaryOptionImpliedVolatilityEngine(std::string type,
                                           double value,
                                           double underlying,
                                           double strike,
                                           double dividendYield, 
                                           double riskFreeRate,
                                           double maturity,
                                           double volatility,
                                           double cashPayoff) {

#ifdef QL_HIGH_RESOLUTION_DATE    
    // in minutes
    boost::posix_time::time_duration length = boost::posix_time::minutes(maturity * 360 * 24 * 60); 
#else
    int length = int(maturity*360 + 0.5); // FIXME: this could be better
#endif

    QuantLib::Option::Type optionType = getOptionType(type);

    // updated again for QuantLib 0.9.0, 
    // cf QuantLib-0.9.0/test-suite/digitaloption.cpp
    QuantLib::Date today = QuantLib::Date::todaysDate();
    QuantLib::Settings::instance().evaluationDate() = today;
    QuantLib::DayCounter dc = QuantLib::Actual360();
    boost::shared_ptr<QuantLib::SimpleQuote> spot(new QuantLib::SimpleQuote(underlying));
    boost::shared_ptr<QuantLib::SimpleQuote> qRate(new QuantLib::SimpleQuote(dividendYield));
    boost::shared_ptr<QuantLib::YieldTermStructure> qTS = flatRate(today, qRate, dc);
    boost::shared_ptr<QuantLib::SimpleQuote> rRate(new QuantLib::SimpleQuote(riskFreeRate));
    boost::shared_ptr<QuantLib::YieldTermStructure> rTS = flatRate(today, rRate, dc);
    boost::shared_ptr<QuantLib::SimpleQuote> vol(new QuantLib::SimpleQuote(volatility));
    boost::shared_ptr<QuantLib::BlackVolTermStructure> volTS = flatVol(today, vol, dc);
    
    boost::shared_ptr<QuantLib::StrikedTypePayoff> 
        payoff(new QuantLib::CashOrNothingPayoff(optionType, strike, cashPayoff));

#ifdef QL_HIGH_RESOLUTION_DATE
    QuantLib::Date exDate(today.dateTime() + length);
#else
    QuantLib::Date exDate = today + length;
#endif    
    
    boost::shared_ptr<QuantLib::Exercise> exercise(new QuantLib::EuropeanExercise(exDate));

    boost::shared_ptr<QuantLib::BlackScholesMertonProcess> 
        stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle<QuantLib::Quote>(spot),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(qTS),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(rTS),
                                                             QuantLib::Handle<QuantLib::BlackVolTermStructure>(volTS)));
    //boost::shared_ptr<PricingEngine> engine(new AnalyticEuropeanEngine(stochProcess));
    boost::shared_ptr<QuantLib::PricingEngine> engine(new QuantLib::AnalyticBarrierEngine(stochProcess));

    QuantLib::VanillaOption opt(payoff, exercise);
    opt.setPricingEngine(engine);

    return opt.impliedVolatility(value, stochProcess);
}
Exemple #18
0
 Real SwaptionHelper::blackPrice(Volatility sigma) const {
     calculate();
     Handle<Quote> vol(boost::shared_ptr<Quote>(new SimpleQuote(sigma)));
     boost::shared_ptr<PricingEngine> black(new
                                 BlackSwaptionEngine(termStructure_, vol));
     swaption_->setPricingEngine(black);
     Real value = swaption_->NPV();
     swaption_->setPricingEngine(engine_);
     return value;
 }
Exemple #19
0
void test_gliss_sin() {
	Sine vox;
	LineSegment line(3, 100, 800);
	vox.set_frequency(line);
	StaticVariable vol(0.1);
	MulOp mul(vox, vol);
	logMsg("playing gliss sin...");
	run_test(mul);
	logMsg("gliss sin done.");
}
Exemple #20
0
int V4LRadioControl::volume() const
{
    const QString ctlName("Line DAC Playback Volume");
    const QString card("hw:0");

    int volume = 0;
    int err;
    static snd_ctl_t *handle = NULL;
    snd_ctl_elem_info_t *info;
    snd_ctl_elem_id_t *id;
    snd_ctl_elem_value_t *control;

    snd_ctl_elem_info_alloca(&info);
    snd_ctl_elem_id_alloca(&id);
    snd_ctl_elem_value_alloca(&control);
    snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER);	/* MIXER */

    snd_ctl_elem_id_set_name(id, ctlName.toAscii());

    if ((err = snd_ctl_open(&handle, card.toAscii(), 0)) < 0) {
        return 0;
    }

    snd_ctl_elem_info_set_id(info, id);
    if ((err = snd_ctl_elem_info(handle, info)) < 0) {
        snd_ctl_close(handle);
        handle = NULL;
        return 0;
    }

    snd_ctl_elem_info_get_id(info, id);	/* FIXME: Remove it when hctl find works ok !!! */
    snd_ctl_elem_value_set_id(control, id);

    snd_ctl_close(handle);
    handle = NULL;

    snd_hctl_t *hctl;
    snd_hctl_elem_t *elem;
    if ((err = snd_hctl_open(&hctl, card.toAscii(), 0)) < 0) {
        return 0;
    }
    if ((err = snd_hctl_load(hctl)) < 0) {
        return 0;
    }
    elem = snd_hctl_find_elem(hctl, id);
    if (elem)
        volume = vol(elem);

    snd_hctl_close(hctl);

    return (volume/118.0) * 100;
}
void VolRenRaycastCuda::raycast(const QMatrix4x4&, const QMatrix4x4& matView, const QMatrix4x4&)
{
    cc(cudaGraphicsMapResources(1, &entryRes, 0));
    cc(cudaGraphicsMapResources(1, &exitRes, 0));
    cc(cudaGraphicsMapResources(1, &outRes, 0));
    cc(cudaGraphicsMapResources(1, &volRes, 0));
    cc(cudaGraphicsMapResources(1, &tfFullRes, 0));
    cc(cudaGraphicsMapResources(1, &tfBackRes, 0));

    cudaArray *entryArr, *exitArr, *volArr, *tfFullArr, *tfBackArr;
    float *outPtr;
    size_t nBytes;
    cc(cudaGraphicsSubResourceGetMappedArray(&entryArr, entryRes, 0, 0));
    cc(cudaGraphicsSubResourceGetMappedArray(&exitArr, exitRes, 0, 0));
    cc(cudaGraphicsResourceGetMappedPointer((void**)&outPtr, &nBytes, outRes));
    cc(cudaGraphicsSubResourceGetMappedArray(&volArr, volRes, 0, 0));
    cc(cudaGraphicsSubResourceGetMappedArray(&tfFullArr, tfFullRes, 0, 0));
    cc(cudaGraphicsSubResourceGetMappedArray(&tfBackArr, tfBackRes, 0, 0));

    static std::map<Filter, cudaTextureFilterMode> vr2cu
            = { { Filter_Linear, cudaFilterModeLinear }
              , { Filter_Nearest, cudaFilterModePoint } };
    assert(vr2cu.count(tfFilter) > 0);

    updateCUDALights(matView);

    cudacast(vol()->w(), vol()->h(), vol()->d(), volArr,
             tfInteg->getTexFull()->width(), tfInteg->getTexFull()->height(), stepsize, vr2cu[tfFilter], tfFullArr, tfBackArr,
             scalarMin, scalarMax,
             frustum.getTextureWidth(), frustum.getTextureHeight(), entryArr, exitArr, outPtr);

    cc(cudaGraphicsUnmapResources(1, &tfBackRes, 0));
    cc(cudaGraphicsUnmapResources(1, &tfFullRes, 0));
    cc(cudaGraphicsUnmapResources(1, &volRes, 0));
    cc(cudaGraphicsUnmapResources(1, &entryRes, 0));
    cc(cudaGraphicsUnmapResources(1, &exitRes, 0));
    cc(cudaGraphicsUnmapResources(1, &outRes, 0));
}
Exemple #22
0
Scheme<double> Cell::phi(vector<shared_ptr<Boundary> > const &bc, int_2 bias) {
  Scheme<double> sch; 
  if (next < 0 && prev < 0) {
    sch.push_pair(id, 1.0); 
  } else {
    // use next and prev to compute phi;
    if (next >= 0 && prev >= 0) {
      if (bias == 0) {
	double dn = abs((grid->listCell[next]->getCoord() - getCoord())*vol()); 
	double dp = abs((grid->listCell[prev]->getCoord() - getCoord())*vol()); 
	sch.push_pair(prev, dn/(dn+dp)); 
	sch.push_pair(next, dp/(dn+dp)); 
      } else if (bias == -1) { 
	sch.push_pair(prev, 1.0); 
      } else if (bias == 1) { 
	sch.push_pair(next, 1.0); 
      }
    } else {
      auto bndr = (prev >= 0) ? -next-1 : -prev-1; 
      auto row = (prev >= 0) ? prev : next; 
      if (bc[bndr]->type == 0) { 
	sch.push_constant(bc[bndr]->b_val);
	sch.push_pair(row, bc[bndr]->a_val); 
      } else if (bc[bndr]->type == 1) {
	auto c0 = grid->listCell[row]; 
	auto norm = vol(); norm = norm/norm.abs(); 
	double dx = norm*(getCoord() - c0->getCoord()); 
	sch.push_constant(dx*bc[bndr]->b_val);
	sch.push_pair(row, (1.0 + dx*bc[bndr]->a_val)); 
      } else { 
	cout << "Cell (Quad) :: interp :: boundary condition type not recognized " << endl; 
	exit(1); 
      }
 
    }
  }
  return sch; 
}
Exemple #23
0
void test_fm_sin() {
	Sine vox, mod;
	vox.set_frequency(261);
	mod.set_frequency(261);
	DynamicVariable fm(250, mod);
	StaticVariable offset(261);
	AddOp adder(offset, fm);
	vox.set_frequency(adder);
	StaticVariable vol(0.1);
	MulOp mul(vox, vol);
	logMsg("playing FM sin...");
	run_test(mul);
	logMsg("FM sin done.");
}
osg::ref_ptr<ossimPlanetDtedElevationDatabase::DtedInfo> ossimPlanetDtedElevationDatabase::getInfo(const std::string& name)
{
   OpenThreads::ScopedLock<OpenThreads::Mutex> lock(theDtedInfoMutex);
   DtedFilePointerList::iterator iter = theFilePointers.find(name);

   if(iter != theFilePointers.end())
   {
      iter->second->theTimeStamp = osg::Timer::instance()->tick();

      return iter->second;
   }
   osg::ref_ptr<DtedInfo> info     = new DtedInfo;
   
   ossimFilename dtedFile = ossimFilename(theLocation).dirCat(ossimFilename(name));

   ifstream in;

   in.open(dtedFile.c_str(), std::ios::binary|std::ios::in);

   if(in.fail()) return 0;

   ossimDtedVol vol(in);
   ossimDtedHdr hdr(in);
   ossimDtedUhl uhl(in);

   in.close();
   
   if((uhl.getErrorStatus() == ossimErrorCodes::OSSIM_ERROR))
   {
      return 0;
   }
   info->theNumLonLines  = uhl.numLonLines();
   info->theNumLatPoints = uhl.numLatPoints();
   info->theLatSpacing   = uhl.latInterval();
   info->theLonSpacing   = uhl.lonInterval();
   info->theMinLat = uhl.latOrigin();
   info->theMinLon = uhl.lonOrigin();
   info->theMaxLat = info->theMinLat + info->theLatSpacing*(info->theNumLatPoints-1);
   info->theMaxLon = info->theMinLon + info->theLonSpacing*(info->theNumLonLines-1);
   info->theTimeStamp  = osg::Timer::instance()->tick();
   info->theFilename   = dtedFile;
   info->theHandler = new ossimDtedHandler(dtedFile, false);
   //info->theHandler->setMemoryMapFlag(false);
   theFilePointers.insert(std::make_pair(name, info));
   shrinkFilePointers();
   
   return info;
   
}
    Volatility StrippedOptionletAdapter::volatilityImpl(Time length,
                                                        Rate strike) const {
        calculate();

        std::vector<Volatility> vol(nInterpolations_);
        for (Size i=0; i<nInterpolations_; ++i)
            vol[i] = strikeInterpolations_[i]->operator()(strike, true);

        const std::vector<Time>& optionletTimes =
                                    optionletStripper_->optionletFixingTimes();
        boost::shared_ptr<LinearInterpolation> timeInterpolator(new
            LinearInterpolation(optionletTimes.begin(), optionletTimes.end(),
                                vol.begin()));
        return timeInterpolator->operator()(length, true);
    }
Exemple #26
0
double Cell::phiVal_bcface(VecX<double> &phi, vector<shared_ptr<Boundary> > const &bc, int_2 const &bias) {
  auto bndr = (prev >= 0) ? -next-1 : -prev-1; 
  auto row = (prev >= 0) ? prev : next; 
  if (bc[bndr]->type == 0) { 
    return bc[bndr]->b_val + phi[row]*bc[bndr]->a_val; 
  } else if (bc[bndr]->type == 1) {
    auto c0 = grid->listCell[row]; 
    auto norm = vol(); norm = norm/norm.abs(); 
    double dx = norm*(getCoord() - c0->getCoord()); 
    return dx*bc[bndr]->b_val + phi[row]*(1.0 + dx*bc[bndr]->a_val); 
  } else { 
    cout << "Cell (Quad) :: interp :: boundary condition type not recognized " << endl; 
    exit(1); 
  }
}
Exemple #27
0
//------------------------------------------------------------------------------
void SdFatBase::initErrorPrint(Print* pr) {
  if (cardErrorCode()) {
    pr->println(F("Can't access SD card. Do not reformat."));
    if (cardErrorCode() == SD_CARD_ERROR_CMD0) {
      pr->println(F("No card, wrong chip select pin, or SPI problem?"));
    }
    errorPrint(pr);
  } else if (vol()->fatType() == 0) {
    pr->println(F("Invalid format, reformat SD."));
  } else if (!vwd()->isOpen()) {
    pr->println(F("Can't open root directory."));
  } else {
    pr->println(F("No error found."));
  }
}
Exemple #28
0
// [[Rcpp::export]]
double europeanOptionImpliedVolatilityEngine(std::string type,
                                             double value,
                                             double underlying,
                                             double strike,
                                             double dividendYield,
                                             double riskFreeRate,
                                             double maturity,
                                             double volatility) {

    const QuantLib::Size maxEvaluations = 100;
    const double tolerance = 1.0e-6;
  
    int length = int(maturity*360 + 0.5); // FIXME: this could be better

    QuantLib::Option::Type optionType = getOptionType(type);

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

    // new framework as per QuantLib 0.3.5
    // updated for 0.3.7
    QuantLib::DayCounter dc = QuantLib::Actual360();

    boost::shared_ptr<QuantLib::SimpleQuote> spot(new QuantLib::SimpleQuote(underlying));
    boost::shared_ptr<QuantLib::SimpleQuote> vol(new QuantLib::SimpleQuote(volatility));
    boost::shared_ptr<QuantLib::BlackVolTermStructure> volTS = flatVol(today, vol, dc);
    boost::shared_ptr<QuantLib::SimpleQuote> qRate(new QuantLib::SimpleQuote(dividendYield));
    boost::shared_ptr<QuantLib::YieldTermStructure> qTS = flatRate(today,qRate,dc);
    boost::shared_ptr<QuantLib::SimpleQuote> rRate(new QuantLib::SimpleQuote(riskFreeRate));
    boost::shared_ptr<QuantLib::YieldTermStructure> rTS = flatRate(today,rRate,dc);
    QuantLib::Date exDate = today + length;
    boost::shared_ptr<QuantLib::Exercise> exercise(new QuantLib::EuropeanExercise(exDate));
    boost::shared_ptr<QuantLib::StrikedTypePayoff> payoff(new QuantLib::PlainVanillaPayoff(optionType, strike));
    boost::shared_ptr<QuantLib::VanillaOption> 
        option = makeOption(payoff, exercise, spot, qTS, rTS, 
                            volTS, Analytic, 
                            QuantLib::Null<QuantLib::Size>(), 
                            QuantLib::Null<QuantLib::Size>());

    boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess> 
        process = makeProcess(spot, qTS, rTS,volTS);

    double volguess = volatility;
    vol->setValue(volguess);

    return option->impliedVolatility(value, process, tolerance, maxEvaluations);
}
	std::vector<Real> cap_floor(Date evaluationDate,
		CapFloor::Type type,
		Real strike,
		Real nominal,
		Schedule schedule,
		Natural fixingDays,
		BusinessDayConvention convention,
		boost::shared_ptr<IborIndex> index,
		boost::shared_ptr<YieldTermStructure> termStructure,
		Volatility volatility) {

			Date todaysDate = evaluationDate;
			Settings::instance().evaluationDate() = todaysDate;
			std::vector<Real> nominals = std::vector<Real>(1, nominal);		

			/*Make Leg*/
			Leg leg = IborLeg(schedule, index)
				.withNotionals(nominals)
				.withPaymentDayCounter(index->dayCounter())
				.withPaymentAdjustment(convention)
				.withFixingDays(fixingDays);

			/*Make Engine*/
			Handle<Quote> vol(boost::shared_ptr<Quote>(new SimpleQuote(volatility)));
			boost::shared_ptr<PricingEngine> engine = 
				boost::shared_ptr<PricingEngine>(new BlackCapFloorEngine(Handle<YieldTermStructure>(termStructure), vol));

			/*Pricing*/
			boost::shared_ptr<CapFloor> testProduct;
			switch (type) {
			case CapFloor::Cap:
				testProduct = boost::shared_ptr<CapFloor>(new Cap(leg, std::vector<Rate>(1, strike)));
				break;
			case CapFloor::Floor:
				testProduct = boost::shared_ptr<CapFloor>(new Floor(leg, std::vector<Rate>(1, strike)));
				break;
			default:
				QL_FAIL("unknown cap/floor type");
			}

			testProduct->setPricingEngine(engine);

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

	}
Exemple #30
0
int main(int argc, char *argv[])
{
  int T;
  scanf("%d", &T);
  while(T--){
    double r, R, H, V;
    scanf("%lf%lf%lf%lf", &r, &R, &H, &V);
    double mid, left=0 ,right=H;
    while(fabs(left-right)>esp){
      mid=(left+right)/2;
      if(vol(r,R,mid,H)>V) right=mid;
      else left=mid;
    }
    printf ("%.6lf\n", mid);
  }
  return 0;
}