ZoneHVACLowTempRadiantVarFlow::ZoneHVACLowTempRadiantVarFlow(const Model& model,
                                                             Schedule& availabilitySchedule,
                                                             HVACComponent& heatingCoil,
                                                             HVACComponent& coolingCoil)
                                                             
  : ZoneHVACComponent(ZoneHVACLowTempRadiantVarFlow::iddObjectType(),model)
{
  OS_ASSERT(getImpl<detail::ZoneHVACLowTempRadiantVarFlow_Impl>());

  bool ok = setAvailabilitySchedule(availabilitySchedule);
  
  if (!ok) 
  {
    remove();
    LOG_AND_THROW("Unable to set " << briefDescription() << "'s availability schedule to "
                  << availabilitySchedule.briefDescription() << ".");
  }
  
  ok = setHeatingCoil(heatingCoil);
  OS_ASSERT(ok);

  ok = setCoolingCoil(coolingCoil);
  OS_ASSERT(ok);
} 
Example #2
0
void CPISwapTest::cpibondconsistency() {
    CommonVars common;

    // ZeroInflationSwap aka CPISwap

    CPISwap::Type type = CPISwap::Payer;
    Real nominal = 1000000.0;
    bool subtractInflationNominal = true;
    // float+spread leg
    Spread spread = 0.0;
    DayCounter floatDayCount = Actual365Fixed();
    BusinessDayConvention floatPaymentConvention = ModifiedFollowing;
    Natural fixingDays = 0;
    ext::shared_ptr<IborIndex> floatIndex(new GBPLibor(Period(6,Months),
                                                         common.nominalTS));

    // fixed x inflation leg
    Rate fixedRate = 0.1;//1% would be 0.01
    Real baseCPI = 206.1; // would be 206.13871 if we were interpolating
    DayCounter fixedDayCount = Actual365Fixed();
    BusinessDayConvention fixedPaymentConvention = ModifiedFollowing;
    Calendar fixedPaymentCalendar = UnitedKingdom();
    ext::shared_ptr<ZeroInflationIndex> fixedIndex = common.ii;
    Period contractObservationLag = common.contractObservationLag;
    CPI::InterpolationType observationInterpolation = common.contractObservationInterpolation;

    // set the schedules
    Date startDate(2, October, 2007);
    Date endDate(2, October, 2052);
    Schedule floatSchedule = MakeSchedule().from(startDate).to(endDate)
    .withTenor(Period(6,Months))
    .withCalendar(UnitedKingdom())
    .withConvention(floatPaymentConvention)
    .backwards()
    ;
    Schedule fixedSchedule = MakeSchedule().from(startDate).to(endDate)
    .withTenor(Period(6,Months))
    .withCalendar(UnitedKingdom())
    .withConvention(Unadjusted)
    .backwards()
    ;


    CPISwap zisV(type, nominal, subtractInflationNominal,
                 spread, floatDayCount, floatSchedule,
                 floatPaymentConvention, fixingDays, floatIndex,
                 fixedRate, baseCPI, fixedDayCount, fixedSchedule,
                 fixedPaymentConvention, contractObservationLag,
                 fixedIndex, observationInterpolation);

    Real floatFix[] = {0.06255,0.05975,0.0637,0.018425,0.0073438,-1,-1};
    Real cpiFix[] = {211.4,217.2,211.4,213.4,-2,-2};
    for(Size i=0;i<floatSchedule.size(); i++){
        if (floatSchedule[i] < common.evaluationDate) {
            floatIndex->addFixing(floatSchedule[i], floatFix[i],true);//true=overwrite
        }

        ext::shared_ptr<CPICoupon>
        zic = ext::dynamic_pointer_cast<CPICoupon>(zisV.cpiLeg()[i]);
        if (zic) {
            if (zic->fixingDate() < (common.evaluationDate - Period(1,Months))) {
                fixedIndex->addFixing(zic->fixingDate(), cpiFix[i],true);
            }
        }
    }


    // simple structure so simple pricing engine - most work done by index
    ext::shared_ptr<DiscountingSwapEngine>
    dse(new DiscountingSwapEngine(common.nominalTS));

    zisV.setPricingEngine(dse);

    // now do the bond equivalent
    std::vector<Rate> fixedRates(1,fixedRate);
    Natural settlementDays = 1;// cannot be zero!
    bool growthOnly = true;
    CPIBond cpiB(settlementDays, nominal, growthOnly,
                 baseCPI, contractObservationLag, fixedIndex,
                 observationInterpolation, fixedSchedule,
                 fixedRates, fixedDayCount, fixedPaymentConvention);

    ext::shared_ptr<DiscountingBondEngine>
    dbe(new DiscountingBondEngine(common.nominalTS));
    cpiB.setPricingEngine(dbe);

    QL_REQUIRE(fabs(cpiB.NPV() - zisV.legNPV(0))<1e-5,"cpi bond does not equal equivalent cpi swap leg");
    // remove circular refernce
    common.hcpi.linkTo(ext::shared_ptr<ZeroInflationTermStructure>());
}
boost::optional<IdfObject> ForwardTranslator::translateFanConstantVolume( FanConstantVolume& modelObject )
{
  OptionalString s;
  OptionalDouble d;
  OptionalModelObject temp;

  // Create a new IddObjectType::Fan_ConstantVolume
  IdfObject idfObject(IddObjectType::Fan_ConstantVolume);

  ///////////////////////////////////////////////////////////////////////////
  // Field: Name ////////////////////////////////////////////////////////////
  s = modelObject.name();
  if(s)
  {
    idfObject.setName(*s);
  }
  ///////////////////////////////////////////////////////////////////////////


  // hook up required objects
  try {
    if( boost::optional<model::AirLoopHVAC> airLoopHVAC = modelObject.airLoopHVAC() )
    {
      Schedule sched = airLoopHVAC->availabilitySchedule();
      boost::optional<IdfObject> schedIdf = translateAndMapModelObject(sched);
      if( schedIdf )
      {
        idfObject.setString(Fan_ConstantVolumeFields::AvailabilityScheduleName,schedIdf->name().get());
      }
    }
    else
    {
      Schedule sched = modelObject.availabilitySchedule();
      translateAndMapModelObject(sched);
      idfObject.setString(Fan_ConstantVolumeFields::AvailabilityScheduleName,sched.name().get());
    }
  }
  catch (std::exception& e) {
    LOG(Error,"Could not translate " << modelObject.briefDescription() << ", because " 
        << e.what() << ".");
    return boost::none;
  }


  ///////////////////////////////////////////////////////////////////////////
  // Fan Efficiency /////////////////////////////////////////////////////////
  idfObject.setDouble(openstudio::Fan_ConstantVolumeFields::FanTotalEfficiency,modelObject.fanEfficiency());
  ///////////////////////////////////////////////////////////////////////////

  ///////////////////////////////////////////////////////////////////////////
  // Pressure Rise //////////////////////////////////////////////////////////
  idfObject.setDouble(openstudio::Fan_ConstantVolumeFields::PressureRise,modelObject.pressureRise());
  ///////////////////////////////////////////////////////////////////////////

  ///////////////////////////////////////////////////////////////////////////
  // Maximum Flow Rate //////////////////////////////////////////////////////
  d = modelObject.maximumFlowRate();
  if(d)
  {
    idfObject.setDouble(openstudio::Fan_ConstantVolumeFields::MaximumFlowRate,*d);
  }
  else
  {
    idfObject.setString(openstudio::Fan_ConstantVolumeFields::MaximumFlowRate,"AutoSize");
  }
  ///////////////////////////////////////////////////////////////////////////

  ///////////////////////////////////////////////////////////////////////////
  // Motor Efficiency ///////////////////////////////////////////////////////
  idfObject.setDouble(openstudio::Fan_ConstantVolumeFields::MotorEfficiency,modelObject.motorEfficiency());
  ///////////////////////////////////////////////////////////////////////////

  ///////////////////////////////////////////////////////////////////////////
  // Motor In Airstream Fraction ////////////////////////////////////////////
  idfObject.setDouble(openstudio::Fan_ConstantVolumeFields::MotorInAirstreamFraction,modelObject.motorInAirstreamFraction());
  ///////////////////////////////////////////////////////////////////////////

  ///////////////////////////////////////////////////////////////////////////
  // Air Inlet Node Name ////////////////////////////////////////////////////
  temp = modelObject.inletModelObject();
  if(temp)
  {
    s = temp->name();
    if(s)
    {
      idfObject.setString(openstudio::Fan_ConstantVolumeFields::AirInletNodeName,*s);
    }
  }
  ///////////////////////////////////////////////////////////////////////////

  ///////////////////////////////////////////////////////////////////////////
  // Air Outlet Node Name ///////////////////////////////////////////////////
  temp = modelObject.outletModelObject();
  if(temp)
  {
    s = temp->name();
    if(s)
    {
      idfObject.setString(openstudio::Fan_ConstantVolumeFields::AirOutletNodeName,*s);
    }
  }
  ///
  ////////////////////////////////////////////////////////////////////////

  m_idfObjects.push_back(idfObject);
  return boost::optional<IdfObject>(idfObject);
}
Example #4
0
// implements staging scheme for finding the schedule for WFs set
// <PRE> 0 <= firstWfNum < data.workflows.size()
double Scheduler::StagedScheme(int firstWfNum){
   cout << "StagedScheme(int) was called\n";
   try{
      int wfCount = data.GetWFCount();
      if (firstWfNum < 0 || firstWfNum > wfCount) 
         throw UserException("Scheduler::StagedScheme(int) error. Wrong init workflow number");
      // creating XML with init time windows
      //xmlWriter->SetXMLBaseName("Init_");
      Schedule oneWFsched;
      //xmlWriter->CreateXML(oneWFsched, -1);
      // ??!! think about it !
      xmlWriter->SetXMLBaseName("Staged_");
      //double stagedT = clock();

      //string resFileName = "staged_scheme_" + to_string(firstWfNum) + ".txt";
      //ofstream res(resFileName);
      //if (res.fail()) 
      //	throw UserException("Scheduler::StagedScheme(int) error. Unable to create res file");
      //res << "Stage 1, workflow # " << firstWfNum << endl;
      //cout << "Stage 1, workflow # " << firstWfNum << endl;
      
      vector <double> eff;
      // applying settings of scheduling method for initial WF
      unique_ptr <SchedulingMethod> method = SchedulingFactory::GetMethod(data, methodsSet[firstWfNum], firstWfNum);
      // getting schedule for first WF
      double oneStepStart = clock();
      eff.push_back(method->GetWFSchedule(oneWFsched));

      // set local to global packages
      int initNum = data.GetInitPackageNumber(firstWfNum);
      for (int i = 0; i < oneWFsched.size(); i++)
         oneWFsched[i].get<0>() += initNum;


      fullSchedule = oneWFsched;
      
      //cout << "Elapsed time: " << (clock()-oneStepStart)/1000.0 << " sec" << endl;
      scheduledWFs.push_back(firstWfNum);	
      //xmlWriter->CreateXML(oneWFsched, firstWfNum);
      // write result to XML
      data.FixBusyIntervals();

      
      // write result to res file
      //PrintOneWFSched(res, oneWFsched, firstWfNum);
      
      
      // we need to store current busy intervals
      // of schedule that give the best efficiency
      // current best schedule is stored in oneWFsched
      vector<vector <BusyIntervals>> storedIntervals;
      Schedule storedSched;

      while (scheduledWFs.size() != wfCount ){
         //cout << "Stage " << scheduledWFs.size() + 1 << endl;
         double stageMaxEff = numeric_limits<double>::infinity();
         int bestWfNum = -1;
         for (int i = 0; i < wfCount; i++){
            // if this WF wasn't scheduled yet
            if (find(scheduledWFs.begin(), scheduledWFs.end(), i) == scheduledWFs.end()){
               //cout << "CurrentWfNum = " << i << " ";
               oneStepStart = clock();
               method = SchedulingFactory::GetMethod(data, methodsSet[i], i);
               oneWFsched.clear();
               double currentEff = method->GetWFSchedule(oneWFsched);
               //cout << "Elapsed time: " << (clock()-oneStepStart)/1000.0 << " sec" << endl;
               /*ReadData(i);
               directBellman = false;
               BackBellmanProcedure();
               directBellman = true;
               double currentEff = DirectBellman(i);*/
               if (stageMaxEff > currentEff){
                  stageMaxEff = currentEff;
                  bestWfNum = i;
                  storedSched = oneWFsched;
                  storedIntervals.clear();
                  data.GetCurrentIntervals(storedIntervals);
                  //GetBestBusyIntervals(bestBusyIntervals);
               }
               data.ResetBusyIntervals(); // newfag in my program
               //states.clear(); controls.clear(); nextStateNumbers.clear(); stagesCores.clear();
            }
         }
         // set local to global packages
         int initNum = data.GetInitPackageNumber(bestWfNum);
         for (int i = 0; i < storedSched.size(); i++)
            storedSched[i].get<0>() += initNum;

         copy(storedSched.begin(), storedSched.end(), back_inserter(fullSchedule));
         //copy(bestStagesCores.begin(), bestStagesCores.end(),back_inserter(allStagesCores));
         scheduledWFs.push_back(bestWfNum);
         //usedNums = scheduledWFs; ???
         //stagesCores = bestStagesCores;
         //currentWfNum = bestWfNum;
         eff.push_back(stageMaxEff);
         // set current intervals as stored intervals
         data.SetCurrentIntervals(storedIntervals);
         // write result to XML
         // xmlWriter->CreateXML(storedSched, bestWfNum);
         // write result to res file
      //	PrintOneWFSched(res, storedSched, bestWfNum);
           
         data.FixBusyIntervals();
         
         /*SetBestBusyIntervals(bestBusyIntervals);
         FixNewBusyIntervals();
         BellmanToXML(true);*/
         //std::system("pause");
      }
      /*usedNums = scheduledWFs; ???
      SetFirstBusyIntervals();
      stagesCores = allStagesCores;
      BellmanToXML(false);*/
      //PrintFooter(res, eff);
      double sumEff = 0.0;
      for (int i = 0; i < eff.size(); i++)
         sumEff += eff[i];
      
      data.SetInitBusyIntervals();
      //xmlWriter->CreateXML(fullSchedule, -1);
      //res.close();
      cout << "Max eff: " << sumEff/maxPossible << endl;
      //cout << "Elapsed time: " << (clock()-stagedT)/1000.0 << " sec" << endl;
      return sumEff/maxPossible ;
   }
   catch (UserException& e){
      cout<<"error : " << e.what() <<endl;
      std::system("pause");
      exit(EXIT_FAILURE);
   }
}
boost::optional<IdfObject> ForwardTranslator::translateZoneHVACBaseboardConvectiveWater(
    ZoneHVACBaseboardConvectiveWater & modelObject )
{
  // Makes sure the modelObject gets put in the map, and that the new idfObject gets put in 
  // the final file. Also set's the idfObject's name.
  IdfObject idfObject = createRegisterAndNameIdfObject(IddObjectType::ZoneHVAC_Baseboard_Convective_Water,modelObject);

  boost::optional<std::string> s;
  boost::optional<double> value;
  boost::optional<ModelObject> temp;
  //get the heating coil as a straight component, cast it to optional HT coil, if cast is successful, 
  //get the object of class CoilHeatingWaterBaseboard
  StraightComponent coilStraight = modelObject.heatingCoil();
  boost::optional<CoilHeatingWaterBaseboard>  coilOptionalHeatBBConvWater = coilStraight.optionalCast<CoilHeatingWaterBaseboard>();
  
  // AvailabilityScheduleName
  Schedule availabilitySchedule = modelObject.availabilitySchedule();
  translateAndMapModelObject(availabilitySchedule);
  idfObject.setString(ZoneHVAC_Baseboard_Convective_WaterFields::AvailabilityScheduleName,
                      availabilitySchedule.name().get() );

  if (coilOptionalHeatBBConvWater){
    CoilHeatingWaterBaseboard coilHeatBBConvWater = *coilOptionalHeatBBConvWater;

    // Inlet Node Name 
    temp = coilHeatBBConvWater.inletModelObject();
    if(temp)
    {
      s = temp->name();
      if(s)
      {
        idfObject.setString(openstudio::ZoneHVAC_Baseboard_Convective_WaterFields::InletNodeName,*s);
      }
    }

    // Outlet Node Name 
    temp = coilHeatBBConvWater.outletModelObject();
    if(temp)
    {
      s = temp->name();
      if(s)
      {
        idfObject.setString(openstudio::ZoneHVAC_Baseboard_Convective_WaterFields::OutletNodeName,*s);
      }
    }

    // UFactorTimesAreaValue
    if(coilHeatBBConvWater.isUFactorTimesAreaValueAutosized())
    {
      idfObject.setString(ZoneHVAC_Baseboard_Convective_WaterFields::UFactorTimesAreaValue,"Autosize");
    }
    else if( value = coilHeatBBConvWater.uFactorTimesAreaValue() )
    {
      idfObject.setDouble(ZoneHVAC_Baseboard_Convective_WaterFields::UFactorTimesAreaValue,value.get());
    }

   // MaximumWaterFlowRate

    if(coilHeatBBConvWater.isMaximumWaterFlowRateAutosized() )
    {
      idfObject.setString(ZoneHVAC_Baseboard_Convective_WaterFields::MaximumWaterFlowRate,"Autosize");
    }
    else if( value = coilHeatBBConvWater.maximumWaterFlowRate() )
    {
      idfObject.setDouble(ZoneHVAC_Baseboard_Convective_WaterFields::MaximumWaterFlowRate,value.get());
    }

   // Convergence Tolerance

    if( coilHeatBBConvWater.isConvergenceToleranceDefaulted())
    {
      idfObject.setDouble(ZoneHVAC_Baseboard_Convective_WaterFields::ConvergenceTolerance,0.001);
    }
    else if( value = coilHeatBBConvWater.convergenceTolerance())
    {
      idfObject.setDouble(ZoneHVAC_Baseboard_Convective_WaterFields::ConvergenceTolerance,value.get());
    }
  }
 return idfObject;
}
boost::optional<IdfObject> ForwardTranslator::translateFanVariableVolume( FanVariableVolume& modelObject )
{
  OptionalString s;
  OptionalDouble d;
  OptionalModelObject temp;

  // Create a new IddObjectType::Fan_VariableVolume
  IdfObject idfObject(IddObjectType::Fan_VariableVolume);

  m_idfObjects.push_back(idfObject);

  // Field: Name ////////////////////////////////////////////////////////////
  s = modelObject.name();
  if(s)
  {
    idfObject.setName(*s);
  }

  // AvailabilityScheduleName

  if( boost::optional<model::AirLoopHVAC> airLoopHVAC = modelObject.airLoopHVAC() )
  {
    Schedule sched = airLoopHVAC->availabilitySchedule();
    boost::optional<IdfObject> schedIdf = translateAndMapModelObject(sched);
    if( schedIdf )
    {
      idfObject.setString(Fan_VariableVolumeFields::AvailabilityScheduleName,schedIdf->name().get());
    }
  }
  else
  {
    Schedule sched = modelObject.availabilitySchedule();
    translateAndMapModelObject(sched);
    idfObject.setString(Fan_VariableVolumeFields::AvailabilityScheduleName,sched.name().get());
  }

  // Fan Efficiency /////////////////////////////////////////////////////////
  idfObject.setDouble(openstudio::Fan_VariableVolumeFields::FanTotalEfficiency,modelObject.fanEfficiency());

  // Pressure Rise //////////////////////////////////////////////////////////
  idfObject.setDouble(openstudio::Fan_VariableVolumeFields::PressureRise,modelObject.pressureRise());

  // Maximum Flow Rate //////////////////////////////////////////////////////
  if( modelObject.isMaximumFlowRateAutosized() )
  {
    idfObject.setString(openstudio::Fan_VariableVolumeFields::MaximumFlowRate,"AutoSize");
  }
  else if( (d = modelObject.maximumFlowRate()) )
  {
    idfObject.setDouble(openstudio::Fan_VariableVolumeFields::MaximumFlowRate,d.get());
  }

  // FanPowerMinimumFlowRateInputMethod
  if( (s = modelObject.fanPowerMinimumFlowRateInputMethod()) )
  {
    idfObject.setString(Fan_VariableVolumeFields::FanPowerMinimumFlowRateInputMethod,s.get());
  }

  // FanPowerMinimumFlowFraction
  if( (d = modelObject.fanPowerMinimumFlowFraction()) )
  {
    idfObject.setDouble(Fan_VariableVolumeFields::FanPowerMinimumFlowFraction,d.get());
  }

  // FanPowerMinimumAirFlowRate

  if( (d = modelObject.fanPowerMinimumAirFlowRate()) )
  {
    idfObject.setDouble(Fan_VariableVolumeFields::FanPowerMinimumAirFlowRate,d.get());
  }

  // Motor Efficiency ///////////////////////////////////////////////////////
  idfObject.setDouble(openstudio::Fan_VariableVolumeFields::MotorEfficiency,modelObject.motorEfficiency());

  // FanPowerCoefficient1

  if( (d = modelObject.fanPowerCoefficient1()) )
  {
    idfObject.setDouble(Fan_VariableVolumeFields::FanPowerCoefficient1,d.get());
  }

  // FanPowerCoefficient2

  if( (d = modelObject.fanPowerCoefficient2()) )
  {
    idfObject.setDouble(Fan_VariableVolumeFields::FanPowerCoefficient2,d.get());
  }

  // FanPowerCoefficient3

  if( (d = modelObject.fanPowerCoefficient3()) )
  {
    idfObject.setDouble(Fan_VariableVolumeFields::FanPowerCoefficient3,d.get());
  }

  // FanPowerCoefficient4

  if( (d = modelObject.fanPowerCoefficient4()) )
  {
    idfObject.setDouble(Fan_VariableVolumeFields::FanPowerCoefficient4,d.get());
  }

  // FanPowerCoefficient5

  if( (d = modelObject.fanPowerCoefficient5()) )
  {
    idfObject.setDouble(Fan_VariableVolumeFields::FanPowerCoefficient5,d.get());
  }

  // Motor In Airstream Fraction ////////////////////////////////////////////
  idfObject.setDouble(openstudio::Fan_VariableVolumeFields::MotorInAirstreamFraction,modelObject.motorInAirstreamFraction());

  // Air Inlet Node Name ////////////////////////////////////////////////////
  temp = modelObject.inletModelObject();
  if(temp)
  {
    s = temp->name();
    if(s)
    {
      idfObject.setString(openstudio::Fan_VariableVolumeFields::AirInletNodeName,*s);
    }
  }

  // Air Outlet Node Name ///////////////////////////////////////////////////
  temp = modelObject.outletModelObject();
  if(temp)
  {
    s = temp->name();
    if(s)
    {
      idfObject.setString(openstudio::Fan_VariableVolumeFields::AirOutletNodeName,*s);
    }
  }

  return idfObject;
}
Example #7
0
void InflationTest::testYYTermStructure() {
    BOOST_MESSAGE("Testing year-on-year inflation term structure...");

    SavedSettings backup;

    // try the YY UK
    Calendar calendar = UnitedKingdom();
    BusinessDayConvention bdc = ModifiedFollowing;
    Date evaluationDate(13, August, 2007);
    evaluationDate = calendar.adjust(evaluationDate);
    Settings::instance().evaluationDate() = evaluationDate;


    // fixing data
    Date from(1, January, 2005);
    Date to(13, August, 2007);
    Schedule rpiSchedule = MakeSchedule().from(from).to(to)
    .withTenor(1*Months)
    .withCalendar(UnitedKingdom())
    .withConvention(ModifiedFollowing);
    Real fixData[] = { 189.9, 189.9, 189.6, 190.5, 191.6, 192.0,
        192.2, 192.2, 192.6, 193.1, 193.3, 193.6,
        194.1, 193.4, 194.2, 195.0, 196.5, 197.7,
        198.5, 198.5, 199.2, 200.1, 200.4, 201.1,
        202.7, 201.6, 203.1, 204.4, 205.4, 206.2,
        207.3, -999.0, -999 };

    RelinkableHandle<YoYInflationTermStructure> hy;
    bool interp = false;
    boost::shared_ptr<YYUKRPIr> iir(new YYUKRPIr(interp, hy));
    for (Size i=0; i<rpiSchedule.size();i++) {
        iir->addFixing(rpiSchedule[i], fixData[i]);
    }



    boost::shared_ptr<YieldTermStructure> nominalTS = nominalTermStructure();

    // now build the YoY inflation curve
    Datum yyData[] = {
        { Date(13, August, 2008), 2.95 },
        { Date(13, August, 2009), 2.95 },
        { Date(13, August, 2010), 2.93 },
        { Date(15, August, 2011), 2.955 },
        { Date(13, August, 2012), 2.945 },
        { Date(13, August, 2013), 2.985 },
        { Date(13, August, 2014), 3.01 },
        { Date(13, August, 2015), 3.035 },
        { Date(13, August, 2016), 3.055 },  // note that
        { Date(13, August, 2017), 3.075 },  // some dates will be on
        { Date(13, August, 2019), 3.105 },  // holidays but the payment
        { Date(15, August, 2022), 3.135 },  // calendar will roll them
        { Date(13, August, 2027), 3.155 },
        { Date(13, August, 2032), 3.145 },
        { Date(13, August, 2037), 3.145 }
    };

    Period observationLag = Period(2,Months);
    DayCounter dc = Thirty360();

    // now build the helpers ...
    std::vector<boost::shared_ptr<BootstrapHelper<YoYInflationTermStructure> > > helpers =
    makeHelpers<YoYInflationTermStructure,YearOnYearInflationSwapHelper,
    YoYInflationIndex>(yyData, LENGTH(yyData), iir,
                        observationLag,
                        calendar, bdc, dc);

    Rate baseYYRate = yyData[0].rate/100.0;
    boost::shared_ptr<PiecewiseYoYInflationCurve<Linear> > pYYTS(
        new PiecewiseYoYInflationCurve<Linear>(
                evaluationDate, calendar, dc, observationLag,
                iir->frequency(),iir->interpolated(), baseYYRate,
                Handle<YieldTermStructure>(nominalTS), helpers));
    pYYTS->recalculate();

    // validation
    // yoy swaps should reprice to zero
    // yy rates should not equal yySwap rates
    Real eps = 0.000001;
    // usual swap engine
    Handle<YieldTermStructure> hTS(nominalTS);
    boost::shared_ptr<PricingEngine> sppe(new DiscountingSwapEngine(hTS));

    // make sure that the index has the latest yoy term structure
    hy.linkTo(pYYTS);

    for (Size j = 1; j < LENGTH(yyData); j++) {

        from = nominalTS->referenceDate();
        to = yyData[j].date;
        Schedule yoySchedule = MakeSchedule().from(from).to(to)
        .withConvention(Unadjusted) // fixed leg gets calendar from
        .withCalendar(calendar)     // schedule
        .withTenor(1*Years)
        .backwards()
        ;

        YearOnYearInflationSwap yyS2(YearOnYearInflationSwap::Payer,
                                        1000000.0,
                                        yoySchedule,//fixed schedule, but same as yoy
                                        yyData[j].rate/100.0,
                                        dc,
                                        yoySchedule,
                                        iir,
                                        observationLag,
                                        0.0,        //spread on index
                                        dc,
                                        UnitedKingdom());

        yyS2.setPricingEngine(sppe);



        BOOST_CHECK_MESSAGE(fabs(yyS2.NPV())<eps,"fresh yoy swap NPV!=0 from TS "
                <<"swap quote for pt " << j
                << ", is " << yyData[j].rate/100.0
                <<" vs YoY rate "<< pYYTS->yoyRate(yyData[j].date-observationLag)
                <<" at quote date "<<(yyData[j].date-observationLag)
                <<", NPV of a fresh yoy swap is " << yyS2.NPV()
                <<"\n      fair rate " << yyS2.fairRate()
                <<" payment "<<yyS2.paymentConvention());
    }

    Size jj=3;
    for (Size k = 0; k < 14; k++) {

        from = nominalTS->referenceDate() - k*Months;
        to = yyData[jj].date - k*Months;
        Schedule yoySchedule = MakeSchedule().from(from).to(to)
        .withConvention(Unadjusted) // fixed leg gets calendar from
        .withCalendar(calendar)     // schedule
        .withTenor(1*Years)
        .backwards()
        ;

        YearOnYearInflationSwap yyS3(YearOnYearInflationSwap::Payer,
                                    1000000.0,
                                    yoySchedule,//fixed schedule, but same as yoy
                                    yyData[jj].rate/100.0,
                                    dc,
                                    yoySchedule,
                                    iir,
                                    observationLag,
                                    0.0,        //spread on index
                                    dc,
                                    UnitedKingdom());

        yyS3.setPricingEngine(sppe);

        BOOST_CHECK_MESSAGE(fabs(yyS3.NPV())< 20000.0,
                            "unexpected size of aged YoY swap, aged "
                            <<k<<" months: YY aged NPV = " << yyS3.NPV()
                            <<", legs "<< yyS3.legNPV(0) << " and " << yyS3.legNPV(1)
                            );
    }

}
Example #8
0
void InflationTest::testZeroTermStructure() {
    BOOST_MESSAGE("Testing zero inflation term structure...");

    SavedSettings backup;

    // try the Zero UK
    Calendar calendar = UnitedKingdom();
    BusinessDayConvention bdc = ModifiedFollowing;
    Date evaluationDate(13, August, 2007);
    evaluationDate = calendar.adjust(evaluationDate);
    Settings::instance().evaluationDate() = evaluationDate;

    // fixing data
    Date from(1, January, 2005);
    Date to(13, August, 2007);
    Schedule rpiSchedule = MakeSchedule().from(from).to(to)
    .withTenor(1*Months)
    .withCalendar(UnitedKingdom())
    .withConvention(ModifiedFollowing);

    Real fixData[] = { 189.9, 189.9, 189.6, 190.5, 191.6, 192.0,
        192.2, 192.2, 192.6, 193.1, 193.3, 193.6,
        194.1, 193.4, 194.2, 195.0, 196.5, 197.7,
        198.5, 198.5, 199.2, 200.1, 200.4, 201.1,
        202.7, 201.6, 203.1, 204.4, 205.4, 206.2,
        207.3, 206.1,  -999.0 };

    RelinkableHandle<ZeroInflationTermStructure> hz;
    bool interp = false;
    boost::shared_ptr<UKRPI> iiUKRPI(new UKRPI(interp, hz));
    for (Size i=0; i<rpiSchedule.size();i++) {
        iiUKRPI->addFixing(rpiSchedule[i], fixData[i]);
    }

    boost::shared_ptr<ZeroInflationIndex> ii = boost::dynamic_pointer_cast<ZeroInflationIndex>(iiUKRPI);
    boost::shared_ptr<YieldTermStructure> nominalTS = nominalTermStructure();

    // now build the zero inflation curve
    Datum zcData[] = {
        { Date(13, August, 2008), 2.93 },
        { Date(13, August, 2009), 2.95 },
        { Date(13, August, 2010), 2.965 },
        { Date(15, August, 2011), 2.98 },
        { Date(13, August, 2012), 3.0 },
        { Date(13, August, 2014), 3.06 },
        { Date(13, August, 2017), 3.175 },
        { Date(13, August, 2019), 3.243 },
        { Date(15, August, 2022), 3.293 },
        { Date(14, August, 2027), 3.338 },
        { Date(13, August, 2032), 3.348 },
        { Date(15, August, 2037), 3.348 },
        { Date(13, August, 2047), 3.308 },
        { Date(13, August, 2057), 3.228 }
    };

    Period observationLag = Period(2,Months);
    DayCounter dc = Thirty360();
    Frequency frequency = Monthly;
    std::vector<boost::shared_ptr<BootstrapHelper<ZeroInflationTermStructure> > > helpers =
    makeHelpers<ZeroInflationTermStructure,ZeroCouponInflationSwapHelper,
                ZeroInflationIndex>(zcData, LENGTH(zcData), ii,
                                    observationLag,
                                    calendar, bdc, dc);

    Rate baseZeroRate = zcData[0].rate/100.0;
    boost::shared_ptr<PiecewiseZeroInflationCurve<Linear> > pZITS(
                        new PiecewiseZeroInflationCurve<Linear>(
                        evaluationDate, calendar, dc, observationLag,
                        frequency, ii->interpolated(), baseZeroRate,
                        Handle<YieldTermStructure>(nominalTS), helpers));
    pZITS->recalculate();

    // first check that the zero rates on the curve match the data
    // and that the helpers give the correct impled rates
    const Real eps = 0.00000001;
    bool forceLinearInterpolation = false;
    for (Size i=0; i<LENGTH(zcData); i++) {
        BOOST_REQUIRE_MESSAGE(std::fabs(zcData[i].rate/100.0
            - pZITS->zeroRate(zcData[i].date, observationLag, forceLinearInterpolation)) < eps,
            "ZITS zeroRate != instrument "
            << pZITS->zeroRate(zcData[i].date, observationLag, forceLinearInterpolation)
            << " vs " << zcData[i].rate/100.0
            << " interpolation: " << ii->interpolated()
            << " forceLinearInterpolation " << forceLinearInterpolation);
        BOOST_REQUIRE_MESSAGE(std::fabs(helpers[i]->impliedQuote()
            - zcData[i].rate/100.0) < eps,
            "ZITS implied quote != instrument "
            << helpers[i]->impliedQuote()
            << " vs " << zcData[i].rate/100.0);
    }


    // now test the forecasting capability of the index.
    hz.linkTo(pZITS);
    from = hz->baseDate();
    to = hz->maxDate()-1*Months; // a bit of margin for adjustments
    Schedule testIndex = MakeSchedule().from(from).to(to)
                            .withTenor(1*Months)
                            .withCalendar(UnitedKingdom())
                            .withConvention(ModifiedFollowing);


    // we are testing UKRPI which is not interpolated
    Date bd = hz->baseDate();
    Real bf = ii->fixing(bd);
    for (Size i=0; i<testIndex.size();i++) {
        Date d = testIndex[i];
        Real z = hz->zeroRate(d, Period(0,Days));
        Real t = hz->dayCounter().yearFraction(bd, d);
        if(!ii->interpolated()) // because fixing constant over period
            t = hz->dayCounter().yearFraction(bd,
                inflationPeriod(d, ii->frequency()).first);
        Real calc = bf * pow( 1+z, t);
        if (t<=0)
            calc = ii->fixing(d,false); // still historical
        if (std::fabs(calc - ii->fixing(d,true))/10000.0 > eps)
            BOOST_ERROR("ZC index does not forecast correctly for date " << d
                        << " from base date " << bd
                        << " with fixing " << bf
                        << ", correct:  " << calc
                        << ", fix: " << ii->fixing(d,true)
                        << ", t " << t);
    }


    //===========================================================================================
    // Test zero-inflation-indexed (i.e. cpi ratio) cashflow
    // just ordinary indexed cashflow with a zero inflation index

    Date baseDate(1, January, 2006);
    Date fixDate(1, August, 2014);
    Date payDate=UnitedKingdom().adjust(fixDate+Period(3,Months),ModifiedFollowing);
    boost::shared_ptr<Index> ind = boost::dynamic_pointer_cast<Index>(ii);
    BOOST_REQUIRE_MESSAGE(ind,"dynamic_pointer_cast to Index from InflationIndex failed");

    Real notional = 1000000.0;//1m
    IndexedCashFlow iicf(notional,ind,baseDate,fixDate,payDate);
    Real correctIndexed = ii->fixing(iicf.fixingDate())/ii->fixing(iicf.baseDate());
    Real calculatedIndexed = iicf.amount()/iicf.notional();
    BOOST_REQUIRE_MESSAGE(std::fabs(correctIndexed - calculatedIndexed) < eps,
               "IndexedCashFlow indexing wrong: " << calculatedIndexed << " vs correct = "
               << correctIndexed);


    //===========================================================================================
    // Test zero coupon swap

    // first make one ...

    boost::shared_ptr<ZeroInflationIndex> zii = boost::dynamic_pointer_cast<ZeroInflationIndex>(ii);
    BOOST_REQUIRE_MESSAGE(zii,"dynamic_pointer_cast to ZeroInflationIndex from UKRPI failed");
    ZeroCouponInflationSwap nzcis(ZeroCouponInflationSwap::Payer,
                                     1000000.0,
                                     evaluationDate,
                                     zcData[6].date,    // end date = maturity
                                     calendar, bdc, dc, zcData[6].rate/100.0, // fixed rate
                                     zii, observationLag);

    // N.B. no coupon pricer because it is not a coupon, effect of inflation curve via
    //      inflation curve attached to the inflation index.
    Handle<YieldTermStructure> hTS(nominalTS);
    boost::shared_ptr<PricingEngine> sppe(new DiscountingSwapEngine(hTS));
    nzcis.setPricingEngine(sppe);

    // ... and price it, should be zero
    BOOST_CHECK_MESSAGE(fabs(nzcis.NPV())<0.00001,"ZCIS does not reprice to zero "
                        << nzcis.NPV()
                        << evaluationDate << " to " << zcData[6].date << " becoming " << nzcis.maturityDate()
                        << " rate " << zcData[6].rate
                        << " fixed leg " << nzcis.legNPV(0)
                        << " indexed-predicted inflated leg " << nzcis.legNPV(1)
                        << " discount " << nominalTS->discount(nzcis.maturityDate())
                        );


    //===========================================================================================
    // Test multiplicative seasonality in price
    //

    //Seasonality factors NOT normalized
    //and UKRPI is not interpolated
    Date trueBaseDate = inflationPeriod(hz->baseDate(), ii->frequency()).second;
    Date seasonallityBaseDate(31,January,trueBaseDate.year());
    std::vector<Rate> seasonalityFactors(12);
    seasonalityFactors[0] = 1.003245;
    seasonalityFactors[1] = 1.000000;
    seasonalityFactors[2] = 0.999715;
    seasonalityFactors[3] = 1.000495;
    seasonalityFactors[4] = 1.000929;
    seasonalityFactors[5] = 0.998687;
    seasonalityFactors[6] = 0.995949;
    seasonalityFactors[7] = 0.994682;
    seasonalityFactors[8] = 0.995949;
    seasonalityFactors[9] = 1.000519;
    seasonalityFactors[10] = 1.003705;
    seasonalityFactors[11] = 1.004186;

    //Creating two different seasonality objects
    //
    boost::shared_ptr<MultiplicativePriceSeasonality> seasonality_1(new MultiplicativePriceSeasonality());
    std::vector<Rate> seasonalityFactors_1(12, 1.0);
    seasonality_1->set(seasonallityBaseDate,Monthly,seasonalityFactors_1);

    boost::shared_ptr<MultiplicativePriceSeasonality> seasonality_real(
        new MultiplicativePriceSeasonality(seasonallityBaseDate,Monthly,seasonalityFactors));
    //Testing seasonality correction when seasonality factors are = 1
    //
    Rate fixing[] = {
        ii->fixing(Date(14,January  ,2013),true),
        ii->fixing(Date(14,February ,2013),true),
        ii->fixing(Date(14,March    ,2013),true),
        ii->fixing(Date(14,April    ,2013),true),
        ii->fixing(Date(14,May      ,2013),true),
        ii->fixing(Date(14,June     ,2013),true),
        ii->fixing(Date(14,July     ,2013),true),
        ii->fixing(Date(14,August   ,2013),true),
        ii->fixing(Date(14,September,2013),true),
        ii->fixing(Date(14,October  ,2013),true),
        ii->fixing(Date(14,November ,2013),true),
        ii->fixing(Date(14,December ,2013),true)
    };

    hz->setSeasonality(seasonality_1);
    QL_REQUIRE(hz->hasSeasonality(),"[44] incorrectly believes NO seasonality correction");

    Rate seasonalityFixing_1[] = {
        ii->fixing(Date(14,January  ,2013),true),
        ii->fixing(Date(14,February ,2013),true),
        ii->fixing(Date(14,March    ,2013),true),
        ii->fixing(Date(14,April    ,2013),true),
        ii->fixing(Date(14,May      ,2013),true),
        ii->fixing(Date(14,June     ,2013),true),
        ii->fixing(Date(14,July     ,2013),true),
        ii->fixing(Date(14,August   ,2013),true),
        ii->fixing(Date(14,September,2013),true),
        ii->fixing(Date(14,October  ,2013),true),
        ii->fixing(Date(14,November ,2013),true),
        ii->fixing(Date(14,December ,2013),true)

    };

    for(int i=0;i<12;i++){
        if(std::fabs(fixing[i] - seasonalityFixing_1[i]) > eps) {
            BOOST_ERROR("Seasonality doesn't work correctly when seasonality factors are set = 1");
        }
    }

    //Testing seasonality correction when seasonality factors are different from 1
    //
    //0.998687 is the seasonality factor corresponding to June (the base CPI curve month)
    //
    Rate expectedFixing[] = {
        ii->fixing(Date(14,January  ,2013),true) * 1.003245/0.998687,
        ii->fixing(Date(14,February ,2013),true) * 1.000000/0.998687,
        ii->fixing(Date(14,March    ,2013),true) * 0.999715/0.998687,
        ii->fixing(Date(14,April    ,2013),true) * 1.000495/0.998687,
        ii->fixing(Date(14,May      ,2013),true) * 1.000929/0.998687,
        ii->fixing(Date(14,June     ,2013),true) * 0.998687/0.998687,
        ii->fixing(Date(14,July     ,2013),true) * 0.995949/0.998687,
        ii->fixing(Date(14,August   ,2013),true) * 0.994682/0.998687,
        ii->fixing(Date(14,September,2013),true) * 0.995949/0.998687,
        ii->fixing(Date(14,October  ,2013),true) * 1.000519/0.998687,
        ii->fixing(Date(14,November ,2013),true) * 1.003705/0.998687,
        ii->fixing(Date(14,December ,2013),true) * 1.004186/0.998687
    };

    hz->setSeasonality(seasonality_real);

    Rate seasonalityFixing_real[] = {
        ii->fixing(Date(14,January  ,2013),true),
        ii->fixing(Date(14,February ,2013),true),
        ii->fixing(Date(14,March    ,2013),true),
        ii->fixing(Date(14,April    ,2013),true),
        ii->fixing(Date(14,May      ,2013),true),
        ii->fixing(Date(14,June     ,2013),true),
        ii->fixing(Date(14,July     ,2013),true),
        ii->fixing(Date(14,August   ,2013),true),
        ii->fixing(Date(14,September,2013),true),
        ii->fixing(Date(14,October  ,2013),true),
        ii->fixing(Date(14,November ,2013),true),
        ii->fixing(Date(14,December ,2013),true)
    };

    for(int i=0;i<12;i++){
        if(std::fabs(expectedFixing[i] - seasonalityFixing_real[i]) > 0.01) {
            BOOST_ERROR("Seasonality doesn't work correctly when considering seasonality factors != 1 "
                        << expectedFixing[i] << " vs " << seasonalityFixing_real[i]);
        }
    }

    //Testing Unset function
    //
    QL_REQUIRE(hz->hasSeasonality(),"[4] incorrectly believes NO seasonality correction");
    hz->setSeasonality();
    QL_REQUIRE(!hz->hasSeasonality(),"[5] incorrectly believes HAS seasonality correction");

    Rate seasonalityFixing_unset[] = {
        ii->fixing(Date(14,January  ,2013),true),
        ii->fixing(Date(14,February ,2013),true),
        ii->fixing(Date(14,March    ,2013),true),
        ii->fixing(Date(14,April    ,2013),true),
        ii->fixing(Date(14,May      ,2013),true),
        ii->fixing(Date(14,June     ,2013),true),
        ii->fixing(Date(14,July     ,2013),true),
        ii->fixing(Date(14,August   ,2013),true),
        ii->fixing(Date(14,September,2013),true),
        ii->fixing(Date(14,October  ,2013),true),
        ii->fixing(Date(14,November ,2013),true),
        ii->fixing(Date(14,December ,2013),true)
    };

    for(int i=0;i<12;i++){
        if(std::fabs(seasonalityFixing_unset[i] - seasonalityFixing_1[i]) > eps) {
            BOOST_ERROR("UnsetSeasonality doesn't work correctly "
                        << seasonalityFixing_unset[i] << " vs " << seasonalityFixing_1[i]);
        }
    }



    //==============================================================================
    // now do an INTERPOLATED index, i.e. repeat everything on a fake version of
    // UKRPI (to save making another term structure)

    bool interpYES = true;
    boost::shared_ptr<UKRPI> iiUKRPIyes(new UKRPI(interpYES, hz));
    for (Size i=0; i<rpiSchedule.size();i++) {
        iiUKRPIyes->addFixing(rpiSchedule[i], fixData[i]);
    }

    boost::shared_ptr<ZeroInflationIndex> iiyes
        = boost::dynamic_pointer_cast<ZeroInflationIndex>(iiUKRPIyes);

    // now build the zero inflation curve
    // same data, bigger lag or it will be a self-contradiction
    Period observationLagyes = Period(3,Months);
    std::vector<boost::shared_ptr<BootstrapHelper<ZeroInflationTermStructure> > > helpersyes =
    makeHelpers<ZeroInflationTermStructure,ZeroCouponInflationSwapHelper,
    ZeroInflationIndex>(zcData, LENGTH(zcData), iiyes,
                        observationLagyes,
                        calendar, bdc, dc);

    boost::shared_ptr<PiecewiseZeroInflationCurve<Linear> > pZITSyes(
            new PiecewiseZeroInflationCurve<Linear>(
            evaluationDate, calendar, dc, observationLagyes,
            frequency, iiyes->interpolated(), baseZeroRate,
            Handle<YieldTermStructure>(nominalTS), helpersyes));
    pZITSyes->recalculate();

    // first check that the zero rates on the curve match the data
    // and that the helpers give the correct impled rates
    forceLinearInterpolation = false;   // still
    for (Size i=0; i<LENGTH(zcData); i++) {
        BOOST_CHECK_MESSAGE(std::fabs(zcData[i].rate/100.0
                    - pZITSyes->zeroRate(zcData[i].date, observationLagyes, forceLinearInterpolation)) < eps,
                    "ZITS INTERPOLATED zeroRate != instrument "
                    << pZITSyes->zeroRate(zcData[i].date, observationLagyes, forceLinearInterpolation)
                    << " date " << zcData[i].date << " observationLagyes " << observationLagyes
                    << " vs " << zcData[i].rate/100.0
                    << " interpolation: " << iiyes->interpolated()
                    << " forceLinearInterpolation " << forceLinearInterpolation);
        BOOST_CHECK_MESSAGE(std::fabs(helpersyes[i]->impliedQuote()
                        - zcData[i].rate/100.0) < eps,
                    "ZITS INTERPOLATED implied quote != instrument "
                    << helpersyes[i]->impliedQuote()
                    << " vs " << zcData[i].rate/100.0);
    }


    //======================================================================================
    // now test the forecasting capability of the index.
    hz.linkTo(pZITSyes);
    from = hz->baseDate()+1*Months; // to avoid historical linear bit for rest of base month
    to = hz->maxDate()-1*Months; // a bit of margin for adjustments
    testIndex = MakeSchedule().from(from).to(to)
    .withTenor(1*Months)
    .withCalendar(UnitedKingdom())
    .withConvention(ModifiedFollowing);

    // we are testing UKRPI which is FAKE interpolated for testing here
    bd = hz->baseDate();
    bf = iiyes->fixing(bd);
    for (Size i=0; i<testIndex.size();i++) {
        Date d = testIndex[i];
        Real z = hz->zeroRate(d, Period(0,Days));
        Real t = hz->dayCounter().yearFraction(bd, d);
        Real calc = bf * pow( 1+z, t);
        if (t<=0) calc = iiyes->fixing(d); // still historical
        if (std::fabs(calc - iiyes->fixing(d)) > eps)
            BOOST_ERROR("ZC INTERPOLATED index does not forecast correctly for date " << d
                        << " from base date " << bd
                        << " with fixing " << bf
                        << ", correct:  " << calc
                        << ", fix: " << iiyes->fixing(d)
                        << ", t " << t
                        << ", zero " << z);
    }



    //===========================================================================================
    // Test zero coupon swap

    boost::shared_ptr<ZeroInflationIndex> ziiyes = boost::dynamic_pointer_cast<ZeroInflationIndex>(iiyes);
    BOOST_REQUIRE_MESSAGE(ziiyes,"dynamic_pointer_cast to ZeroInflationIndex from UKRPI-I failed");
    ZeroCouponInflationSwap nzcisyes(ZeroCouponInflationSwap::Payer,
                                     1000000.0,
                                     evaluationDate,
                                     zcData[6].date,    // end date = maturity
                                     calendar, bdc, dc, zcData[6].rate/100.0, // fixed rate
                                     ziiyes, observationLagyes);

    // N.B. no coupon pricer because it is not a coupon, effect of inflation curve via
    //      inflation curve attached to the inflation index.
    nzcisyes.setPricingEngine(sppe);

    // ... and price it, should be zero
    BOOST_CHECK_MESSAGE(fabs(nzcisyes.NPV())<0.00001,"ZCIS-I does not reprice to zero "
                        << nzcisyes.NPV()
                        << evaluationDate << " to " << zcData[6].date << " becoming " << nzcisyes.maturityDate()
                        << " rate " << zcData[6].rate
                        << " fixed leg " << nzcisyes.legNPV(0)
                        << " indexed-predicted inflated leg " << nzcisyes.legNPV(1)
                        << " discount " << nominalTS->discount(nzcisyes.maturityDate())
                        );

}
Example #9
0
void verifyWellState(const std::string& rst_filename,
                     const EclipseGrid& ecl_grid,
                     const Schedule& schedule) {

  well_info_type* well_info = well_info_alloc(ecl_grid.c_ptr());
  well_info_load_rstfile(well_info, rst_filename.c_str(), false);

  //Verify numwells
  int numwells = well_info_get_num_wells(well_info);
  BOOST_CHECK_EQUAL( numwells, schedule.numWells() );

  auto wells = schedule.getWells();

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

    //Verify wellnames
    const char * wellname = well_info_iget_well_name(well_info, i);
    auto* well = wells.at(i);
    BOOST_CHECK_EQUAL( wellname, well->name() );

    // Verify well-head position data
    well_ts_type* well_ts = well_info_get_ts(well_info , wellname);
    well_state_type* well_state = well_ts_iget_state(well_ts, 0);
    const well_conn_type* well_head = well_state_get_wellhead(well_state, ECL_GRID_GLOBAL_GRID);
    BOOST_CHECK_EQUAL(well_conn_get_i(well_head), well->getHeadI());
    BOOST_CHECK_EQUAL(well_conn_get_j(well_head), well->getHeadJ());

    for (int j = 0; j < well_ts_get_size(well_ts); ++j) {
      well_state = well_ts_iget_state(well_ts, j);

      //Verify welltype
      int well_type = ERT_UNDOCUMENTED_ZERO;
      if( well->isProducer( j ) ) {
          well_type = ERT_PRODUCER;
      }
      else {
          switch( well->getInjectionProperties( j ).injectorType ) {
              case WellInjector::WATER:
                  well_type = ERT_WATER_INJECTOR;
                  break;
              case WellInjector::GAS:
                  well_type = ERT_GAS_INJECTOR;
                  break;
              case WellInjector::OIL:
                  well_type = ERT_OIL_INJECTOR;
                  break;
              default:
                  break;
          }
      }

      int ert_well_type = well_state_get_type( well_state );
      BOOST_CHECK_EQUAL( ert_well_type, well_type );

      //Verify wellstatus
      int ert_well_status = well_state_is_open(well_state) ? 1 : 0;
      int wellstatus = well->getStatus( j ) == WellCommon::OPEN ? 1 : 0;

      BOOST_CHECK_EQUAL(ert_well_status, wellstatus);

      //Verify number of completion connections
      const well_conn_collection_type * well_connections = well_state_get_global_connections( well_state );
      size_t num_wellconnections = well_conn_collection_get_size(well_connections);

      int report_nr = well_state_get_report_nr(well_state);
      const auto& connections_set = well->getConnections((size_t)report_nr);

      BOOST_CHECK_EQUAL(num_wellconnections, connections_set.size());

      //Verify coordinates for each completion connection
      for (size_t k = 0; k < num_wellconnections; ++k) {
          const well_conn_type * well_connection = well_conn_collection_iget_const(well_connections , k);

          const auto& completion = connections_set.get(k);

          BOOST_CHECK_EQUAL(well_conn_get_i(well_connection), completion.getI());
          BOOST_CHECK_EQUAL(well_conn_get_j(well_connection), completion.getJ());
          BOOST_CHECK_EQUAL(well_conn_get_k(well_connection), completion.getK());
      }
    }
  }

  well_info_free(well_info);
}
boost::optional<IdfObject> ForwardTranslator::translateCoilCoolingDXSingleSpeedWithoutUnitary( model::CoilCoolingDXSingleSpeed & modelObject )
{
  OptionalString s;
  IdfObject idfObject(IddObjectType::Coil_Cooling_DX_SingleSpeed);

  s = modelObject.name();
  if( s )
  {
    idfObject.setName(*s);
  }

  // hook up required objects
  try {
    Schedule sched = modelObject.getAvailabilitySchedule();
    translateAndMapModelObject(sched);
    idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::AvailabilityScheduleName,
                        sched.name().get() );

    Curve cb =  modelObject.getTotalCoolingCapacityFunctionOfTemperatureCurve();
    translateAndMapModelObject(cb);
    idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::TotalCoolingCapacityFunctionofTemperatureCurveName,
                       cb.name().get());

    Curve cq = modelObject.getTotalCoolingCapacityFunctionOfFlowFractionCurve();
    translateAndMapModelObject(cq);
    idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::TotalCoolingCapacityFunctionofFlowFractionCurveName,
                        cq.name().get());

    cb =modelObject.getEnergyInputRatioFunctionOfTemperatureCurve();
    translateAndMapModelObject(cb);
    idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::EnergyInputRatioFunctionofTemperatureCurveName,
                        cb.name().get());

    cq=modelObject.getEnergyInputRatioFunctionOfFlowFractionCurve();
    translateAndMapModelObject(cq);
    idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::EnergyInputRatioFunctionofFlowFractionCurveName,
                        cq.name().get());

    cq=modelObject.getPartLoadFractionCorrelationCurve();
    translateAndMapModelObject(cq);
    idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::PartLoadFractionCorrelationCurveName,
                        cq.name().get());
  }
  catch (std::exception& e) {
    LOG(Error,"Could not translate " << modelObject.briefDescription() << ", because " 
        << e.what() << ".");
    return boost::none;
  }

  OptionalDouble d = modelObject.ratedTotalCoolingCapacity();
  if( d )
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::GrossRatedTotalCoolingCapacity,*d);
  }
  else
  {
    idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::GrossRatedTotalCoolingCapacity,"Autosize");
  }

  d = modelObject.ratedSensibleHeatRatio();
  if( d )
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::GrossRatedSensibleHeatRatio,*d);
  }
  else
  {
    idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::GrossRatedSensibleHeatRatio,"Autosize");
  }

  d = modelObject.getRatedCOP();
  if( d )
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::GrossRatedCoolingCOP,*d);
  }

  d = modelObject.ratedAirFlowRate();
  if( d )
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::RatedAirFlowRate,*d);
  }
  else
  {
    idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::RatedAirFlowRate,"Autosize");
  }

  d = modelObject.getRatedEvaporatorFanPowerPerVolumeFlowRate();
  if( d )
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::RatedEvaporatorFanPowerPerVolumeFlowRate,*d);
  }

  OptionalModelObject omo = modelObject.inletModelObject();
  if( omo )
  {
    translateAndMapModelObject(*omo);
    s = omo->name();
    if(s)
    {
      idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::AirInletNodeName,*s );
    }
  }

  omo= modelObject.outletModelObject();
  if( omo )
  {
    translateAndMapModelObject(*omo);
    s = omo->name();
    if(s)
    {
      idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::AirOutletNodeName,*s);
    }
  }

  d=modelObject.getNominalTimeForCondensateRemovalToBegin();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::NominalTimeforCondensateRemovaltoBegin,*d);
  }

  d=modelObject.getRatioOfInitialMoistureEvaporationRateAndSteadyStateLatentCapacity();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::RatioofInitialMoistureEvaporationRateandSteadyStateLatentCapacity,*d);
  }

  d=modelObject.getMaximumCyclingRate();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::MaximumCyclingRate,*d);
  }

  d=modelObject.getLatentCapacityTimeConstant();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::LatentCapacityTimeConstant,*d);
  }

  s=modelObject.getCondenserAirInletNodeName();
  if(s)
  {
    idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::CondenserAirInletNodeName,*s);
  }

  idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::CondenserType,modelObject.getCondenserType());

  d=modelObject.getEvaporativeCondenserEffectiveness();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::EvaporativeCondenserEffectiveness,*d);
  }

  d=modelObject.getEvaporativeCondenserAirFlowRate();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::EvaporativeCondenserAirFlowRate,*d);
  }

  d=modelObject.getEvaporativeCondenserPumpRatedPowerConsumption();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::EvaporativeCondenserPumpRatedPowerConsumption,*d);
  }

  d=modelObject.getCrankcaseHeaterCapacity();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::CrankcaseHeaterCapacity,*d);
  }

  d=modelObject.getMaximumOutdoorDryBulbTemperatureForCrankcaseHeaterOperation();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::MaximumOutdoorDryBulbTemperatureforCrankcaseHeaterOperation,*d);
  }

  //TODO
  //getSupplyWaterStorageTankName
  //getCondensateCollectionWaterStorageTankName

  d=modelObject.getBasinHeaterCapacity();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::BasinHeaterCapacity,*d);
  }

  d=modelObject.getBasinHeaterSetpointTemperature();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_SingleSpeedFields::BasinHeaterSetpointTemperature,*d);
  }

  OptionalSchedule os = modelObject.getBasinHeaterOperatingSchedule();
  if( os )
  {
    translateAndMapModelObject(*os);
    idfObject.setString(Coil_Cooling_DX_SingleSpeedFields::BasinHeaterOperatingScheduleName,
                        os->name().get() );
  }

  m_idfObjects.push_back(idfObject);
  return idfObject;
}
void ScheduleManager::registerSchedule()
{
	enum ScheduleManagerFunction
	{
		SET_SCREEN = 1,
		SET_DATE,
		SET_MOVIE,
		SET_TIME,
		REGISTER_SCHEDULE,
	};

	for (Schedule schedule;;)
	{
		system("cls");
		cout <<
			"극장 관리 시스템\n"
			" > 상영 일정 관리\n"
			"  > 상영 일정 등록\n"
			"\n";

		if (0 != schedule.screen.getNumber()
			|| 0 != schedule.date.getValue()
			|| 0 != schedule.movie.getCode()
			|| 0 != schedule.getStartTime())
		{
			cout << "새 스케쥴\n";
			if (0 != schedule.screen.getNumber())
			{
				schedule.screen.show();
			}
			if (0 != schedule.date.getValue())
			{
				schedule.date.show();
			}
			if (0 != schedule.movie.getCode())
			{
				schedule.movie.show();
			}
			if (0 != schedule.getStartTime())
			{
				schedule.showTime();
			}
			cout << endl;
		}
				
		cout <<
			"1. 상영관 설정\n"
			"2. 날짜 설정\n"
			"3. 영화 설정\n"
			"4. 시간 설정\n"
			"5. 새 스케쥴 등록\n"
			"0. 종료\n"
			"\n"
			"선택: ";

		int32_t function = 0;
		switch (inputPositiveInteger(function))
		{
		case FUNCTION_CANCEL:
			return;
		case FUNCTION_ERROR:
			cout << "\n잘못된 입력입니다.\n";
			system("pause");
			continue;
		case FUNCTION_SUCCESS:
			switch (function)
			{
			case SET_SCREEN:
				setScreen(schedule.screen);
				continue;
			case SET_DATE:
				setDate(schedule.date);
				continue;
			case SET_MOVIE:
				setMovie(schedule.movie);
				continue;
			case SET_TIME:
				cout << endl;
				if (0 == schedule.screen.getNumber())
				{
					cout << "상영관을 선택하지 않았습니다.\n";
				}
				else if (0 == schedule.date.getValue())
				{
					cout << "상영일을 선택하지 않았습니다.\n";
				}
				else if (0 == schedule.movie.getCode())
				{
					cout << "영화를 선택하지 않았습니다.\n";
				}
				else
				{
					setTime(schedule);
					continue;
				}
				system("pause");
				continue;
			case REGISTER_SCHEDULE:
				if (0 == schedule.getStartTime())
				{
					cout << "\n상영 시간을 입력하지 않았습니다.\n";
					system("pause");
					continue;
				}
			}
		}

		SQLWCHAR scheduleSql[BUFSIZ];
		swprintf_s(scheduleSql, L""
			"INSERT INTO d%d "
			"(movie_code, movie_title, age, start_time, end_time, screen) "
			"VALUES (?, ?, ?, ?, ?, ?);",
			schedule.date.getValue());
		SQLWCHAR seatSql[BUFSIZ];
		swprintf_s(seatSql, L"SELECT * INTO d%ds%dt%d FROM screen%d;",
			schedule.date.getValue(), schedule.screen.getNumber(), schedule.getStartTime(),
			schedule.screen.getNumber());

		if (SQL_SUCCESS == schedule.bindParameter()
			&& SQL_SUCCESS == schedule.execute(MDF_SCHEDULE, scheduleSql)
			&& SQL_SUCCESS == schedule.execute(MDF_SEAT, seatSql))
		{
			schedule.initialize();
			cout << "\n상영 일정이 등록 되었습니다.\n";
		}
		else
		{
			cout << "\n상영 일정 등록을 실패했습니다.\n";
		}
		system("pause");
	}
}
Example #12
0
bool cmp(Schedule s1, Schedule s2) {
	if (s1.getFitness() <= s2.getFitness()) {
		return 0;
	}
	else return 1;
}
Example #13
0
    AssetSwap::AssetSwap(bool parSwap,
                         const boost::shared_ptr<Bond>& bond,
                         Real bondCleanPrice,
                         Real nonParRepayment,
                         Real gearing,
                         const boost::shared_ptr<IborIndex>& iborIndex,
                         Spread spread,
                         const DayCounter& floatingDayCounter,
                         Date dealMaturity,
                         bool payBondCoupon)
    : Swap(2), bond_(bond), bondCleanPrice_(bondCleanPrice),
      nonParRepayment_(nonParRepayment), spread_(spread), parSwap_(parSwap)
    {
        Schedule tempSch(bond_->settlementDate(),
                         bond_->maturityDate(),
                         iborIndex->tenor(),
                         iborIndex->fixingCalendar(),
                         iborIndex->businessDayConvention(),
                         iborIndex->businessDayConvention(),
                         DateGeneration::Backward,
                         false); // endOfMonth
        if (dealMaturity==Date())
            dealMaturity = bond_->maturityDate();
        QL_REQUIRE(dealMaturity <= tempSch.dates().back(),
                   "deal maturity " << dealMaturity <<
                   " cannot be later than (adjusted) bond maturity " <<
                   tempSch.dates().back());

        // the following might become an input parameter
        BusinessDayConvention paymentAdjustment = Following;

        Date finalDate = tempSch.calendar().adjust(
            dealMaturity, paymentAdjustment);
        Schedule schedule = tempSch.until(finalDate);

        // bondCleanPrice must be the (forward) clean price
        // at the floating schedule start date
        upfrontDate_ = schedule.startDate();
        Real dirtyPrice = bondCleanPrice_ +
                          bond_->accruedAmount(upfrontDate_);

        Real notional = bond_->notional(upfrontDate_);
        /* In the market asset swap, the bond is purchased in return for
           payment of the full price. The notional of the floating leg is
           then scaled by the full price. */
        if (!parSwap_)
            notional *= dirtyPrice/100.0;

        if (floatingDayCounter==DayCounter())
            legs_[1] = IborLeg(schedule, iborIndex)
                .withNotionals(notional)
                .withPaymentAdjustment(paymentAdjustment)
                .withGearings(gearing)
                .withSpreads(spread);
        else
            legs_[1] = IborLeg(schedule, iborIndex)
                .withNotionals(notional)
                .withPaymentDayCounter(floatingDayCounter)
                .withPaymentAdjustment(paymentAdjustment)
                .withGearings(gearing)
                .withSpreads(spread);

        for (Leg::const_iterator i=legs_[1].begin(); i<legs_[1].end(); ++i)
            registerWith(*i);

        const Leg& bondLeg = bond_->cashflows();
        Leg::const_iterator i = bondLeg.begin();
        // skip bond redemption
        for (; i<bondLeg.end()-1 && (*i)->date()<=dealMaturity; ++i) {
            // whatever might be the choice for the discounting engine
            // bond flows on upfrontDate_ must be discarded
            bool upfrontDateBondFlows = false;
            if (!(*i)->hasOccurred(upfrontDate_, upfrontDateBondFlows))
                legs_[0].push_back(*i);
        }
        // if the first skipped cashflow is not the redemption
        // and it is a coupon then add the accrued coupon
        if (i<bondLeg.end()-1) {
            shared_ptr<Coupon> c = boost::dynamic_pointer_cast<Coupon>(*i);
            if (c) {
                shared_ptr<CashFlow> accruedCoupon(new
                    SimpleCashFlow(c->accruedAmount(dealMaturity), finalDate));
                legs_[0].push_back(accruedCoupon);
            }
        }
        // add the nonParRepayment_
        shared_ptr<CashFlow> nonParRepaymentFlow(new
            SimpleCashFlow(nonParRepayment_, finalDate));
        legs_[0].push_back(nonParRepaymentFlow);

        QL_REQUIRE(!legs_[0].empty(),
                   "empty bond leg to start with");

        // special flows
        if (parSwap_) {
            // upfront on the floating leg
            Real upfront = (dirtyPrice-100.0)/100.0*notional;
            shared_ptr<CashFlow> upfrontCashFlow(new
                SimpleCashFlow(upfront, upfrontDate_));
            legs_[1].insert(legs_[1].begin(), upfrontCashFlow);
            // backpayment on the floating leg
            // (accounts for non-par redemption, if any)
            Real backPayment = notional;
            shared_ptr<CashFlow> backPaymentCashFlow(new
                SimpleCashFlow(backPayment, finalDate));
            legs_[1].push_back(backPaymentCashFlow);
        } else {
            // final notional exchange
            shared_ptr<CashFlow> finalCashFlow (new
                SimpleCashFlow(notional, finalDate));
            legs_[1].push_back(finalCashFlow);
        }

        QL_REQUIRE(!legs_[0].empty(), "empty bond leg");
        for (Leg::const_iterator i=legs_[0].begin(); i<legs_[0].end(); ++i)
            registerWith(*i);

        if (payBondCoupon) {
            payer_[0]=-1.0;
            payer_[1]=+1.0;
        } else {
            payer_[0]=+1.0;
            payer_[1]=-1.0;
        }
    }
Example #14
0
    AssetSwap::AssetSwap(bool payBondCoupon,
                         const shared_ptr<Bond>& bond,
                         Real bondCleanPrice,
                         const shared_ptr<IborIndex>& iborIndex,
                         Spread spread,
                         const Schedule& floatSchedule,
                         const DayCounter& floatingDayCounter,
                         bool parSwap)
    : Swap(2), bond_(bond), bondCleanPrice_(bondCleanPrice),
      nonParRepayment_(100), spread_(spread), parSwap_(parSwap)
    {
        Schedule schedule = floatSchedule;
        if (floatSchedule.empty())
            schedule = Schedule(bond_->settlementDate(),
                                bond_->maturityDate(),
                                iborIndex->tenor(),
                                iborIndex->fixingCalendar(),
                                iborIndex->businessDayConvention(),
                                iborIndex->businessDayConvention(),
                                DateGeneration::Backward,
                                false); // endOfMonth

        // the following might become an input parameter
        BusinessDayConvention paymentAdjustment = Following;

        Date finalDate = schedule.calendar().adjust(
            schedule.endDate(), paymentAdjustment);
        Date adjBondMaturityDate = schedule.calendar().adjust(
            bond_->maturityDate(), paymentAdjustment);

        QL_REQUIRE(finalDate==adjBondMaturityDate,
                   "adjusted schedule end date (" <<
                   finalDate <<
                   ") must be equal to adjusted bond maturity date (" <<
                   adjBondMaturityDate << ")");

        // bondCleanPrice must be the (forward) clean price
        // at the floating schedule start date
        upfrontDate_ = schedule.startDate();
        Real dirtyPrice = bondCleanPrice_ +
                          bond_->accruedAmount(upfrontDate_);

        Real notional = bond_->notional(upfrontDate_);
        /* In the market asset swap, the bond is purchased in return for
           payment of the full price. The notional of the floating leg is
           then scaled by the full price. */
        if (!parSwap_)
            notional *= dirtyPrice/100.0;

        if (floatingDayCounter==DayCounter())
            legs_[1] = IborLeg(schedule, iborIndex)
                .withNotionals(notional)
                .withPaymentAdjustment(paymentAdjustment)
                .withSpreads(spread);
        else
            legs_[1] = IborLeg(schedule, iborIndex)
                .withNotionals(notional)
                .withPaymentDayCounter(floatingDayCounter)
                .withPaymentAdjustment(paymentAdjustment)
                .withSpreads(spread);

        for (Leg::const_iterator i=legs_[1].begin(); i<legs_[1].end(); ++i)
            registerWith(*i);

        const Leg& bondLeg = bond_->cashflows();
        for (Leg::const_iterator i=bondLeg.begin(); i<bondLeg.end(); ++i) {
            // whatever might be the choice for the discounting engine
            // bond flows on upfrontDate_ must be discarded
            bool upfrontDateBondFlows = false;
            if (!(*i)->hasOccurred(upfrontDate_, upfrontDateBondFlows))
                legs_[0].push_back(*i);
        }

        QL_REQUIRE(!legs_[0].empty(),
                   "empty bond leg to start with");

        // special flows
        if (parSwap_) {
            // upfront on the floating leg
            Real upfront = (dirtyPrice-100.0)/100.0*notional;
            shared_ptr<CashFlow> upfrontCashFlow(new
                SimpleCashFlow(upfront, upfrontDate_));
            legs_[1].insert(legs_[1].begin(), upfrontCashFlow);
            // backpayment on the floating leg
            // (accounts for non-par redemption, if any)
            Real backPayment = notional;
            shared_ptr<CashFlow> backPaymentCashFlow(new
                SimpleCashFlow(backPayment, finalDate));
            legs_[1].push_back(backPaymentCashFlow);
        } else {
            // final notional exchange
            shared_ptr<CashFlow> finalCashFlow(new
                SimpleCashFlow(notional, finalDate));
            legs_[1].push_back(finalCashFlow);
        }

        QL_REQUIRE(!legs_[0].empty(), "empty bond leg");
        for (Leg::const_iterator i=legs_[0].begin(); i<legs_[0].end(); ++i)
            registerWith(*i);

        if (payBondCoupon) {
            payer_[0]=-1.0;
            payer_[1]=+1.0;
        } else {
            payer_[0]=+1.0;
            payer_[1]=-1.0;
        }
    }
Example #15
0
FMOD_RESULT F_CALLBACK DSPCallback(FMOD_DSP_STATE* dsp_state, 
	f32* inbuffer, f32* outbuffer, u32 length, 
	s32 inchannels, s32* outchannels){

	assert(*outchannels >= 2);

	FMOD::DSP *thisdsp = (FMOD::DSP *)dsp_state->instance; 

	void* ud = nullptr;
	cfmod(thisdsp->getUserData(&ud));

	s32 samplerate = 0;
	cfmod(dsp_state->callbacks->getsamplerate(dsp_state, &samplerate));
	f64 inc = 1.0/samplerate;

	auto dud = static_cast<DSPUserdata*>(ud);
	auto& phase = dud->phase;

	for(u32 i = 0; i < length; i++){
		f32 out = 0.f;
		f32 outl = 0.f;
		f32 outr = 0.f;
		
		sched.PlayNotes([&](const NoteTimePair& n){
			constexpr f32 attack = 0.1;
			
			auto pos = (sched.time-n.begin)/n.length;
			f32 env;
			if(pos < attack){
				env = pos/attack;
			}else{
				env = (1.0-pos)/(1.0-attack);
			}

			f32 o = 0.0;
			// o += Wave::sin(n.freq*phase*0.5) * env * 0.2;
			// o += Wave::sin(n.freq*phase*2.0) * env;
			f32 mod = Wave::sin(phase*10.f) * .02f;
			f32 ph = n.freq*phase + mod;
			f32 a = std::min(1.f, std::max(env*env*env * .5f, 0.f)); //Wave::sin(phase*1.f)*.5f + .5f;

			env *= n.volume;
			o += (Wave::sin(ph) * (1-a) + Wave::sqr(ph*2.f) * a) * env;
			// o += Wave::sin((n.freq + Wave::tri(phase*6.f) * .01f)*phase) * env;
			// o += Wave::sin((n.freq + 0.5)*phase) * env;
			out += o/3.0;
		});

		chords.PlayNotes([&](const NoteTimePair& n){
			constexpr f32 attack = 0.005;
			
			auto pos = (chords.time-n.begin)/n.length;
			f32 env;
			if(pos < attack){
				env = pos/attack;
			}else{
				env = (1.0-pos)/(1.0-attack);
			}

			f32 mod = Wave::sin(phase*10.f) * .02f;
			f32 ph = n.freq*phase + mod;
			f32 a = env*env * .3f + .3f + Wave::sin(phase*6.f) * 0.2f;
			a = std::min(1.f, std::max(a, 0.f));

			f32 phaseShift = 0.2f + Wave::sin(phase*3.f) * .2f + .5f; //phase / 6.f;

			outl += (Wave::sin(ph) * (1-a) + Wave::tri(ph) * a) * env * n.volume;
			outr += (Wave::sin(ph + phaseShift) * (1-a) + Wave::tri(ph * 1.01) * a) * env * n.volume;
		});

		perc.PlayNotes([&](const NoteTimePair& n){
			constexpr f32 attack = 0.1;

			auto pos = (perc.time-n.begin)/n.length;
			f32 env = 0;
			if(pos < attack){
				env = pos/attack;
			}else{
				env = (1.0-pos)/(1.0-attack);
			}

			env *= n.volume;

			f32 o = 0;
			o += Wave::sin(n.freq*phase) * env;
			o += Wave::tri(n.freq*phase) * env;
			out += o;
		});

		outbuffer[i**outchannels+0] = out + outl/3.f;
		outbuffer[i**outchannels+1] = out + outr/3.f;

		phase += inc;
		chords.Update(inc/60.0* tempo);
		sched.Update(inc/60.0* tempo);
		perc.Update(inc/60.0* tempo);
	}

	return FMOD_OK;
}
bool Schedule::operator<(const Schedule& rhs) const
{
	return GetNextStartTime() < rhs.GetNextStartTime();
}
boost::optional<IdfObject> ForwardTranslator::translateZoneHVACFourPipeFanCoil(
    ZoneHVACFourPipeFanCoil & modelObject )
{
  boost::optional<std::string> s;
  boost::optional<double> value;

  IdfObject idfObject(IddObjectType::ZoneHVAC_FourPipeFanCoil);

  // Get model object name and define node names for future use
  // Model Name
  std::string baseName = modelObject.name().get();
  // Node Names
  std::string mixedAirNodeName = baseName + " Mixed Air Node";
  std::string fanOutletNodeName = baseName + " Fan Outlet Node";
  std::string coolingCoilOutletNodeName = baseName + " Cooling Coil Outlet Node";
  std::string reliefAirNodeName = baseName + " Relief Air Node";
  std::string oaNodeName = baseName + " OA Node";

  boost::optional<AirLoopHVAC> t_airLoopHVAC = modelObject.airLoopHVAC();

  // AirInletNodeName
  boost::optional<std::string> airInletNodeName;
  if( boost::optional<Node> node = modelObject.inletNode() )
  {
    if( (s = node->name()) )
    {
      airInletNodeName = s;
      idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::AirInletNodeName,s.get() );
    }
  }
  // AirOutletNodeName
  boost::optional<std::string> airOutletNodeName;
  if( boost::optional<Node> node = modelObject.outletNode() )
  {
    if( (s = node->name()) )
    {
      airOutletNodeName = s;
      idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::AirOutletNodeName,s.get() );
    }
  }

  // hook up required objects
  try {
    // AvailabilityScheduleName
    Schedule availabilitySchedule = modelObject.availabilitySchedule();
    translateAndMapModelObject(availabilitySchedule);
    idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::AvailabilityScheduleName,
                        availabilitySchedule.name().get() );

    // Supply Air Fan
    HVACComponent supplyAirFan = modelObject.supplyAirFan();
    if( boost::optional<IdfObject> _supplyAirFan = translateAndMapModelObject(supplyAirFan) )
    {
      // SupplyAirFanObjectType
      idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::SupplyAirFanObjectType,_supplyAirFan->iddObject().name() );

      // SupplyAirFanName
      idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::SupplyAirFanName,_supplyAirFan->name().get() );
      // Supply Air Fan Inlet and Outlet Nodes
      if( airOutletNodeName && airInletNodeName )
      {
        // If there is an AirLoopHVAC then we provide no mixer
        std::string fanInletNodeName;
        if( t_airLoopHVAC ) {
          fanInletNodeName = airInletNodeName.get();
        } else {
          fanInletNodeName = mixedAirNodeName;
        }

        if( _supplyAirFan->iddObject().type() == IddObjectType::Fan_ConstantVolume )
        {
          _supplyAirFan->setString(Fan_ConstantVolumeFields::AirInletNodeName,fanInletNodeName );
          _supplyAirFan->setString(Fan_ConstantVolumeFields::AirOutletNodeName,fanOutletNodeName );
        }
        else if( _supplyAirFan->iddObject().type() == IddObjectType::Fan_OnOff )
        {
          
          _supplyAirFan->setString(Fan_OnOffFields::AirInletNodeName,fanInletNodeName );
          _supplyAirFan->setString(Fan_OnOffFields::AirOutletNodeName,fanOutletNodeName );
        }
        else if( _supplyAirFan->iddObject().type() == IddObjectType::Fan_VariableVolume )
        {
          _supplyAirFan->setString(Fan_VariableVolumeFields::AirInletNodeName,fanInletNodeName );
          _supplyAirFan->setString(Fan_VariableVolumeFields::AirOutletNodeName,fanOutletNodeName );
        }
      }
    }

    // Cooling Coil
    HVACComponent coolingCoil = modelObject.coolingCoil();
    if( boost::optional<IdfObject> _coolingCoil = translateAndMapModelObject(coolingCoil) )
    {
      // CoolingCoilObjectType
      idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::CoolingCoilObjectType,_coolingCoil->iddObject().name() );
      // CoolingCoilName
      idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::CoolingCoilName,_coolingCoil->name().get() );
      // Cooling Coil Inlet and Outlet Nodes
      if( _coolingCoil->iddObject().type() == IddObjectType::Coil_Cooling_Water )
      {
        _coolingCoil->setString(Coil_Cooling_WaterFields::AirInletNodeName,fanOutletNodeName );
        _coolingCoil->setString(Coil_Cooling_WaterFields::AirOutletNodeName,coolingCoilOutletNodeName );
      }
    }

    // Heating Coil
    HVACComponent heatingCoil = modelObject.heatingCoil();
    if( boost::optional<IdfObject> _heatingCoil = translateAndMapModelObject(heatingCoil) )
    {
      // HeatingCoilObjectType
      idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::HeatingCoilObjectType,_heatingCoil->iddObject().name() );
      // HeatingCoilName
      idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::HeatingCoilName,_heatingCoil->name().get() );
      // Heating Coil Inlet and Outlet Nodes
      if( _heatingCoil->iddObject().type() == IddObjectType::Coil_Heating_Water )
      {
        _heatingCoil->setString(Coil_Heating_WaterFields::AirInletNodeName,coolingCoilOutletNodeName );
        _heatingCoil->setString(Coil_Heating_WaterFields::AirOutletNodeName,airOutletNodeName.get() );
      }
    }
  }
  catch (std::exception& e) {
    LOG(Error,"Could not translate " << modelObject.briefDescription() << ", because "
        << e.what() << ".");
    return boost::none;
  }

  m_idfObjects.push_back(idfObject);

  // Name
  idfObject.setName(baseName);

  // CapacityControlMethod
  idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::CapacityControlMethod,
                      modelObject.capacityControlMethod());

  // MaximumSupplyAirFlowRate
  if( modelObject.isMaximumSupplyAirFlowRateAutosized() )
  {
    idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::MaximumSupplyAirFlowRate,"Autosize");
  }
  else if( (value = modelObject.maximumSupplyAirFlowRate()) )
  {
    idfObject.setDouble(ZoneHVAC_FourPipeFanCoilFields::MaximumSupplyAirFlowRate,value.get());
  }

  // LowSpeedSupplyAirFlowRatio
  if(! modelObject.isLowSpeedSupplyAirFlowRatioDefaulted() )
  {
    idfObject.setDouble(ZoneHVAC_FourPipeFanCoilFields::LowSpeedSupplyAirFlowRatio,modelObject.lowSpeedSupplyAirFlowRatio() );
  }

  // MediumSpeedSupplyAirFlowRatio
  if(! (modelObject.isMediumSpeedSupplyAirFlowRatioDefaulted()) )
  {
    idfObject.setDouble(ZoneHVAC_FourPipeFanCoilFields::MediumSpeedSupplyAirFlowRatio,modelObject.mediumSpeedSupplyAirFlowRatio() );
  }

  // MaximumOutdoorAirFlowRate
  if( modelObject.isMaximumOutdoorAirFlowRateAutosized() )
  {
    idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::MaximumOutdoorAirFlowRate,"Autosize");
  }
  else if( (value = modelObject.maximumOutdoorAirFlowRate()) )
  {
    idfObject.setDouble(ZoneHVAC_FourPipeFanCoilFields::MaximumOutdoorAirFlowRate,value.get());
  }

  // OutdoorAirScheduleName
  if( boost::optional<Schedule> schedule = modelObject.outdoorAirSchedule() )
  {
    if( boost::optional<IdfObject> _schedule = translateAndMapModelObject(schedule.get()) )
    {
      idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::OutdoorAirScheduleName,_schedule->name().get());
    }
  }

  if( ! t_airLoopHVAC ) {
    // OutdoorAirMixerObjectType
    idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::OutdoorAirMixerObjectType,
                        modelObject.outdoorAirMixerObjectType());

    // OutdoorAirMixerName
    std::string oaMixerName = modelObject.name().get() + " OA Mixer";
    idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::OutdoorAirMixerName,oaMixerName);

    // Create Outdoor Air Mixer
    IdfObject _outdoorAirMixer(IddObjectType::OutdoorAir_Mixer);
    _outdoorAirMixer.setName(oaMixerName);
    m_idfObjects.push_back(_outdoorAirMixer);

    _outdoorAirMixer.setString(OutdoorAir_MixerFields::MixedAirNodeName,mixedAirNodeName);
    _outdoorAirMixer.setString(OutdoorAir_MixerFields::OutdoorAirStreamNodeName,oaNodeName);
    _outdoorAirMixer.setString(OutdoorAir_MixerFields::ReliefAirStreamNodeName,reliefAirNodeName);
    if(airInletNodeName)
    {
      _outdoorAirMixer.setString(OutdoorAir_MixerFields::ReturnAirStreamNodeName,airInletNodeName.get());
    }

    // Create Outdoor Air Node List
    IdfObject _oaNodeList(openstudio::IddObjectType::OutdoorAir_NodeList);
    _oaNodeList.setString(0,oaNodeName);
    m_idfObjects.push_back(_oaNodeList);
  }

  // MaximumColdWaterFlowRate
  if( modelObject.isMaximumColdWaterFlowRateAutosized() )
  {
    idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::MaximumColdWaterFlowRate,"Autosize");
  }
  else if( (value = modelObject.maximumColdWaterFlowRate()) )
  {
    idfObject.setDouble(ZoneHVAC_FourPipeFanCoilFields::MaximumColdWaterFlowRate,value.get());
  }

  // MinimumColdWaterFlowRate
  if(! modelObject.isMinimumColdWaterFlowRateDefaulted() )
  {
    idfObject.setDouble(ZoneHVAC_FourPipeFanCoilFields::MinimumColdWaterFlowRate,modelObject.minimumColdWaterFlowRate() );
  }

  // CoolingConvergenceTolerance
  if(! modelObject.isCoolingConvergenceToleranceDefaulted() )
  {
    idfObject.setDouble(ZoneHVAC_FourPipeFanCoilFields::CoolingConvergenceTolerance,modelObject.coolingConvergenceTolerance() );
  }

  // MaximumHotWaterFlowRate
  if( modelObject.isMaximumHotWaterFlowRateAutosized() )
  {
    idfObject.setString(ZoneHVAC_FourPipeFanCoilFields::MaximumHotWaterFlowRate,"Autosize");
  }
  else if( (value = modelObject.maximumHotWaterFlowRate()) )
  {
    idfObject.setDouble(ZoneHVAC_FourPipeFanCoilFields::MaximumHotWaterFlowRate,value.get());
  }

  // MinimumHotWaterFlowRate
  if(! modelObject.isMinimumHotWaterFlowRateDefaulted() )
  {
    idfObject.setDouble(ZoneHVAC_FourPipeFanCoilFields::MinimumHotWaterFlowRate,modelObject.minimumHotWaterFlowRate() );
  }

  // HeatingConvergenceTolerance
  if(! modelObject.isHeatingConvergenceToleranceDefaulted() )
  {
    idfObject.setDouble(ZoneHVAC_FourPipeFanCoilFields::HeatingConvergenceTolerance,modelObject.heatingConvergenceTolerance() );
  }

  return idfObject;
}
boost::optional<IdfObject> ForwardTranslator::translateZoneMixing( ZoneMixing & modelObject )
{
  // Makes sure the modelObject gets put in the map, and that the new idfObject gets put in 
  // the final file. Also set's the idfObject's name.
  IdfObject idfObject = createRegisterAndNameIdfObject(IddObjectType::ZoneMixing, modelObject);

  boost::optional<double> value;

  // ZoneName 
  ThermalZone zone = modelObject.zone();
  translateAndMapModelObject(zone);
  idfObject.setString(ZoneMixingFields::ZoneName, zone.name().get());

  // ScheduleName 
  Schedule schedule = modelObject.schedule();
  translateAndMapModelObject(schedule);
  idfObject.setString(ZoneMixingFields::ScheduleName, schedule.name().get());

  // DesignFlowRateCalculationMethod
  idfObject.setString(ZoneMixingFields::DesignFlowRateCalculationMethod, modelObject.designFlowRateCalculationMethod());

  // DesignFlowRate
  value = modelObject.designFlowRate();
  if (value){
    idfObject.setDouble(ZoneMixingFields::DesignFlowRate, *value);
  }

  // FlowRateperZoneFloorArea
  value = modelObject.flowRateperZoneFloorArea();
  if (value){
    idfObject.setDouble(ZoneMixingFields::FlowRateperZoneFloorArea, *value);
  }

  // FlowRateperPerson
  value = modelObject.flowRateperPerson();
  if (value){
    idfObject.setDouble(ZoneMixingFields::FlowRateperPerson, *value);
  }

  // AirChangesperHour
  value = modelObject.airChangesperHour();
  if (value){
    idfObject.setDouble(ZoneMixingFields::AirChangesperHour, *value);
  }

  // SourceZone
  boost::optional<ThermalZone> sourceZone = modelObject.sourceZone();
  if (sourceZone){
    // DLM: do not translate source zone now, it will be translated at the right time
    idfObject.setString(ZoneMixingFields::SourceZoneName, sourceZone->name().get());
  }

  // DeltaTemperature
  value = modelObject.deltaTemperature();
  if (value){
    idfObject.setDouble(ZoneMixingFields::DeltaTemperature, *value);
  }

  // DeltaTemperatureScheduleName
  boost::optional<Schedule> optSchedule = modelObject.deltaTemperatureSchedule();
  if (optSchedule){
    translateAndMapModelObject(*optSchedule);
    idfObject.setString(ZoneMixingFields::DeltaTemperatureScheduleName, optSchedule->name().get());
  }
  
  // MinimumZoneTemperatureScheduleName
  optSchedule = modelObject.minimumZoneTemperatureSchedule();
  if (optSchedule){
    translateAndMapModelObject(*optSchedule);
    idfObject.setString(ZoneMixingFields::MinimumZoneTemperatureScheduleName, optSchedule->name().get());
  }

  // MaximumZoneTemperatureScheduleName
  optSchedule = modelObject.maximumZoneTemperatureSchedule();
  if (optSchedule){
    translateAndMapModelObject(*optSchedule);
    idfObject.setString(ZoneMixingFields::MaximumZoneTemperatureScheduleName, optSchedule->name().get());
  }

  // MinimumSourceZoneTemperatureScheduleName
  optSchedule = modelObject.minimumSourceZoneTemperatureSchedule();
  if (optSchedule){
    translateAndMapModelObject(*optSchedule);
    idfObject.setString(ZoneMixingFields::MinimumSourceZoneTemperatureScheduleName, optSchedule->name().get());
  }

  // MaximumSourceZoneTemperatureScheduleName
  optSchedule = modelObject.maximumSourceZoneTemperatureSchedule();
  if (optSchedule){
    translateAndMapModelObject(*optSchedule);
    idfObject.setString(ZoneMixingFields::MaximumSourceZoneTemperatureScheduleName, optSchedule->name().get());
  }

  // MinimumOutdoorTemperatureScheduleName
  optSchedule = modelObject.minimumOutdoorTemperatureSchedule();
  if (optSchedule){
    translateAndMapModelObject(*optSchedule);
    idfObject.setString(ZoneMixingFields::MinimumOutdoorTemperatureScheduleName, optSchedule->name().get());
  }

  // MaximumOutdoorTemperatureScheduleName
  optSchedule = modelObject.maximumOutdoorTemperatureSchedule();
  if (optSchedule){
    translateAndMapModelObject(*optSchedule);
    idfObject.setString(ZoneMixingFields::MaximumOutdoorTemperatureScheduleName, optSchedule->name().get());
  }

  return idfObject;
}
Example #19
0
void InflationTest::testYYIndex() {
    BOOST_MESSAGE("Testing year-on-year inflation indices...");

    SavedSettings backup;

    YYEUHICP yyeuhicp(true);
    if (yyeuhicp.name() != "EU YY_HICP"
        || yyeuhicp.frequency() != Monthly
        || yyeuhicp.revised()
        || !yyeuhicp.interpolated()
        || yyeuhicp.ratio()
        || yyeuhicp.availabilityLag() != 1*Months) {
        BOOST_ERROR("wrong year-on-year EU HICP data ("
                    << yyeuhicp.name() << ", "
                    << yyeuhicp.frequency() << ", "
                    << yyeuhicp.revised() << ", "
                    << yyeuhicp.interpolated() << ", "
                    << yyeuhicp.ratio() << ", "
                    << yyeuhicp.availabilityLag() << ")");
    }

    YYEUHICPr yyeuhicpr(true);
    if (yyeuhicpr.name() != "EU YYR_HICP"
        || yyeuhicpr.frequency() != Monthly
        || yyeuhicpr.revised()
        || !yyeuhicpr.interpolated()
        || !yyeuhicpr.ratio()
        || yyeuhicpr.availabilityLag() != 1*Months) {
        BOOST_ERROR("wrong year-on-year EU HICPr data ("
                    << yyeuhicpr.name() << ", "
                    << yyeuhicpr.frequency() << ", "
                    << yyeuhicpr.revised() << ", "
                    << yyeuhicpr.interpolated() << ", "
                    << yyeuhicpr.ratio() << ", "
                    << yyeuhicpr.availabilityLag() << ")");
    }

    YYUKRPI yyukrpi(false);
    if (yyukrpi.name() != "UK YY_RPI"
        || yyukrpi.frequency() != Monthly
        || yyukrpi.revised()
        || yyukrpi.interpolated()
        || yyukrpi.ratio()
        || yyukrpi.availabilityLag() != 1*Months) {
        BOOST_ERROR("wrong year-on-year UK RPI data ("
                    << yyukrpi.name() << ", "
                    << yyukrpi.frequency() << ", "
                    << yyukrpi.revised() << ", "
                    << yyukrpi.interpolated() << ", "
                    << yyukrpi.ratio() << ", "
                    << yyukrpi.availabilityLag() << ")");
    }

    YYUKRPIr yyukrpir(false);
    if (yyukrpir.name() != "UK YYR_RPI"
        || yyukrpir.frequency() != Monthly
        || yyukrpir.revised()
        || yyukrpir.interpolated()
        || !yyukrpir.ratio()
        || yyukrpir.availabilityLag() != 1*Months) {
        BOOST_ERROR("wrong year-on-year UK RPIr data ("
                    << yyukrpir.name() << ", "
                    << yyukrpir.frequency() << ", "
                    << yyukrpir.revised() << ", "
                    << yyukrpir.interpolated() << ", "
                    << yyukrpir.ratio() << ", "
                    << yyukrpir.availabilityLag() << ")");
    }


    // Retrieval test.
    //----------------
    // make sure of the evaluation date
    Date evaluationDate(13, August, 2007);
    evaluationDate = UnitedKingdom().adjust(evaluationDate);
    Settings::instance().evaluationDate() = evaluationDate;

    // fixing data
    Date from(1, January, 2005);
    Date to(13, August, 2007);
    Schedule rpiSchedule = MakeSchedule().from(from).to(to)
    .withTenor(1*Months)
    .withCalendar(UnitedKingdom())
    .withConvention(ModifiedFollowing);

    Real fixData[] = { 189.9, 189.9, 189.6, 190.5, 191.6, 192.0,
        192.2, 192.2, 192.6, 193.1, 193.3, 193.6,
        194.1, 193.4, 194.2, 195.0, 196.5, 197.7,
        198.5, 198.5, 199.2, 200.1, 200.4, 201.1,
        202.7, 201.6, 203.1, 204.4, 205.4, 206.2,
        207.3, -999.0, -999.0 };

    bool interp = false;
    boost::shared_ptr<YYUKRPIr> iir(new YYUKRPIr(interp));
    boost::shared_ptr<YYUKRPIr> iirYES(new YYUKRPIr(true));
    for (Size i=0; i<rpiSchedule.size();i++) {
        iir->addFixing(rpiSchedule[i], fixData[i]);
        iirYES->addFixing(rpiSchedule[i], fixData[i]);
    }

    Date todayMinusLag = evaluationDate - iir->availabilityLag();
    std::pair<Date,Date> lim = inflationPeriod(todayMinusLag, iir->frequency());
    todayMinusLag = lim.second + 1 - 2*Period(iir->frequency());

    Real eps = 1.0e-8;

    // Interpolation tests
    //--------------------
    // (no TS so can't forecast).
    for (Size i=13; i<rpiSchedule.size();i++) {
        std::pair<Date,Date> lim = inflationPeriod(rpiSchedule[i],
                                                   iir->frequency());
        std::pair<Date,Date> limBef = inflationPeriod(rpiSchedule[i-12],
                                                      iir->frequency());
        for (Date d=lim.first; d<=lim.second; d++) {
            if (d < todayMinusLag) {
                Rate expected = fixData[i]/fixData[i-12] - 1.0;
                Rate calculated = iir->fixing(d);
                BOOST_CHECK_MESSAGE(std::fabs(calculated - expected) < eps,
                                    "Non-interpolated fixings not constant within a period: "
                                    << calculated
                                    << ", should be "
                                    << expected);

                Real dp= lim.second + 1- lim.first;
                Real dpBef=limBef.second + 1 - limBef.first;
                Real dl = d-lim.first;
                // potentially does not work on 29th Feb
                Real dlBef = NullCalendar().advance(d, -1*Years, ModifiedFollowing)
                -limBef.first;

                Real linearNow = fixData[i] + (fixData[i+1]-fixData[i])*dl/dp;
                Real linearBef = fixData[i-12] + (fixData[i+1-12]-fixData[i-12])*dlBef/dpBef;
                Rate expectedYES = linearNow / linearBef - 1.0;
                Rate calculatedYES = iirYES->fixing(d);
                BOOST_CHECK_MESSAGE(fabs(expectedYES-calculatedYES)<eps,
                                    "Error in interpolated fixings: expect "<<expectedYES
                                    <<" see " << calculatedYES
                                    <<" flat " << calculated
                                    <<", data: "<< fixData[i-12] <<", "<< fixData[i+1-12]
                                    <<", "<<    fixData[i] <<", "<< fixData[i+1]
                                    <<", fac: "<< dp <<", "<< dl
                                    <<", "<< dpBef <<", "<< dlBef
                                    <<", to: "<<linearNow<<", "<<linearBef
                                    );
            }
        }
    }

}
boost::optional<IdfObject> ForwardTranslator::translateZoneHVACUnitHeater(
    ZoneHVACUnitHeater & modelObject )
{
  // Make sure the modelObject gets ut into the map, and the new idfObject gets put into the final file.
  // Also sets the idfObjects name

  IdfObject idfObject = createRegisterAndNameIdfObject(IddObjectType::ZoneHVAC_UnitHeater,modelObject);
  
  
  boost::optional<std::string> s;
  boost::optional<double> value;
  boost::optional<Node> node;
  
  // Get model object name and define node names for future use
  
  // Model Name
  std::string baseName = modelObject.name().get();
  
  // Node Names
  std::string fanOutletNodeName = baseName + " Fan Outlet Node";
  
  // Field: Availability Schedule Name

  Schedule availabilitySchedule = modelObject.availabilitySchedule();
  translateAndMapModelObject(availabilitySchedule);
  
  s = availabilitySchedule.name();
  
  if(s)
  {
    idfObject.setString(ZoneHVAC_UnitHeaterFields::AvailabilityScheduleName,*s);
  }

  // Field: Air Inlet Node Name
  
  node = modelObject.inletNode();
  
  if(node)
  {
    s = node->name();

    if(s)
    {
      idfObject.setString(ZoneHVAC_UnitHeaterFields::AirInletNodeName,*s);
    }
  }

  // Field: Air Outlet Node Name
  
  node = modelObject.outletNode();

  if(node)
  {
    s = node->name();

    if(s)
    {
      idfObject.setString(ZoneHVAC_UnitHeaterFields::AirOutletNodeName,*s);
    }
  }

  //Field: Supply Air Fan Object Type

  HVACComponent supplyAirFan = modelObject.supplyAirFan();

  if(boost::optional<IdfObject> _supplyAirFan = translateAndMapModelObject(supplyAirFan)) 
  {
    idfObject.setString(ZoneHVAC_UnitHeaterFields::SupplyAirFanObjectType,_supplyAirFan->iddObject().name());
  }

  // Field: Supply Air Fan Name
  
  s = modelObject.supplyAirFan().name();
   

  if(s)

  {
    idfObject.setString(ZoneHVAC_UnitHeaterFields::SupplyAirFanName,*s);
  }

  // Supply Air Fan Inlet and Outlet Nodes
  
  node = modelObject.inletNode();
  
  if(boost::optional<IdfObject> _supplyAirFan = translateAndMapModelObject(supplyAirFan))
  {
  
    if(node)
    {
      s = node->name();

      if( _supplyAirFan->iddObject().type() == IddObjectType::Fan_ConstantVolume)
      {
        _supplyAirFan->setString(Fan_ConstantVolumeFields::AirInletNodeName,*s);
        _supplyAirFan->setString(Fan_ConstantVolumeFields::AirOutletNodeName,fanOutletNodeName);
      }
      else if( _supplyAirFan->iddObject().type() == IddObjectType::Fan_VariableVolume )
      {
        _supplyAirFan->setString(Fan_VariableVolumeFields::AirInletNodeName,*s);
        _supplyAirFan->setString(Fan_VariableVolumeFields::AirOutletNodeName,fanOutletNodeName);
      }
    }
  }

  // Field Maximum Supply Air Flow Rate

  if( modelObject.isMaximumSupplyAirFlowRateAutosized())
  {
    idfObject.setString(ZoneHVAC_UnitHeaterFields::MaximumSupplyAirFlowRate,"Autosize");
  }

  else if ( (value = modelObject.maximumSupplyAirFlowRate()) )
  {
    idfObject.setDouble(ZoneHVAC_UnitHeaterFields::MaximumSupplyAirFlowRate,*value);
  }

  // Field: Fan Control Type

   idfObject.setString(ZoneHVAC_UnitHeaterFields::FanControlType,modelObject.fanControlType());

   // Field: Heating Coil Object Type

  HVACComponent heatingCoil = modelObject.heatingCoil();

  if( boost::optional<IdfObject> _heatingCoil = translateAndMapModelObject(heatingCoil))
  {
    idfObject.setString(ZoneHVAC_UnitHeaterFields::HeatingCoilObjectType,_heatingCoil->iddObject().name());
  }

   // Field: Heating Coil Name

  s = modelObject.heatingCoil().name();
   
  if(s)
  {
    idfObject.setString(ZoneHVAC_UnitHeaterFields::HeatingCoilName,*s);
  }

  // Heating coil inlet and outlet node names

  node = modelObject.outletNode();
  
  if(boost::optional<IdfObject> _heatingCoil = translateAndMapModelObject(heatingCoil))
  {
    if(node)
    {
      s = node->name();

      if( _heatingCoil->iddObject().type() == IddObjectType::Coil_Heating_Electric)
      {
        _heatingCoil->setString(Coil_Heating_ElectricFields::AirInletNodeName,fanOutletNodeName);
        _heatingCoil->setString(Coil_Heating_ElectricFields::AirOutletNodeName,*s);
      }
      else if( _heatingCoil->iddObject().type() == IddObjectType::Coil_Heating_Gas )
      {
        _heatingCoil->setString(Coil_Heating_GasFields::AirInletNodeName,fanOutletNodeName);
        _heatingCoil->setString(Coil_Heating_GasFields::AirOutletNodeName,*s);
      }
      else if( _heatingCoil->iddObject().type() == IddObjectType::Coil_Heating_Water )
      {
        _heatingCoil->setString(Coil_Heating_WaterFields::AirInletNodeName,fanOutletNodeName);
        _heatingCoil->setString(Coil_Heating_WaterFields::AirOutletNodeName,*s);
      }
    }
  }

  // Field Maximum Hot Water [or Steam] Flow Rate

  if( modelObject.isMaximumHotWaterFlowRateAutosized())
  
  {
    idfObject.setString(ZoneHVAC_UnitHeaterFields::MaximumHotWaterorSteamFlowRate,"Autosize");
  }

  else if ( (value = modelObject.maximumHotWaterFlowRate()) )
  {
     idfObject.setDouble(ZoneHVAC_UnitHeaterFields::MaximumHotWaterorSteamFlowRate,*value);
  }

  // Field: Minimum Hot Water [or Steam] Flow Rate

  idfObject.setDouble(ZoneHVAC_UnitHeaterFields::MinimumHotWaterorSteamFlowRate,modelObject.minimumHotWaterFlowRate());

 // Field: Heating Convergence Tolerance

  idfObject.setDouble(ZoneHVAC_UnitHeaterFields::HeatingConvergenceTolerance,modelObject.heatingConvergenceTolerance());

  // Field: Availability Manager List Name: Ignored?

  return idfObject;
}
Example #21
0
void InflationTest::testZeroIndex() {
    BOOST_MESSAGE("Testing zero inflation indices...");

    SavedSettings backup;

    EUHICP euhicp(true);
    if (euhicp.name() != "EU HICP"
        || euhicp.frequency() != Monthly
        || euhicp.revised()
        || !euhicp.interpolated()
        || euhicp.availabilityLag() != 1*Months) {
        BOOST_ERROR("wrong EU HICP data ("
                    << euhicp.name() << ", "
                    << euhicp.frequency() << ", "
                    << euhicp.revised() << ", "
                    << euhicp.interpolated() << ", "
                    << euhicp.availabilityLag() << ")");
    }

    UKRPI ukrpi(false);
    if (ukrpi.name() != "UK RPI"
        || ukrpi.frequency() != Monthly
        || ukrpi.revised()
        || ukrpi.interpolated()
        || ukrpi.availabilityLag() != 1*Months) {
        BOOST_ERROR("wrong UK RPI data ("
                    << ukrpi.name() << ", "
                    << ukrpi.frequency() << ", "
                    << ukrpi.revised() << ", "
                    << ukrpi.interpolated() << ", "
                    << ukrpi.availabilityLag() << ")");
    }

    // Retrieval test.
    //----------------
    // make sure of the evaluation date
    Date evaluationDate(13, August, 2007);
    evaluationDate = UnitedKingdom().adjust(evaluationDate);
    Settings::instance().evaluationDate() = evaluationDate;

    // fixing data
    Date from(1, January, 2005);
    Date to(13, August, 2007);
    Schedule rpiSchedule = MakeSchedule().from(from).to(to)
    .withTenor(1*Months)
    .withCalendar(UnitedKingdom())
    .withConvention(ModifiedFollowing);

    Real fixData[] = { 189.9, 189.9, 189.6, 190.5, 191.6, 192.0,
        192.2, 192.2, 192.6, 193.1, 193.3, 193.6,
        194.1, 193.4, 194.2, 195.0, 196.5, 197.7,
        198.5, 198.5, 199.2, 200.1, 200.4, 201.1,
        202.7, 201.6, 203.1, 204.4, 205.4, 206.2,
        207.3, 206.1, -999.0 };

    bool interp = false;
    boost::shared_ptr<UKRPI> iir(new UKRPI(interp));
    for (Size i=0; i<rpiSchedule.size();i++) {
        iir->addFixing(rpiSchedule[i], fixData[i]);
    }

    Date todayMinusLag = evaluationDate - iir->availabilityLag();
    std::pair<Date,Date> lim = inflationPeriod(todayMinusLag, iir->frequency());
    todayMinusLag = lim.first;

    Real eps = 1.0e-8;

    // -1 because last value not yet available,
    // (no TS so can't forecast).
    for (Size i=0; i<rpiSchedule.size()-1;i++) {
        std::pair<Date,Date> lim = inflationPeriod(rpiSchedule[i],
                                                   iir->frequency());
        for (Date d=lim.first; d<=lim.second; d++) {
            if (d < inflationPeriod(todayMinusLag,iir->frequency()).first) {
                if (std::fabs(iir->fixing(d) - fixData[i]) > eps)
                    BOOST_ERROR("Fixings not constant within a period: "
                                << iir->fixing(d)
                                << ", should be " << fixData[i]);
            }
        }
    }
}
void ScheduleManager::registerPrice(Schedule &schedule)
{
	for (Price price;;)
	{
		system("cls");
		cout <<
			"극장 관리 시스템\n"
			" > 상영 일정 관리\n"
			"  > 상영 일정 확인/수정\n"
			"   > 가격 등록\n\n"

			"선택한 상영 일정\n";
		schedule.date.show();
		schedule.screen.show();
		schedule.show();
		
		if (0 < price.getCode())
		{
			cout << "\n선택한 가격 정보\n";
			price.show();

			cout << "\n등록하시겠습니까?(y/n): ";
			switch (inputYN())
			{
			case FUNCTION_ERROR:
				cout << "\n잘못된 입력입니다.\n";
				system("pause");
				break;
			case FUNCTION_SUCCESS:
				SQLWCHAR sql[BUFSIZ];
				swprintf_s(sql, L""
					"INSERT INTO d%d "
					"(schedule_id, code, name, won) "
					"VALUES (%d, ?, ?, ?);", schedule.date.getValue(), schedule.getId());
				if (SQL_SUCCESS == price.bindParameter(MDF_PRICE)
					&& SQL_SUCCESS == price.execute(MDF_PRICE, sql))
				{
					cout << "\n등록되었습니다.\n";
					system("pause");
				}
				else
				{
					cout << "\n오류가 발생했습니다.(registerPrice)\n";
					system("pause");
					break;
				}
			case FUNCTION_CANCEL:
				price.initialize();
			}
		}
		else
		{
			if (SQL_SUCCESS != price.bindCol(MDF_THEATER)
				|| SQL_SUCCESS != price.prepare(MDF_THEATER, L"SELECT code, name, won FROM price;"))
			{
				cout << "오류가 발생했습니다.(registerPrice)\n";
				system("pause");
				return;
			}

			switch (price.choose(MDF_THEATER))
			{
			case FUNCTION_NULL:
				cout << "등록된 가격 정보가 없습니다.\n";
				system("pause");
			case FUNCTION_ERROR:
			case FUNCTION_CANCEL:
				return;
			}
		}
	}
}
Example #23
0
// TODO: complete this to work. Or determine how to do this.
void TestModels::test_ModelAPIs_currentSchedule()
{
    Schedule* sch = ModelAPIs::currentSchedule("running");
    QVERIFY(sch->element()->name() == "running");
    QVERIFY(ModelAPIs::currentSchedule("noName") == 0);
}
void LgmSwaptionEngineAD::calculate() const {

    // collect data needed for core computation routine

    QL_REQUIRE(arguments_.settlementType == Settlement::Physical,
               "cash-settled swaptions not yet implemented ...");

    Date settlement = model_->termStructure()->referenceDate();

    if (arguments_.exercise->dates().back() <=
        settlement) { // swaption is expired, possibly generated swap is not
                      // valued
        results_.value = 0.0;
        return;
    }

    int idxMax = static_cast<int>(arguments_.exercise->dates().size()) - 1;
    int minIdxAlive = static_cast<int>(
        std::upper_bound(arguments_.exercise->dates().begin(),
                         arguments_.exercise->dates().end(), settlement) -
        arguments_.exercise->dates().begin());

    VanillaSwap swap = *arguments_.swap;

    int callput = arguments_.type == VanillaSwap::Payer ? 1 : -1;

    Schedule fixedSchedule = swap.fixedSchedule();
    Schedule floatSchedule = swap.floatingSchedule();

    Date expiry0;

    std::vector<int> fix_startidxes, float_startidxes;
    std::vector<Date> expiryDates;

    for (int idx = minIdxAlive; idx <= idxMax; ++idx) {
        expiry0 = arguments_.exercise->dates()[idx];
        expiryDates.push_back(expiry0);

        Size j1 = std::upper_bound(fixedSchedule.dates().begin(),
                                   fixedSchedule.dates().end(), expiry0 - 1) -
                  fixedSchedule.dates().begin();
        Size k1 = std::upper_bound(floatSchedule.dates().begin(),
                                   floatSchedule.dates().end(), expiry0 - 1) -
                  floatSchedule.dates().begin();

        fix_startidxes.push_back(j1);
        float_startidxes.push_back(k1);
    }

    std::vector<double> float_mults, index_acctimes, float_spreads, fix_cpn;
    std::vector<Date> floatt1Dates, floatt2Dates, floattpDates;
    std::vector<Date> fixtpDates;

    for (Size i = 0; i < arguments_.floatingFixingDates.size(); ++i) {
        float_mults.push_back(arguments_.nominal *
                              arguments_.floatingAccrualTimes[i]);
        float_spreads.push_back(arguments_.floatingSpreads[i]);
        boost::shared_ptr<IborIndex> index = arguments_.swap->iborIndex();
        Date d1 = index->valueDate(arguments_.floatingFixingDates[i]);
        Date d2 = index->maturityDate(d1);
        double acctime = index->dayCounter().yearFraction(d1, d2, d1, d2);
        floatt1Dates.push_back(d1);
        floatt2Dates.push_back(d2);
        floattpDates.push_back(arguments_.floatingPayDates[i]);
        index_acctimes.push_back(acctime);
    }

    for (Size i = 0; i < arguments_.fixedCoupons.size(); ++i) {
        fix_cpn.push_back(arguments_.fixedCoupons[i]);
        fixtpDates.push_back(arguments_.fixedPayDates[i]);
    }

    // join all dates and fill index vectors

    std::vector<Date> allDates;
    std::vector<double> allTimes; // with settlement as first entry !
    std::vector<int> expiries, floatt1s, floatt2s, floattps, fixtps;
    std::vector<double> modpar;

    allDates.reserve(expiryDates.size() + floatt1Dates.size() +
                     floatt2Dates.size() + floattpDates.size() +
                     fixtpDates.size());

    allTimes.reserve(allDates.size());
    modpar.reserve(3 * allDates.size());

    allDates.push_back(settlement);
    allDates.insert(allDates.end(), expiryDates.begin(), expiryDates.end());
    allDates.insert(allDates.end(), floatt1Dates.begin(), floatt1Dates.end());
    allDates.insert(allDates.end(), floatt2Dates.begin(), floatt2Dates.end());
    allDates.insert(allDates.end(), floattpDates.begin(), floattpDates.end());
    allDates.insert(allDates.end(), fixtpDates.begin(), fixtpDates.end());

    std::sort(allDates.begin(), allDates.end());
    allDates.erase(unique(allDates.begin(), allDates.end()), allDates.end());

    for (Size i = 0; i < allDates.size(); ++i) {
        allTimes.push_back(
            model_->termStructure()->timeFromReference(allDates[i]));
    }

    for (Size i = 0; i < allDates.size(); ++i) {
        modpar.push_back(model_->parametrization()->H(allTimes[i]));
    }
    for (Size i = 0; i < allDates.size(); ++i) {
        modpar.push_back(model_->parametrization()->zeta(allTimes[i]));
    }
    for (Size i = 0; i < allDates.size(); ++i) {
        modpar.push_back(model_->termStructure()->discount(allTimes[i]));
    }

    for (Size i = 0; i < expiryDates.size(); ++i) {
        expiries.push_back(
            std::find(allDates.begin(), allDates.end(), expiryDates[i]) -
            allDates.begin());
    }
    for (Size i = 0; i < floatt1Dates.size(); ++i) {
        floatt1s.push_back(
            std::find(allDates.begin(), allDates.end(), floatt1Dates[i]) -
            allDates.begin());
    }
    for (Size i = 0; i < floatt2Dates.size(); ++i) {
        floatt2s.push_back(
            std::find(allDates.begin(), allDates.end(), floatt2Dates[i]) -
            allDates.begin());
    }
    for (Size i = 0; i < floattpDates.size(); ++i) {
        floattps.push_back(
            std::find(allDates.begin(), allDates.end(), floattpDates[i]) -
            allDates.begin());
    }
    for (Size i = 0; i < fixtpDates.size(); ++i) {
        fixtps.push_back(
            std::find(allDates.begin(), allDates.end(), fixtpDates[i]) -
            allDates.begin());
    }

    // call core computation routine and set results

    int ntimes = allTimes.size();
    int nexpiries = expiries.size();
    int nfloats = floatt1s.size();
    int nfixs = fix_cpn.size();

    double res = 0.0;
    std::vector<Real> dres(3*ntimes);
    int integration_pts = integrationPoints_;
    double std_devs = stddevs_;
    lgm_swaption_engine_ad_(&ntimes, &allTimes[0], &modpar[0], &nexpiries,
                         &expiries[0], &callput, &nfloats, &float_startidxes[0],
                         &float_mults[0], &index_acctimes[0], &float_spreads[0],
                         &floatt1s[0], &floatt2s[0], &floattps[0],
                         &fix_startidxes[0], &nfixs, &fix_cpn[0], &fixtps[0],
                         &integration_pts, &std_devs, &res, &dres[0]);

    results_.value = res;

    std::vector<Real> H_sensitivity(dres.begin(),dres.begin()+ntimes);
    std::vector<Real> zeta_sensitivity(dres.begin()+ntimes,dres.begin()+2*ntimes);
    std::vector<Real> discount_sensitivity(dres.begin()+2*ntimes,dres.begin()+3*ntimes);

    results_.additionalResults["sensitivityTimes"] = allTimes;
    results_.additionalResults["sensitivityH"] = H_sensitivity;
    results_.additionalResults["sensitivityZeta"] = zeta_sensitivity;
    results_.additionalResults["sensitivityDiscount"] = discount_sensitivity;

}
Example #25
0
// scheduling ordered due to prioretization criteria
void Scheduler::OrderedScheme(int criteriaNumber){
   try{
      maxEff = 0.0;
      // get pointer to criteria 
      unique_ptr<CriteriaMethod> criteria = CriteriaFactory::GetMethod(data,criteriaNumber);
      bool tendsToMin = criteria->TendsToMin();
      // unscheduled WF numbers
      vector <int> unscheduled;
      for (int i = 0; i < data.GetWFCount(); i++)
         unscheduled.push_back(i);
      int stage = 0;
      // while we have unscheduled WFs
      while (unscheduled.size() != 0){
         //if (stage % 10 == 0) cout << "Stage " << stage << endl;
         stage++;
         // best schedule (from the prioretization criteria point of view)
         Schedule best;
         // and "best" wf number
         int bestWFNum = -1;
         // max eff (on this iteration)
         double currentBestEff = 0.0;
         // current best criteria value
         double bestCriteria = tendsToMin ? numeric_limits<double>::max() : 
            -1 * numeric_limits<double>::max();
         // busy intervals for best schedule

         vector<vector <BusyIntervals>> storedIntervals;
         // for each unscheduled WF
         for (auto &wfNum : unscheduled){
            Schedule current;
            unique_ptr <SchedulingMethod> method = 
               SchedulingFactory::GetMethod(data, methodsSet[wfNum], wfNum);
            // get current schedule in current variable
            double currentEff = method->GetWFSchedule(current);
            // get current criteria
            double currentCriteria = criteria->GetCriteria(current, wfNum);
            if (criteria->IsBetter(currentCriteria, bestCriteria)){
               best = current;
               bestWFNum = wfNum;
               currentBestEff = currentEff;
               bestCriteria = currentCriteria;
               storedIntervals.clear();
               data.GetCurrentIntervals(storedIntervals);
            }
            data.ResetBusyIntervals();
         }

         // set local to global packages
         int initNum = data.GetInitPackageNumber(bestWFNum);
         for (int i = 0; i < best.size(); i++)
            best[i].get<0>() += initNum;
         // add best schedule to full schedule
         copy(best.begin(), best.end(), back_inserter(fullSchedule));

         data.SetCurrentIntervals(storedIntervals);
         data.FixBusyIntervals();

         maxEff += currentBestEff;

         //cout << "Best wf num: " << bestWFNum << " bestCriteria: " << bestCriteria << endl;
         if (bestWFNum == -1) { 
            cout << "unscheduled.size() == " << unscheduled.size() << endl;
            break;
         }
         auto idx = find(unscheduled.begin(), unscheduled.end(), bestWFNum);
         if (idx == unscheduled.end()) 
            throw UserException("Scheduler::OrderedScheme(int) error. Best wf number was not found");
         unscheduled.erase(idx);
      }
      data.SetInitBusyIntervals();
      maxEff /= maxPossible;
      cout << "Ordered scheme eff: " << maxEff << endl;
      xmlWriter->SetXMLBaseName("Ordered_");
      // write result to XML
      xmlWriter->CreateXML(fullSchedule, -1);
      string resFileName = "ordered.txt";
      ofstream res(resFileName);
      if (res.fail()) 
         throw UserException("Scheduler::OrderedScheme error. Unable to create res file");
      PrintOneWFSched(res, fullSchedule, -1);
      res.close();
   }
   catch (UserException& e){
      cout<<"error : " << e.what() <<endl;
      std::system("pause");
      exit(EXIT_FAILURE);
   }
}
boost::optional<IdfObject> ForwardTranslator::translateCoilCoolingDXTwoSpeedWithoutUnitary( model::CoilCoolingDXTwoSpeed & modelObject )
{
  //setup two boost optionals to use to store get method returns
  boost::optional<std::string> s;
  boost::optional<double> d;

  //create the IdfObject that will be the coil
  IdfObject idfObject(IddObjectType::Coil_Cooling_DX_TwoSpeed);

  //Name
  m_idfObjects.push_back(idfObject);
  s = modelObject.name();
  if( s )
  {
    idfObject.setName(*s);
  }

  //  A2 , \field Availability Schedule Name
  Schedule sched = modelObject.getAvailabilitySchedule();
  translateAndMapModelObject(sched);
  idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::AvailabilityScheduleName,
                      sched.name().get() );

  //  N1 , \field Rated High Speed Total Cooling Capacity
  d = modelObject.getRatedHighSpeedTotalCoolingCapacity();
  if( d )
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::RatedHighSpeedTotalCoolingCapacity,*d);
  }
  else
  {
    idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::RatedHighSpeedTotalCoolingCapacity,"Autosize");
  }

  //  N2 , \field Rated High Speed Sensible Heat Ratio
  d = modelObject.getRatedHighSpeedSensibleHeatRatio();
  if( d )
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::RatedHighSpeedSensibleHeatRatio,*d);
  }
  else
  {
    idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::RatedHighSpeedSensibleHeatRatio,"Autosize");
  }

  //  N3 , \field Rated High Speed COP
  d = modelObject.getRatedHighSpeedCOP();
  if( d )
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::RatedHighSpeedCOP,*d);
  }

  //  N4 , \field Rated High Speed Air Flow Rate
  d = modelObject.getRatedHighSpeedAirFlowRate();
  if( d )
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::RatedHighSpeedAirFlowRate,*d);
  }
  else
  {
    idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::RatedHighSpeedAirFlowRate,"Autosize");
  }

  //A3 , \field Air Inlet Node Name
  OptionalModelObject omo = modelObject.inletModelObject();
  if( omo )
  {
    translateAndMapModelObject(*omo);
    s = omo->name();
    if(s)
    {
      idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::AirInletNodeName,*s );
    }
  }

  //A4 , \field Air Outlet Node Name
  omo= modelObject.outletModelObject();
  if( omo )
  {
    translateAndMapModelObject(*omo);
    s = omo->name();
    if(s)
    {
      idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::AirOutletNodeName,*s);
    }
  }

  //  A5 , \field Total Cooling Capacity Function of Temperature Curve Name
  Curve cb =  modelObject.getTotalCoolingCapacityFunctionOfTemperatureCurve();
  translateAndMapModelObject(cb);
  idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::TotalCoolingCapacityFunctionofTemperatureCurveName,
                     cb.name().get());

  //  A6 , \field Total Cooling Capacity Function of Flow Fraction Curve Name
  cb =  modelObject.getTotalCoolingCapacityFunctionOfFlowFractionCurve();
  translateAndMapModelObject(cb);
  idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::TotalCoolingCapacityFunctionofFlowFractionCurveName,
                     cb.name().get());

  //  A7 , \field Energy Input Ratio Function of Temperature Curve Name
  cb =modelObject.getEnergyInputRatioFunctionOfTemperatureCurve();
  translateAndMapModelObject(cb);
  idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::EnergyInputRatioFunctionofTemperatureCurveName,
                      cb.name().get());

  //  A8 , \field Energy Input Ratio Function of Flow Fraction Curve Name
  Curve cq = modelObject.getEnergyInputRatioFunctionOfFlowFractionCurve();
  translateAndMapModelObject(cq);
  idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::EnergyInputRatioFunctionofFlowFractionCurveName,
                      cq.name().get());

  //  A9 , \field Part Load Fraction Correlation Curve Name
  cq = modelObject.getPartLoadFractionCorrelationCurve();
  translateAndMapModelObject(cq);
  idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::PartLoadFractionCorrelationCurveName,
                      cq.name().get());

  //  N5 , \field Rated Low Speed Total Cooling Capacity
  d = modelObject.getRatedLowSpeedTotalCoolingCapacity();
  if( d )
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::RatedLowSpeedTotalCoolingCapacity,*d);
  }
  else
  {
    idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::RatedLowSpeedTotalCoolingCapacity,"Autosize");
  }

  //  N6 , \field Rated Low Speed Sensible Heat Ratio
  d = modelObject.getRatedLowSpeedSensibleHeatRatio();
  if( d )
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::RatedLowSpeedSensibleHeatRatio,*d);
  }
  else
  {
    idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::RatedLowSpeedSensibleHeatRatio,"Autosize");
  }

  //  N7 , \field Rated Low Speed COP
  d = modelObject.getRatedLowSpeedCOP();
  if( d )
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::RatedLowSpeedCOP,*d);
  }

  //  N8 , \field Rated Low Speed Air Flow Rate
  d = modelObject.getRatedLowSpeedAirFlowRate();
  if( d )
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::RatedLowSpeedAirFlowRate,*d);
  }
  else
  {
    idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::RatedLowSpeedAirFlowRate,"Autosize");
  }

  //  A10, \field Low Speed Total Cooling Capacity Function of Temperature Curve Name
  cq = modelObject.getLowSpeedTotalCoolingCapacityFunctionOfTemperatureCurve();
  translateAndMapModelObject(cq);
  idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::LowSpeedTotalCoolingCapacityFunctionofTemperatureCurveName,
                      cq.name().get());

  //  A11, \field Low Speed Energy Input Ratio Function of Temperature Curve Name
  cq = modelObject.getLowSpeedEnergyInputRatioFunctionOfTemperatureCurve();
  translateAndMapModelObject(cq);
  idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::LowSpeedEnergyInputRatioFunctionofTemperatureCurveName,
                      cq.name().get());

  //  A12, \field Condenser Air Inlet Node Name
  s=modelObject.getCondenserAirInletNodeName();
  if(s)
  {
    idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::CondenserAirInletNodeName,*s);
  }

  //  A13, \field Condenser Type
  idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::CondenserType,modelObject.getCondenserType());

  //   N9, \field High Speed Evaporative Condenser Effectiveness
  d=modelObject.getHighSpeedEvaporativeCondenserEffectiveness();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedEvaporativeCondenserEffectiveness,*d);
  }

  //  N10, \field High Speed Evaporative Condenser Air Flow Rate
  d=modelObject.getHighSpeedEvaporativeCondenserAirFlowRate();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedEvaporativeCondenserAirFlowRate,*d);
  }

  //  N11, \field High Speed Evaporative Condenser Pump Rated Power Consumption
  d=modelObject.getHighSpeedEvaporativeCondenserPumpRatedPowerConsumption();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedEvaporativeCondenserPumpRatedPowerConsumption,*d);
  }

  //  N12, \field Low Speed Evaporative Condenser Effectiveness
  d=modelObject.getLowSpeedEvaporativeCondenserEffectiveness();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedEvaporativeCondenserEffectiveness,*d);
  }

  //  N13, \field Low Speed Evaporative Condenser Air Flow Rate
  d=modelObject.getLowSpeedEvaporativeCondenserAirFlowRate();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedEvaporativeCondenserAirFlowRate,*d);
  }

  //  N14, \field Low Speed Evaporative Condenser Pump Rated Power Consumption
  d=modelObject.getLowSpeedEvaporativeCondenserPumpRatedPowerConsumption();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedEvaporativeCondenserPumpRatedPowerConsumption,*d);
  }

  //TODO
  //  A14, \field Supply Water Storage Tank Name
  //getSupplyWaterStorageTankName

  //TODO
  //  A15, \field Condensate Collection Water Storage Tank Name
  //getCondensateCollectionWaterStorageTankName

  //  N15, \field Basin Heater Capacity
  d=modelObject.getBasinHeaterCapacity();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::BasinHeaterCapacity,*d);
  }

  //  N16, \field Basin Heater Setpoint Temperature
  d=modelObject.getBasinHeaterSetpointTemperature();
  if(d)
  {
    idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::BasinHeaterSetpointTemperature,*d);
  }

  //  A16; \field Basin Heater Operating Schedule Name
  OptionalSchedule os = modelObject.getBasinHeaterOperatingSchedule();
  if( os )
  {
    translateAndMapModelObject(*os);
    idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::BasinHeaterOperatingScheduleName,
                        os->name().get() );
  }

  return idfObject;
}
Example #27
0
 auto num_appointments() {
     return schedule.get_appointments().size();
 }
Example #28
0
s32 main(s32, char**){
	SDL_Init(SDL_INIT_EVERYTHING);
	auto sdlWindow = SDL_CreateWindow("FMOD Test",
		SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
		200, 200, SDL_WINDOW_OPENGL);
	(void)sdlWindow;

	InitFmod();

	amaj.Major();
	amin.Minor();
	penta.Penta();
	scale.Idk();

	std::srand(1000);

	auto chord = [&](auto& scale, s32 root, f32 when, f32 vol = 3.f){
		constexpr f32 length = 3.5f;

		auto snd = root+1 + (rand()%2);
		auto trd = root+3 + (rand()%3);

		chords.Add(scale.Get(root)*0.5f, when+.00f, length, vol * 0.7f);
		// chords.Add(scale.Get(snd)*0.5f, when+.00f, length, vol * 0.7f);

		chords.Add(scale.Get(root), when+.02f, length, vol);
		chords.Add(scale.Get(snd), when+.04f, length, vol);
		chords.Add(scale.Get(trd), when+.06f, length, vol);
	};

	sched.time = -8.0; // Lead in
	sched.repeat = 7.5;

	chords.time = sched.time;
	chords.repeat = 8.0;
	perc.repeat = 8.0;

	// Kick
	for(f32 x = 0.0; x < perc.repeat; x+= 1.0){
		// perc.Add(50.0, x, 0.05, 10.0);
		perc.Add(30.0, x, 0.2, 4.0);
	}

	for(f32 x = 1.0; x < perc.repeat; x+= 2.0){
		perc.Add(1500.0, x, 0.01, 1.0);
	}
	// perc.Add(1500.0, 7.75, 0.01, 1.0);
	// perc.Add(1500.0, 6.75, 0.01, 1.0);

	auto gen = [&](){
		sched.notes.clear();

		// Bass
		for(f32 x = 0.0; x < sched.repeat;){
			x += std::pow(2.0, (rand()%2));
			auto freq = penta.Get(rand()%(penta.degrees.size()*1)) * std::pow(2.0, -2.0);
			// sched.Add(freq, x, 2.0/3.0, 6.0);
			sched.Add(freq, x, 1.0, 2.0);
			// sched.Add(freq*0.5, x+0.75, 2.0/3.0, 6.0);
		}

		// Mid
		for(f32 x = 0.0; x < sched.repeat;){
			x += std::pow(2.0, (rand()%4)-2.0);
			auto freq = penta.Get(rand()%(penta.degrees.size()*2));
			auto length = 0.3 * std::pow(2.0, (rand()%3)-1.0);
			auto vol = ((rand()%1000) - 500)/500.f + 2.0;
			sched.Add(freq, x, length, vol);
		}

		// Treb
		for(f32 x = 0.0; x < sched.repeat;){
			x += std::pow(2.0, (rand()%5)-2.0);
			auto freq = penta.Get(rand()%(penta.degrees.size()*3)) * std::pow(2.0, 1.0);
			auto length = 0.1 * std::pow(2.0, (rand()%4)-2.0);
			auto vol = ((rand()%1000) - 500)/1000.f + 1.0;

			sched.Add(freq, x, length, vol);
			sched.Add(freq, x+1.0/4.0, length, vol);
			// sched.Add(freq, x+2.0/4.0, length);
		}
	};

	auto genchords = [&]() {
		chords.notes.clear();

		for(f32 x = 0.f; x < chords.repeat;) {
			chord(penta, rand()%(penta.degrees.size()*5/4) - penta.degrees.size(), x, 0.8f + (rand()%100 - 50)/300.f);
			// x += std::pow(2.0, (rand()%2)+2) + (rand()%2)*0.5f;
			x += (rand()%5)/2.f + 2.f;
		}
	};

	gen();
	genchords();

	bool running = true;

	while(running){
		SDL_Event e;
		while(SDL_PollEvent(&e)){
			if (e.type == SDL_QUIT
			|| (e.type == SDL_WINDOWEVENT && e.window.event == SDL_WINDOWEVENT_CLOSE)
			|| (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)){
				running = false;
			}
		}

		fmodSystem->update();

		if(sched.numRepeats >= 4){
			gen();
			sched.numRepeats = 0;
		}

		if(chords.numRepeats >= 2){
			genchords();
			chords.numRepeats = 0;
		}

		SDL_Delay(10);
	}

	fmodSystem->release();
	SDL_Quit();

	return 0;
}
boost::optional<IdfObject> ForwardTranslator::translatePlantEquipmentOperationSchemes( PlantLoop & plantLoop )
{
  IdfObject operationSchemes(IddObjectType::PlantEquipmentOperationSchemes);
  m_idfObjects.push_back(operationSchemes);

  operationSchemes.setName(plantLoop.name().get() + " Operation Schemes");

  // Lambda does what the name suggests, create setpoint operation schemes.
  // This is for any component that has a setpoint manager on its outlet node
  auto createSetpointOperationScheme = [&](PlantLoop & plantLoop) {
    const auto & t_setpointComponents = setpointComponents(plantLoop);
    if( ! t_setpointComponents.empty() ) {
      Schedule alwaysOn = plantLoop.model().alwaysOnDiscreteSchedule();

      IdfObject setpointOperation(IddObjectType::PlantEquipmentOperation_ComponentSetpoint);
      setpointOperation.setName(plantLoop.name().get() + " Setpoint Operation Scheme");
      m_idfObjects.push_back(setpointOperation);
      setpointOperation.clearExtensibleGroups();

      IdfExtensibleGroup eg = operationSchemes.pushExtensibleGroup();
      eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeObjectType,setpointOperation.iddObject().name());
      eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeName,setpointOperation.name().get());
      eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeScheduleName,alwaysOn.name().get());

      for( auto setpointComponent : t_setpointComponents )
      {
        boost::optional<IdfObject> _idfObject = translateAndMapModelObject(setpointComponent);
        OS_ASSERT(_idfObject);

        IdfExtensibleGroup eg = setpointOperation.pushExtensibleGroup();
        eg.setString(PlantEquipmentOperation_ComponentSetpointExtensibleFields::EquipmentObjectType,_idfObject->iddObject().name());
        eg.setString(PlantEquipmentOperation_ComponentSetpointExtensibleFields::EquipmentName,_idfObject->name().get());
        if( const auto & t_inletNode = inletNode(plantLoop,setpointComponent) ) {
          eg.setString(PlantEquipmentOperation_ComponentSetpointExtensibleFields::DemandCalculationNodeName,t_inletNode->name().get());
        }
        if( const auto & t_outletNode = outletNode(plantLoop,setpointComponent) ) {
          eg.setString(PlantEquipmentOperation_ComponentSetpointExtensibleFields::SetpointNodeName,t_outletNode->name().get());
        }
        if( auto value = flowrate(setpointComponent) ) {
          eg.setDouble(PlantEquipmentOperation_ComponentSetpointExtensibleFields::ComponentFlowRate,value.get());
        } else {
          eg.setString(PlantEquipmentOperation_ComponentSetpointExtensibleFields::ComponentFlowRate,"Autosize");
        }
        auto t_componentType = componentType(setpointComponent);
        switch(t_componentType)
        {
          case ComponentType::HEATING :
            eg.setString(PlantEquipmentOperation_ComponentSetpointExtensibleFields::OperationType,"Heating");
            break;
          case ComponentType::COOLING :
            eg.setString(PlantEquipmentOperation_ComponentSetpointExtensibleFields::OperationType,"Cooling");
            break;
          default :
            eg.setString(PlantEquipmentOperation_ComponentSetpointExtensibleFields::OperationType,"Dual");
            break;
        }
      }
    }
  };

  Schedule alwaysOn = plantLoop.model().alwaysOnDiscreteSchedule();
  bool applyDefault = true;

  // If any operation schemes are defined in the model then don't apply default operation schemes

  if( auto coolingLoadScheme = plantLoop.plantEquipmentOperationCoolingLoad() ) {
    auto _scheme = translateAndMapModelObject(coolingLoadScheme.get());
    OS_ASSERT(_scheme);
    auto eg = operationSchemes.pushExtensibleGroup();
    eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeObjectType,_scheme->iddObject().name());
    eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeName,_scheme->name().get());
    eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeScheduleName,alwaysOn.name().get());

    applyDefault = false;
  } 

  if( auto heatingLoadScheme = plantLoop.plantEquipmentOperationHeatingLoad() ) {
    auto _scheme = translateAndMapModelObject(heatingLoadScheme.get());
    OS_ASSERT(_scheme);
    auto eg = operationSchemes.pushExtensibleGroup();
    eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeObjectType,_scheme->iddObject().name());
    eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeName,_scheme->name().get());
    eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeScheduleName,alwaysOn.name().get());

    applyDefault = false;
  }

  if( auto primaryScheme = plantLoop.primaryPlantEquipmentOperationScheme() ) {
    auto _scheme = translateAndMapModelObject(primaryScheme.get());
    OS_ASSERT(_scheme);
    auto eg = operationSchemes.pushExtensibleGroup();
    eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeObjectType,_scheme->iddObject().name());
    eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeName,_scheme->name().get());
    eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeScheduleName,alwaysOn.name().get());

    createSetpointOperationScheme(plantLoop);
    applyDefault = false;
  }

  if( applyDefault ) {
    // If we get here then there must not be any operation schemes defined in the model 
    // and we should go ahead and create default schemes.
    const auto & t_heatingComponents = heatingComponents( plantLoop );
    if( ! t_heatingComponents.empty() ) {
      IdfObject heatingOperation(IddObjectType::PlantEquipmentOperation_HeatingLoad);
      heatingOperation.setName(plantLoop.name().get() + " Heating Operation Scheme");
      m_idfObjects.push_back(heatingOperation);
      heatingOperation.clearExtensibleGroups();

      IdfObject plantEquipmentList(IddObjectType::PlantEquipmentList);
      plantEquipmentList.setName(plantLoop.name().get() + " Heating Equipment List");
      plantEquipmentList.clearExtensibleGroups();
      m_idfObjects.push_back(plantEquipmentList);

      IdfExtensibleGroup eg = heatingOperation.pushExtensibleGroup();
      eg.setDouble(PlantEquipmentOperation_HeatingLoadExtensibleFields::LoadRangeLowerLimit,0.0);
      eg.setDouble(PlantEquipmentOperation_HeatingLoadExtensibleFields::LoadRangeUpperLimit,1E9);
      eg.setString(PlantEquipmentOperation_HeatingLoadExtensibleFields::RangeEquipmentListName,plantEquipmentList.name().get());

      eg = operationSchemes.pushExtensibleGroup();
      eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeObjectType,heatingOperation.iddObject().name());
      eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeName,heatingOperation.name().get());
      eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeScheduleName,alwaysOn.name().get());

      for( auto heatingComponent : t_heatingComponents ) {
        if( const auto & idfObject = translateAndMapModelObject(heatingComponent) ) {
          IdfExtensibleGroup eg = plantEquipmentList.pushExtensibleGroup();
          eg.setString(PlantEquipmentListExtensibleFields::EquipmentObjectType,idfObject->iddObject().name());
          eg.setString(PlantEquipmentListExtensibleFields::EquipmentName,idfObject->name().get());
        }
      }
    }

    const auto & t_coolingComponents = coolingComponents( plantLoop );
    if( ! t_coolingComponents.empty() ) {
      IdfObject coolingOperation(IddObjectType::PlantEquipmentOperation_CoolingLoad);
      coolingOperation.setName(plantLoop.name().get() + " Cooling Operation Scheme");
      m_idfObjects.push_back(coolingOperation);
      coolingOperation.clearExtensibleGroups();

      IdfObject plantEquipmentList(IddObjectType::PlantEquipmentList);
      plantEquipmentList.setName(plantLoop.name().get() + " Cooling Equipment List");
      plantEquipmentList.clearExtensibleGroups();
      m_idfObjects.push_back(plantEquipmentList);

      IdfExtensibleGroup eg = coolingOperation.pushExtensibleGroup();
      eg.setDouble(PlantEquipmentOperation_CoolingLoadExtensibleFields::LoadRangeLowerLimit,0.0);
      eg.setDouble(PlantEquipmentOperation_CoolingLoadExtensibleFields::LoadRangeUpperLimit,1E9);
      eg.setString(PlantEquipmentOperation_CoolingLoadExtensibleFields::RangeEquipmentListName,plantEquipmentList.name().get());

      eg = operationSchemes.pushExtensibleGroup();
      eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeObjectType,coolingOperation.iddObject().name());
      eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeName,coolingOperation.name().get());
      eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeScheduleName,alwaysOn.name().get());

      for( auto coolingComponent : t_coolingComponents ) {
        if( const auto & idfObject = translateAndMapModelObject(coolingComponent) ) {
          IdfExtensibleGroup eg = plantEquipmentList.pushExtensibleGroup();
          eg.setString(PlantEquipmentListExtensibleFields::EquipmentObjectType,idfObject->iddObject().name());
          eg.setString(PlantEquipmentListExtensibleFields::EquipmentName,idfObject->name().get());
        }
      }
    }

    const auto & t_uncontrolledComponents = uncontrolledComponents( plantLoop );
    if( ! t_uncontrolledComponents.empty() ) {

      IdfObject uncontrolledOperation(IddObjectType::PlantEquipmentOperation_Uncontrolled);
      uncontrolledOperation.setName(plantLoop.name().get() + " Uncontrolled Operation Scheme");
      m_idfObjects.push_back(uncontrolledOperation);
      uncontrolledOperation.clearExtensibleGroups();

      IdfObject plantEquipmentList(IddObjectType::PlantEquipmentList);
      plantEquipmentList.setName(plantLoop.name().get() + " Uncontrolled Equipment List");
      plantEquipmentList.clearExtensibleGroups();
      m_idfObjects.push_back(plantEquipmentList);

      uncontrolledOperation.setString(PlantEquipmentOperation_UncontrolledFields::EquipmentListName,plantEquipmentList.name().get());

      auto eg = operationSchemes.pushExtensibleGroup();
      eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeObjectType,uncontrolledOperation.iddObject().name());
      eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeName,uncontrolledOperation.name().get());
      eg.setString(PlantEquipmentOperationSchemesExtensibleFields::ControlSchemeScheduleName,alwaysOn.name().get());

      for( auto uncontrolledComponent : t_uncontrolledComponents ) {
        if( const auto & idfObject = translateAndMapModelObject(uncontrolledComponent) ) {
          IdfExtensibleGroup eg = plantEquipmentList.pushExtensibleGroup();
          eg.setString(PlantEquipmentListExtensibleFields::EquipmentObjectType,idfObject->iddObject().name());
          eg.setString(PlantEquipmentListExtensibleFields::EquipmentName,idfObject->name().get());
        }
      }
    }

    createSetpointOperationScheme(plantLoop);
  }

  return operationSchemes;
}
Example #30
0
void CPISwapTest::consistency() {

    // check inflation leg vs calculation directly from inflation TS
    CommonVars common;

    // ZeroInflationSwap aka CPISwap

    CPISwap::Type type = CPISwap::Payer;
    Real nominal = 1000000.0;
    bool subtractInflationNominal = true;
    // float+spread leg
    Spread spread = 0.0;
    DayCounter floatDayCount = Actual365Fixed();
    BusinessDayConvention floatPaymentConvention = ModifiedFollowing;
    Natural fixingDays = 0;
    ext::shared_ptr<IborIndex> floatIndex(new GBPLibor(Period(6,Months),
                                                         common.nominalTS));

    // fixed x inflation leg
    Rate fixedRate = 0.1;//1% would be 0.01
    Real baseCPI = 206.1; // would be 206.13871 if we were interpolating
    DayCounter fixedDayCount = Actual365Fixed();
    BusinessDayConvention fixedPaymentConvention = ModifiedFollowing;
    Calendar fixedPaymentCalendar = UnitedKingdom();
    ext::shared_ptr<ZeroInflationIndex> fixedIndex = common.ii;
    Period contractObservationLag = common.contractObservationLag;
    CPI::InterpolationType observationInterpolation = common.contractObservationInterpolation;

    // set the schedules
    Date startDate(2, October, 2007);
    Date endDate(2, October, 2052);
    Schedule floatSchedule = MakeSchedule().from(startDate).to(endDate)
    .withTenor(Period(6,Months))
    .withCalendar(UnitedKingdom())
    .withConvention(floatPaymentConvention)
    .backwards()
    ;
    Schedule fixedSchedule = MakeSchedule().from(startDate).to(endDate)
    .withTenor(Period(6,Months))
    .withCalendar(UnitedKingdom())
    .withConvention(Unadjusted)
    .backwards()
    ;


    CPISwap zisV(type, nominal, subtractInflationNominal,
                 spread, floatDayCount, floatSchedule,
                 floatPaymentConvention, fixingDays, floatIndex,
                 fixedRate, baseCPI, fixedDayCount, fixedSchedule,
                 fixedPaymentConvention, contractObservationLag,
                 fixedIndex, observationInterpolation);
    Date asofDate = Settings::instance().evaluationDate();

    Real floatFix[] = {0.06255,0.05975,0.0637,0.018425,0.0073438,-1,-1};
    Real cpiFix[] = {211.4,217.2,211.4,213.4,-2,-2};
    for(Size i=0;i<floatSchedule.size(); i++){
        if (floatSchedule[i] < common.evaluationDate) {
            floatIndex->addFixing(floatSchedule[i], floatFix[i],true);//true=overwrite
        }

        ext::shared_ptr<CPICoupon>
        zic = ext::dynamic_pointer_cast<CPICoupon>(zisV.cpiLeg()[i]);
        if (zic) {
            if (zic->fixingDate() < (common.evaluationDate - Period(1,Months))) {
                fixedIndex->addFixing(zic->fixingDate(), cpiFix[i],true);
            }
        }
    }


    // simple structure so simple pricing engine - most work done by index
    ext::shared_ptr<DiscountingSwapEngine>
        dse(new DiscountingSwapEngine(common.nominalTS));

    zisV.setPricingEngine(dse);

    // get float+spread & fixed*inflation leg prices separately
    Real testInfLegNPV = 0.0;
    for(Size i=0;i<zisV.leg(0).size(); i++){

        Date zicPayDate = (zisV.leg(0))[i]->date();
        if(zicPayDate > asofDate) {
            testInfLegNPV += (zisV.leg(0))[i]->amount()*common.nominalTS->discount(zicPayDate);
        }

        ext::shared_ptr<CPICoupon>
            zicV = ext::dynamic_pointer_cast<CPICoupon>(zisV.cpiLeg()[i]);
        if (zicV) {
            Real diff = fabs( zicV->rate() - (fixedRate*(zicV->indexFixing()/baseCPI)) );
            QL_REQUIRE(diff<1e-8,"failed "<<i<<"th coupon reconstruction as "
                       << (fixedRate*(zicV->indexFixing()/baseCPI)) << " vs rate = "
                       <<zicV->rate() << ", with difference: " << diff);
        }
    }

    Real error = fabs(testInfLegNPV - zisV.legNPV(0));
    QL_REQUIRE(error<1e-5,
               "failed manual inf leg NPV calc vs pricing engine: " <<
               testInfLegNPV << " vs " << zisV.legNPV(0));

    Real diff = fabs(1-zisV.NPV()/4191660.0);
    #ifndef QL_USE_INDEXED_COUPON
    Real max_diff = 1e-5;
    #else
    Real max_diff = 3e-5;
    #endif
    QL_REQUIRE(diff<max_diff,
               "failed stored consistency value test, ratio = " << diff);

    // remove circular refernce
    common.hcpi.linkTo(ext::shared_ptr<ZeroInflationTermStructure>());
}