/** Calculates the present value of a bond from the clean price and a curve bundle. */
public class InflationBondPresentValueFromCleanPriceFunction
    extends InflationBondFromCleanPriceAndCurvesFunction {
  /** The present value calculator */
  private static final BondCapitalIndexedSecurityDiscountingMethod CALCULATOR =
      BondCapitalIndexedSecurityDiscountingMethod.getInstance();

  private static final PresentValueDiscountingInflationCalculator PVIC =
      PresentValueDiscountingInflationCalculator.getInstance();

  /** Sets the value requirement name to {@link ValueRequirementNames#PRESENT_VALUE}. */
  public InflationBondPresentValueFromCleanPriceFunction() {
    super(PRESENT_VALUE);
  }

  @Override
  protected Set<ComputedValue> getResult(
      final FunctionInputs inputs,
      final BondCapitalIndexedTransaction<?> bond,
      final InflationIssuerProviderInterface provider,
      final double cleanPrice,
      final ValueSpecification spec) {
    final String expectedCurrency = spec.getProperty(CURRENCY);
    final MultipleCurrencyAmount pvBond =
        CALCULATOR.presentValueFromCleanRealPrice(bond.getBondTransaction(), provider, cleanPrice);
    final MultipleCurrencyAmount pvSettlement =
        bond.getBondTransaction()
            .getSettlement()
            .accept(PVIC, provider.getInflationProvider())
            .multipliedBy(
                bond.getQuantity()
                    * bond.getBondTransaction().getCoupon().getNthPayment(0).getNotional());
    final MultipleCurrencyAmount pv = pvBond.plus(pvSettlement);
    if (pv.size() != 1
        || !(expectedCurrency.equals(pv.getCurrencyAmounts()[0].getCurrency().getCode()))) {
      throw new OpenGammaRuntimeException("Expecting a single result in " + expectedCurrency);
    }
    return Collections.singleton(new ComputedValue(spec, pv.getCurrencyAmounts()[0].getAmount()));
  }

  @Override
  protected ValueProperties.Builder getResultProperties(final ComputationTarget target) {
    final String currency =
        FinancialSecurityUtils.getCurrency(target.getTrade().getSecurity()).getCode();
    return super.getResultProperties(target).with(CURRENCY, currency);
  }
}
/** Build of inflation curve in several blocks with relevant Jacobian matrice. */
public class InflationBuildingCurveSimpleTestEUR {

  private static final Interpolator1D INTERPOLATOR_LINEAR =
      CombinedInterpolatorExtrapolatorFactory.getInterpolator(
          Interpolator1DFactory.LOG_LINEAR,
          Interpolator1DFactory.FLAT_EXTRAPOLATOR,
          Interpolator1DFactory.FLAT_EXTRAPOLATOR);

  private static final LastTimeCalculator MATURITY_CALCULATOR = LastTimeCalculator.getInstance();
  private static final double TOLERANCE_ROOT = 1.0E-10;
  private static final int STEP_MAX = 100;

  private static final Currency EUR = Currency.EUR;

  private static final double NOTIONAL = 1.0;

  private static final GeneratorSwapFixedInflationZeroCoupon GENERATOR_INFLATION_SWAP =
      GeneratorSwapFixedInflationMaster.getInstance().getGenerator("EURHICP");
  private static final IndexPrice EUR_HICP = GENERATOR_INFLATION_SWAP.getIndexPrice();

  private static final ZonedDateTime NOW = DateUtils.getUTCDate(2012, 9, 28);

  private static final ZonedDateTimeDoubleTimeSeries TS_PRICE_INDEX_USD_WITH_TODAY =
      ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
          new ZonedDateTime[] {
            DateUtils.getUTCDate(2011, 9, 27), DateUtils.getUTCDate(2011, 9, 28)
          },
          new double[] {200, 200});
  private static final ZonedDateTimeDoubleTimeSeries TS_PRICE_INDEX_USD_WITHOUT_TODAY =
      ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
          new ZonedDateTime[] {DateUtils.getUTCDate(2011, 9, 27)}, new double[] {100});

  @SuppressWarnings("rawtypes")
  private static final DoubleTimeSeries[] TS_FIXED_PRICE_INDEX_USD_WITH_TODAY =
      new DoubleTimeSeries[] {TS_PRICE_INDEX_USD_WITH_TODAY};

  @SuppressWarnings("rawtypes")
  private static final DoubleTimeSeries[] TS_FIXED_PRICE_INDEX_USD_WITHOUT_TODAY =
      new DoubleTimeSeries[] {TS_PRICE_INDEX_USD_WITHOUT_TODAY};

  private static final String CURVE_NAME_HICP_EUR = "EUR HICP";

  /** Market values for the HICP EUR curve */
  public static final double[] HICP_EUR_MARKET_QUOTES =
      new double[] {
        0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200,
        0.0200, 0.0200, 0.0200, 0.0200
      };

  /** Generators for the HICP EUR curve */
  private static final GeneratorInstrument<? extends GeneratorAttribute>[] HICP_EUR_GENERATORS =
      new GeneratorInstrument<?>[] {
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP
      };
  /** Tenors for the HICP EUR curve */
  private static final Period[] HICP_EUR_TENOR =
      new Period[] {
        Period.ofYears(1),
        Period.ofYears(2),
        Period.ofYears(3),
        Period.ofYears(4),
        Period.ofYears(5),
        Period.ofYears(6),
        Period.ofYears(7),
        Period.ofYears(8),
        Period.ofYears(9),
        Period.ofYears(10),
        Period.ofYears(12),
        Period.ofYears(15),
        Period.ofYears(20),
        Period.ofYears(25),
        Period.ofYears(30)
      };

  private static final GeneratorAttributeIR[] HICP_EUR_ATTR =
      new GeneratorAttributeIR[HICP_EUR_TENOR.length];

  static {
    for (int loopins = 0; loopins < HICP_EUR_TENOR.length; loopins++) {
      HICP_EUR_ATTR[loopins] = new GeneratorAttributeIR(HICP_EUR_TENOR[loopins]);
    }
  }

  /** Standard EUR HICP curve instrument definitions */
  private static final InstrumentDefinition<?>[] DEFINITIONS_HICP_EUR;

  /** Units of curves */
  private static final int[] NB_UNITS = new int[] {1};

  private static final int NB_BLOCKS = NB_UNITS.length;
  private static final InstrumentDefinition<?>[][][][] DEFINITIONS_UNITS =
      new InstrumentDefinition<?>[NB_BLOCKS][][][];
  private static final GeneratorPriceIndexCurve[][][] GENERATORS_UNITS =
      new GeneratorPriceIndexCurve[NB_BLOCKS][][];
  private static final String[][][] NAMES_UNITS = new String[NB_BLOCKS][][];

  private static final MulticurveProviderDiscount eurMulticurveProviderDiscount =
      MulticurveProviderDiscountDataSets.createMulticurveEurUsd().copy();
  private static final InflationProviderDiscount KNOWN_DATA =
      new InflationProviderDiscount(eurMulticurveProviderDiscount);

  private static final LinkedHashMap<String, IndexPrice[]> EUR_HICP_MAP = new LinkedHashMap<>();

  static {
    DEFINITIONS_HICP_EUR =
        getDefinitions(HICP_EUR_MARKET_QUOTES, HICP_EUR_GENERATORS, HICP_EUR_ATTR);

    for (int loopblock = 0; loopblock < NB_BLOCKS; loopblock++) {
      DEFINITIONS_UNITS[loopblock] = new InstrumentDefinition<?>[NB_UNITS[loopblock]][][];
      GENERATORS_UNITS[loopblock] = new GeneratorPriceIndexCurve[NB_UNITS[loopblock]][];
      NAMES_UNITS[loopblock] = new String[NB_UNITS[loopblock]][];
    }
    DEFINITIONS_UNITS[0][0] = new InstrumentDefinition<?>[][] {DEFINITIONS_HICP_EUR};

    final GeneratorPriceIndexCurve genIntLin =
        new GeneratorPriceIndexCurveInterpolated(MATURITY_CALCULATOR, INTERPOLATOR_LINEAR);
    GENERATORS_UNITS[0][0] = new GeneratorPriceIndexCurve[] {genIntLin};

    NAMES_UNITS[0][0] = new String[] {CURVE_NAME_HICP_EUR};

    EUR_HICP_MAP.put(CURVE_NAME_HICP_EUR, new IndexPrice[] {EUR_HICP});
  }

  private static final String NOT_USED = "Not used";
  private static final String[] NOT_USED_2 = {NOT_USED, NOT_USED};

  public static InstrumentDefinition<?>[] getDefinitions(
      final double[] marketQuotes,
      final GeneratorInstrument[] generators,
      final GeneratorAttribute[] attribute) {
    final InstrumentDefinition<?>[] definitions = new InstrumentDefinition<?>[marketQuotes.length];
    for (int loopmv = 0; loopmv < marketQuotes.length; loopmv++) {
      definitions[loopmv] =
          generators[loopmv].generateInstrument(
              NOW, marketQuotes[loopmv], NOTIONAL, attribute[loopmv]);
    }
    return definitions;
  }

  private static List<Pair<InflationProviderDiscount, CurveBuildingBlockBundle>>
      CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK =
          new ArrayList<Pair<InflationProviderDiscount, CurveBuildingBlockBundle>>();

  // Calculator
  private static final PresentValueDiscountingInflationCalculator PVIC =
      PresentValueDiscountingInflationCalculator.getInstance();
  private static final ParSpreadInflationMarketQuoteDiscountingCalculator PSIMQC =
      ParSpreadInflationMarketQuoteDiscountingCalculator.getInstance();
  private static final ParSpreadInflationMarketQuoteCurveSensitivityDiscountingCalculator PSIMQCSC =
      ParSpreadInflationMarketQuoteCurveSensitivityDiscountingCalculator.getInstance();

  private static final InflationDiscountBuildingRepository CURVE_BUILDING_REPOSITORY =
      new InflationDiscountBuildingRepository(TOLERANCE_ROOT, TOLERANCE_ROOT, STEP_MAX);

  private static final double TOLERANCE_CAL = 1.0E-9;

  @BeforeSuite
  static void initClass() {
    for (int loopblock = 0; loopblock < NB_BLOCKS; loopblock++) {
      CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.add(
          makeCurvesFromDefinitions(
              DEFINITIONS_UNITS[loopblock],
              GENERATORS_UNITS[loopblock],
              NAMES_UNITS[loopblock],
              KNOWN_DATA,
              PSIMQC,
              PSIMQCSC,
              false));
    }
  }

  @Test(enabled = false)
  public void performance() {
    long startTime, endTime;
    final int nbTest = 1000;

    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      makeCurvesFromDefinitions(
          DEFINITIONS_UNITS[0],
          GENERATORS_UNITS[0],
          NAMES_UNITS[0],
          KNOWN_DATA,
          PSIMQC,
          PSIMQCSC,
          false);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        "InflationBuildingCurveSimpleTestEUR - "
            + nbTest
            + " curve construction Price index EUR 1 units: "
            + (endTime - startTime)
            + " ms");
    // Performance note: curve construction Price index EUR 1 units: 27-Mar-13: On Dell Precision
    // T1850 3.5 GHz Quad-Core Intel Xeon: 2816 ms for 1000 sets.
  }

  @Test
  public void curveConstructionGeneratorOtherBlocks() {
    for (int loopblock = 0; loopblock < NB_BLOCKS; loopblock++) {
      curveConstructionTest(
          DEFINITIONS_UNITS[loopblock],
          CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(loopblock).getFirst(),
          false,
          loopblock);
    }
  }

  public void curveConstructionTest(
      final InstrumentDefinition<?>[][][] definitions,
      final InflationProviderDiscount curves,
      final boolean withToday,
      final int block) {
    final int nbBlocks = definitions.length;
    for (int loopblock = 0; loopblock < nbBlocks; loopblock++) {
      final InstrumentDerivative[][] instruments =
          convert(definitions[loopblock], loopblock, withToday);
      final double[][] pv = new double[instruments.length][];
      for (int loopcurve = 0; loopcurve < instruments.length; loopcurve++) {
        pv[loopcurve] = new double[instruments[loopcurve].length];
        for (int loopins = 0; loopins < instruments[loopcurve].length; loopins++) {
          pv[loopcurve][loopins] =
              curves
                  .getFxRates()
                  .convert(instruments[loopcurve][loopins].accept(PVIC, curves), EUR)
                  .getAmount();
          assertEquals(
              "Curve construction: block "
                  + block
                  + ", unit "
                  + loopblock
                  + " - instrument "
                  + loopins,
              0,
              pv[loopcurve][loopins],
              TOLERANCE_CAL);
        }
      }
    }
  }

  private static Pair<InflationProviderDiscount, CurveBuildingBlockBundle>
      makeCurvesFromDefinitions(
          final InstrumentDefinition<?>[][][] definitions,
          final GeneratorPriceIndexCurve[][] curveGenerators,
          final String[][] curveNames,
          final InflationProviderDiscount knownData,
          final InstrumentDerivativeVisitor<InflationProviderInterface, Double> calculator,
          final InstrumentDerivativeVisitor<InflationProviderInterface, InflationSensitivity>
              sensitivityCalculator,
          final boolean withToday) {
    final int nbUnits = curveGenerators.length;
    final double[][] parametersGuess = new double[nbUnits][];
    final GeneratorPriceIndexCurve[][] generatorFinal = new GeneratorPriceIndexCurve[nbUnits][];
    final InstrumentDerivative[][][] instruments = new InstrumentDerivative[nbUnits][][];
    for (int loopunit = 0; loopunit < nbUnits; loopunit++) {
      generatorFinal[loopunit] = new GeneratorPriceIndexCurve[curveGenerators[loopunit].length];
      int nbInsUnit = 0;
      for (int loopcurve = 0; loopcurve < curveGenerators[loopunit].length; loopcurve++) {
        nbInsUnit += definitions[loopunit][loopcurve].length;
      }
      parametersGuess[loopunit] = new double[nbInsUnit];
      int startCurve = 0; // First parameter index of the curve in the unit.
      instruments[loopunit] = convert(definitions[loopunit], loopunit, withToday);
      for (int loopcurve = 0; loopcurve < curveGenerators[loopunit].length; loopcurve++) {
        generatorFinal[loopunit][loopcurve] =
            curveGenerators[loopunit][loopcurve].finalGenerator(instruments[loopunit][loopcurve]);
        final double[] guessCurve =
            generatorFinal[loopunit][loopcurve].initialGuess(
                initialGuess(definitions[loopunit][loopcurve]));
        System.arraycopy(
            guessCurve,
            0,
            parametersGuess[loopunit],
            startCurve,
            instruments[loopunit][loopcurve].length);
        startCurve += instruments[loopunit][loopcurve].length;
      }
    }
    return CURVE_BUILDING_REPOSITORY.makeCurvesFromDerivatives(
        instruments,
        generatorFinal,
        curveNames,
        parametersGuess,
        knownData,
        EUR_HICP_MAP,
        calculator,
        sensitivityCalculator);
  }

  @SuppressWarnings("unchecked")
  private static InstrumentDerivative[][] convert(
      final InstrumentDefinition<?>[][] definitions, final int unit, final boolean withToday) {
    //    int nbDef = 0;
    //    for (final InstrumentDefinition<?>[] definition : definitions) {
    //      nbDef += definition.length;
    //    }
    final InstrumentDerivative[][] instruments = new InstrumentDerivative[definitions.length][];
    for (int loopcurve = 0; loopcurve < definitions.length; loopcurve++) {
      instruments[loopcurve] = new InstrumentDerivative[definitions[loopcurve].length];
      int loopins = 0;
      for (final InstrumentDefinition<?> instrument : definitions[loopcurve]) {
        InstrumentDerivative ird;
        if (instrument instanceof SwapFixedInflationZeroCouponDefinition) {
          /* ird = ((SwapFixedInflationZeroCouponDefinition) instrument).toDerivative(NOW, getTSSwapFixedInflation(withToday, unit), NOT_USED_2);*/
          final Annuity<? extends Payment> ird1 =
              ((SwapFixedInflationZeroCouponDefinition) instrument)
                  .getFirstLeg()
                  .toDerivative(NOW, NOT_USED_2);
          final Annuity<? extends Payment> ird2 =
              ((SwapFixedInflationZeroCouponDefinition) instrument)
                  .getSecondLeg()
                  .toDerivative(NOW, TS_PRICE_INDEX_USD_WITH_TODAY, NOT_USED_2);
          ird = new Swap<>(ird1, ird2);
        } else {
          ird = instrument.toDerivative(NOW, NOT_USED_2);
        }
        instruments[loopcurve][loopins++] = ird;
      }
    }
    return instruments;
  }

  @SuppressWarnings("rawtypes")
  private static DoubleTimeSeries[] getTSSwapFixedInflation(
      final Boolean withToday, final Integer unit) {
    switch (unit) {
      case 0:
        return withToday
            ? TS_FIXED_PRICE_INDEX_USD_WITH_TODAY
            : TS_FIXED_PRICE_INDEX_USD_WITHOUT_TODAY;
      case 1:
        return withToday
            ? TS_FIXED_PRICE_INDEX_USD_WITH_TODAY
            : TS_FIXED_PRICE_INDEX_USD_WITHOUT_TODAY;
      default:
        throw new IllegalArgumentException(unit.toString());
    }
  }

  private static double[] initialGuess(final InstrumentDefinition<?>[] definitions) {
    final double[] result = new double[definitions.length];
    int loopr = 0;
    for (final InstrumentDefinition<?> definition : definitions) {
      result[loopr++] = initialGuess(definition);
    }
    return result;
  }

  private static double initialGuess(final InstrumentDefinition<?> instrument) {
    if (instrument instanceof SwapFixedONDefinition) {
      return ((SwapFixedONDefinition) instrument).getFixedLeg().getNthPayment(0).getRate();
    }
    if (instrument instanceof SwapFixedIborDefinition) {
      return ((SwapFixedIborDefinition) instrument).getFixedLeg().getNthPayment(0).getRate();
    }
    if (instrument instanceof SwapFixedInflationZeroCouponDefinition) {

      if (((SwapFixedInflationZeroCouponDefinition) instrument).getFirstLeg().getNthPayment(0)
          instanceof CouponInflationZeroCouponMonthlyDefinition) {
        return ((CouponInflationZeroCouponMonthlyDefinition)
                ((SwapFixedInflationZeroCouponDefinition) instrument)
                    .getFirstLeg()
                    .getNthPayment(0))
            .getIndexStartValue();
      }
      if (((SwapFixedInflationZeroCouponDefinition) instrument).getFirstLeg().getNthPayment(0)
          instanceof CouponInflationZeroCouponInterpolationDefinition) {
        return ((CouponInflationZeroCouponInterpolationDefinition)
                ((SwapFixedInflationZeroCouponDefinition) instrument)
                    .getFirstLeg()
                    .getNthPayment(0))
            .getIndexStartValue();
      }
      return 100;
    }
    if (instrument instanceof ForwardRateAgreementDefinition) {
      return ((ForwardRateAgreementDefinition) instrument).getRate();
    }
    if (instrument instanceof CashDefinition) {
      return ((CashDefinition) instrument).getRate();
    }
    return 1;
  }
}
/**
 * Build of inflation curve and discount curve simultaneously in several blocks with relevant
 * Jacobian matrices.
 */
@Test(groups = TestGroup.UNIT)
public class InflationBuildingCurveWithDiscountTestUSD {

  private static final Interpolator1D INTERPOLATOR_LINEAR =
      CombinedInterpolatorExtrapolatorFactory.getInterpolator(
          Interpolator1DFactory.LOG_LINEAR,
          Interpolator1DFactory.FLAT_EXTRAPOLATOR,
          Interpolator1DFactory.FLAT_EXTRAPOLATOR);

  private static final LastTimeCalculator MATURITY_CALCULATOR = LastTimeCalculator.getInstance();
  private static final double TOLERANCE_ROOT = 1.0E-10;
  private static final int STEP_MAX = 100;

  private static final Currency USD = Currency.USD;
  private static final Calendar NYC = new MondayToFridayCalendar("NYC");
  private static final FXMatrix FX_MATRIX = new FXMatrix(USD);

  private static final double NOTIONAL = 1.0;

  private static final GeneratorSwapFixedON GENERATOR_OIS_USD =
      GeneratorSwapFixedONMaster.getInstance().getGenerator("USD1YFEDFUND", NYC);
  private static final IndexON INDEX_ON_USD = GENERATOR_OIS_USD.getIndex();
  private static final GeneratorDepositON GENERATOR_DEPOSIT_ON_USD =
      new GeneratorDepositON("USD Deposit ON", USD, NYC, INDEX_ON_USD.getDayCount());

  private static final GeneratorSwapFixedInflationZeroCoupon GENERATOR_INFALTION_SWAP =
      GeneratorSwapFixedInflationMaster.getInstance().getGenerator("USCPI");
  private static final IndexPrice US_CPI = GENERATOR_INFALTION_SWAP.getIndexPrice();

  private static final ZonedDateTime NOW = DateUtils.getUTCDate(2012, 9, 28);

  private static final ZonedDateTimeDoubleTimeSeries TS_PRICE_INDEX_USD_WITH_TODAY =
      ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
          new ZonedDateTime[] {
            DateUtils.getUTCDate(2011, 9, 27),
            DateUtils.getUTCDate(2011, 9, 28),
            DateUtils.getUTCDate(2012, 6, 30),
            DateUtils.getUTCDate(2012, 7, 31)
          },
          new double[] {200, 200, 200, 200});
  private static final String CURVE_NAME_DSC_USD = "USD Dsc";
  private static final String CURVE_NAME_CPI_USD = "USD CPI";

  /** Market values for the dsc USD curve */
  private static final double[] DSC_USD_MARKET_QUOTES =
      new double[] {
        0.0400, 0.0400, 0.0400, 0.0400, 0.0400, 0.0400, 0.0400, 0.0400, 0.0400, 0.0400, 0.0400,
        0.0400
      };
  /** Generators for the dsc USD curve */
  private static final GeneratorInstrument<? extends GeneratorAttribute>[] DSC_USD_GENERATORS =
      new GeneratorInstrument<?>[] {
        GENERATOR_DEPOSIT_ON_USD,
        GENERATOR_OIS_USD,
        GENERATOR_OIS_USD,
        GENERATOR_OIS_USD,
        GENERATOR_OIS_USD,
        GENERATOR_OIS_USD,
        GENERATOR_OIS_USD,
        GENERATOR_OIS_USD,
        GENERATOR_OIS_USD,
        GENERATOR_OIS_USD,
        GENERATOR_OIS_USD,
        GENERATOR_OIS_USD
      };
  /** Tenors for the dsc USD curve */
  private static final Period[] DSC_USD_TENOR =
      new Period[] {
        Period.ofDays(0),
        Period.ofMonths(1),
        Period.ofMonths(2),
        Period.ofMonths(3),
        Period.ofMonths(6),
        Period.ofMonths(9),
        Period.ofYears(1),
        Period.ofYears(2),
        Period.ofYears(3),
        Period.ofYears(4),
        Period.ofYears(5),
        Period.ofYears(10)
      };

  private static final GeneratorAttributeIR[] DSC_USD_ATTR =
      new GeneratorAttributeIR[DSC_USD_TENOR.length];

  static {
    for (int loopins = 0; loopins < DSC_USD_TENOR.length; loopins++) {
      DSC_USD_ATTR[loopins] = new GeneratorAttributeIR(DSC_USD_TENOR[loopins]);
    }
  }

  /** Market values for the CPI USD curve */
  public static final double[] CPI_USD_MARKET_QUOTES =
      new double[] {
        0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200,
        0.0200, 0.0200, 0.0200, 0.0200
      };
  /** Generators for the CPI USD curve */
  public static final GeneratorInstrument<? extends GeneratorAttribute>[] CPI_USD_GENERATORS =
      new GeneratorInstrument<?>[] {
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP,
        GENERATOR_INFALTION_SWAP
      };
  /** Tenors for the CPI USD curve */
  public static final Period[] CPI_USD_TENOR =
      new Period[] {
        Period.ofYears(1),
        Period.ofYears(2),
        Period.ofYears(3),
        Period.ofYears(4),
        Period.ofYears(5),
        Period.ofYears(6),
        Period.ofYears(7),
        Period.ofYears(8),
        Period.ofYears(9),
        Period.ofYears(10),
        Period.ofYears(12),
        Period.ofYears(15),
        Period.ofYears(20),
        Period.ofYears(25),
        Period.ofYears(30)
      };

  public static final GeneratorAttributeIR[] CPI_USD_ATTR =
      new GeneratorAttributeIR[CPI_USD_TENOR.length];

  static {
    for (int loopins = 0; loopins < CPI_USD_TENOR.length; loopins++) {
      CPI_USD_ATTR[loopins] = new GeneratorAttributeIR(CPI_USD_TENOR[loopins]);
    }
  }

  /** Standard USD discounting curve instrument definitions */
  private static final InstrumentDefinition<?>[] DEFINITIONS_DSC_USD;

  /** Standard USD CPI curve instrument definitions */
  public static final InstrumentDefinition<?>[] DEFINITIONS_CPI_USD;

  /** Units of curves */
  public static final int[] NB_UNITS = new int[] {2, 1};

  public static final int NB_BLOCKS = NB_UNITS.length;
  public static final InstrumentDefinition<?>[][][][] DEFINITIONS_UNITS =
      new InstrumentDefinition<?>[NB_BLOCKS][][][];
  public static final GeneratorCurve[][][] GENERATORS_UNITS = new GeneratorCurve[NB_BLOCKS][][];
  public static final String[][][] NAMES_UNITS = new String[NB_BLOCKS][][];

  private static final InflationProviderDiscount KNOWN_DATA =
      new InflationProviderDiscount(FX_MATRIX);

  private static final LinkedHashMap<String, Currency> DSC_MAP = new LinkedHashMap<>();
  private static final LinkedHashMap<String, IndexON[]> FWD_ON_MAP = new LinkedHashMap<>();
  public static final LinkedHashMap<String, IndexPrice[]> US_CPI_MAP = new LinkedHashMap<>();

  static {
    DEFINITIONS_DSC_USD = getDefinitions(DSC_USD_MARKET_QUOTES, DSC_USD_GENERATORS, DSC_USD_ATTR);
    DEFINITIONS_CPI_USD = getDefinitions(CPI_USD_MARKET_QUOTES, CPI_USD_GENERATORS, CPI_USD_ATTR);

    for (int loopblock = 0; loopblock < NB_BLOCKS; loopblock++) {
      DEFINITIONS_UNITS[loopblock] = new InstrumentDefinition<?>[NB_UNITS[loopblock]][][];
      GENERATORS_UNITS[loopblock] = new GeneratorCurve[NB_UNITS[loopblock]][];
      NAMES_UNITS[loopblock] = new String[NB_UNITS[loopblock]][];
    }

    DEFINITIONS_UNITS[0][0] = new InstrumentDefinition<?>[][] {DEFINITIONS_DSC_USD};
    DEFINITIONS_UNITS[0][1] = new InstrumentDefinition<?>[][] {DEFINITIONS_CPI_USD};
    DEFINITIONS_UNITS[1][0] =
        new InstrumentDefinition<?>[][] {DEFINITIONS_DSC_USD, DEFINITIONS_CPI_USD};

    final GeneratorYDCurve genIntLinDiscount =
        new GeneratorCurveYieldInterpolated(MATURITY_CALCULATOR, INTERPOLATOR_LINEAR);
    final GeneratorPriceIndexCurve genIntLinInflation =
        new GeneratorPriceIndexCurveInterpolated(MATURITY_CALCULATOR, INTERPOLATOR_LINEAR);

    GENERATORS_UNITS[0][0] = new GeneratorYDCurve[] {genIntLinDiscount};
    GENERATORS_UNITS[0][1] = new GeneratorPriceIndexCurve[] {genIntLinInflation};
    GENERATORS_UNITS[1][0] = new GeneratorCurve[] {genIntLinDiscount, genIntLinInflation};

    NAMES_UNITS[0][0] = new String[] {CURVE_NAME_DSC_USD};
    NAMES_UNITS[0][1] = new String[] {CURVE_NAME_CPI_USD};
    NAMES_UNITS[1][0] = new String[] {CURVE_NAME_DSC_USD, CURVE_NAME_CPI_USD};

    DSC_MAP.put(CURVE_NAME_DSC_USD, USD);
    FWD_ON_MAP.put(CURVE_NAME_DSC_USD, new IndexON[] {INDEX_ON_USD});
    US_CPI_MAP.put(CURVE_NAME_CPI_USD, new IndexPrice[] {US_CPI});
  }

  @SuppressWarnings({"unchecked", "rawtypes"})
  public static InstrumentDefinition<?>[] getDefinitions(
      final double[] marketQuotes,
      final GeneratorInstrument[] generators,
      final GeneratorAttribute[] attribute) {
    final InstrumentDefinition<?>[] definitions = new InstrumentDefinition<?>[marketQuotes.length];
    for (int loopmv = 0; loopmv < marketQuotes.length; loopmv++) {
      definitions[loopmv] =
          generators[loopmv].generateInstrument(
              NOW, marketQuotes[loopmv], NOTIONAL, attribute[loopmv]);
    }
    return definitions;
  }

  private static List<Pair<InflationProviderDiscount, CurveBuildingBlockBundle>>
      CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK = new ArrayList<>();

  // Calculator
  private static final PresentValueDiscountingInflationCalculator PVIC =
      PresentValueDiscountingInflationCalculator.getInstance();
  private static final PresentValueCurveSensitivityDiscountingInflationCalculator PVCSDIC =
      PresentValueCurveSensitivityDiscountingInflationCalculator.getInstance();
  private static final ParSpreadInflationMarketQuoteDiscountingCalculator PSIMQC =
      ParSpreadInflationMarketQuoteDiscountingCalculator.getInstance();
  private static final ParSpreadInflationMarketQuoteCurveSensitivityDiscountingCalculator PSIMQCSC =
      ParSpreadInflationMarketQuoteCurveSensitivityDiscountingCalculator.getInstance();

  private static final InflationDiscountBuildingRepositoryWithDiscount CURVE_BUILDING_REPOSITORY =
      new InflationDiscountBuildingRepositoryWithDiscount(TOLERANCE_ROOT, TOLERANCE_ROOT, STEP_MAX);

  private static final double TOLERANCE_CAL = 1.0E-9;

  @BeforeSuite
  static void initClass() {
    for (int loopblock = 0; loopblock < NB_BLOCKS; loopblock++) {
      CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.add(
          makeCurvesFromDefinitions(
              DEFINITIONS_UNITS[loopblock],
              GENERATORS_UNITS[loopblock],
              NAMES_UNITS[loopblock],
              KNOWN_DATA,
              PSIMQC,
              PSIMQCSC));
    }
  }

  public List<Pair<InflationProviderDiscount, CurveBuildingBlockBundle>> getCurvesWithBlock() {
    initClass();
    return CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK;
  }

  @Test(enabled = false)
  public void comparison1Unit2Units() {
    final InflationProviderDiscount[] units = new InflationProviderDiscount[2];
    final CurveBuildingBlockBundle[] bb = new CurveBuildingBlockBundle[2];
    final YieldAndDiscountCurve[] curveDsc = new YieldAndDiscountCurve[2];
    final PriceIndexCurve[] curveInflation = new PriceIndexCurve[2];

    for (int loopblock = 0; loopblock < 2; loopblock++) {
      units[loopblock] = CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(loopblock).getFirst();
      bb[loopblock] = CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(loopblock).getSecond();
      curveDsc[loopblock] = units[loopblock].getCurve(USD);
      curveInflation[loopblock] = units[loopblock].getCurve(US_CPI);
    }
    assertEquals(
        "Curve construction: 1 unit / 3 units ",
        curveDsc[0].getNumberOfParameters(),
        curveDsc[1].getNumberOfParameters());
    assertEquals(
        "Curve construction: 1 unit / 3 units ",
        curveInflation[0].getNumberOfParameters(),
        curveInflation[1].getNumberOfParameters());

    assertArrayEquals(
        "Curve construction: 1 unit / 3 units ",
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[0]).getCurve().getXData()),
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[1]).getCurve().getXData()),
        TOLERANCE_CAL);
    assertArrayEquals(
        "Curve construction: 1 unit / 3 units ",
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[0]).getCurve().getYData()),
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[1]).getCurve().getYData()),
        TOLERANCE_CAL);
    assertArrayEquals(
        "Curve construction: 1 unit / 3 units ",
        ArrayUtils.toPrimitive(((PriceIndexCurveSimple) curveInflation[0]).getCurve().getXData()),
        ArrayUtils.toPrimitive(((PriceIndexCurveSimple) curveInflation[1]).getCurve().getXData()),
        TOLERANCE_CAL);
    assertArrayEquals(
        "Curve construction: 1 unit / 3 units ",
        ArrayUtils.toPrimitive(((PriceIndexCurveSimple) curveInflation[0]).getCurve().getYData()),
        ArrayUtils.toPrimitive(((PriceIndexCurveSimple) curveInflation[1]).getCurve().getYData()),
        TOLERANCE_CAL);
  }

  @Test(enabled = false)
  public void performance() {
    long startTime, endTime;
    final int nbTest = 1000;

    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      makeCurvesFromDefinitions(
          DEFINITIONS_UNITS[0], GENERATORS_UNITS[0], NAMES_UNITS[0], KNOWN_DATA, PSIMQC, PSIMQCSC);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        "MulticurveBuildingDiscountingDiscountXCcyTest - "
            + nbTest
            + " curve construction / USD/EUR 3 units: "
            + (endTime - startTime)
            + " ms");
    // Performance note: curve construction Price index EUR and discount EUR 1 units: 27-Mar-13: On
    // Dell Precision T1850 3.5 GHz Quad-Core Intel Xeon: 5869 ms for 1000 sets.

    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      makeCurvesFromDefinitions(
          DEFINITIONS_UNITS[1], GENERATORS_UNITS[1], NAMES_UNITS[1], KNOWN_DATA, PSIMQC, PSIMQCSC);
    }
    endTime = System.currentTimeMillis();
    System.out.println(nbTest + " curve construction / 1 unit: " + (endTime - startTime) + " ms");
    // Performance note: curve construction Price index EUR and discount EUR 1 units: 27-Mar-13: On
    // Dell Precision T1850 3.5 GHz Quad-Core Intel Xeon: 9153 ms for 1000 sets.

  }

  @Test
  public void curveConstructionGeneratorOtherBlocks() {
    for (int loopblock = 0; loopblock < NB_BLOCKS; loopblock++) {
      curveConstructionTest(
          DEFINITIONS_UNITS[loopblock],
          CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(loopblock).getFirst(),
          loopblock);
    }
  }

  @Test(enabled = false)
  /** Analyzes the shape of the forward curve. */
  public void marketQuoteSensitivityAnalysis() {

    final InflationProviderDiscount multicurves7 =
        CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(1).getFirst();
    multicurves7.setAll(CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(0).getFirst());
    final CurveBuildingBlockBundle blocks7 =
        CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(1).getSecond();
    blocks7.addAll(CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(0).getSecond());
    final double spreadJPYEUR = 0.0010; // 10bps
    final double notional = 100000;
    final GeneratorAttributeIR swapAttribute = new GeneratorAttributeIR(Period.ofYears(4));
    final SwapFixedInflationZeroCouponDefinition swapDefinition =
        GENERATOR_INFALTION_SWAP.generateInstrument(NOW, spreadJPYEUR, notional, swapAttribute);
    final InstrumentDerivative swap =
        swapDefinition.toDerivative(
            NOW,
            new ZonedDateTimeDoubleTimeSeries[] {
              TS_PRICE_INDEX_USD_WITH_TODAY, TS_PRICE_INDEX_USD_WITH_TODAY
            });
    final ParameterSensitivityInflationParameterCalculator<ParameterInflationProviderInterface>
        PSC = new ParameterSensitivityInflationParameterCalculator<>(PVCSDIC);
    final MarketQuoteInflationSensitivityBlockCalculator<ParameterInflationProviderInterface> MQSC =
        new MarketQuoteInflationSensitivityBlockCalculator<>(PSC);
    @SuppressWarnings("unused")
    final MultipleCurrencyParameterSensitivity mqs =
        MQSC.fromInstrument(swap, multicurves7, blocks7);
  }

  private void curveConstructionTest(
      final InstrumentDefinition<?>[][][] definitions,
      final InflationProviderDiscount curves,
      final int block) {
    final int nbBlocks = definitions.length;
    for (int loopblock = 0; loopblock < nbBlocks; loopblock++) {
      final InstrumentDerivative[][] instruments = convert(definitions[loopblock]);
      final double[][] pv = new double[instruments.length][];
      for (int loopcurve = 0; loopcurve < instruments.length; loopcurve++) {
        pv[loopcurve] = new double[instruments[loopcurve].length];
        for (int loopins = 0; loopins < instruments[loopcurve].length; loopins++) {
          pv[loopcurve][loopins] =
              curves
                  .getFxRates()
                  .convert(instruments[loopcurve][loopins].accept(PVIC, curves), USD)
                  .getAmount();
          assertEquals(
              "Curve construction: block "
                  + block
                  + ", unit "
                  + loopblock
                  + " - instrument "
                  + loopins,
              0,
              pv[loopcurve][loopins],
              TOLERANCE_CAL);
        }
      }
    }
  }

  @SuppressWarnings("unchecked")
  private static Pair<InflationProviderDiscount, CurveBuildingBlockBundle>
      makeCurvesFromDefinitions(
          final InstrumentDefinition<?>[][][] definitions,
          final GeneratorCurve[][] curveGenerators,
          final String[][] curveNames,
          final InflationProviderDiscount knownData,
          final InstrumentDerivativeVisitor<ParameterInflationProviderInterface, Double> calculator,
          final InstrumentDerivativeVisitor<
                  ParameterInflationProviderInterface, InflationSensitivity>
              sensitivityCalculator) {
    final int nUnits = definitions.length;
    final MultiCurveBundle<GeneratorCurve>[] curveBundles = new MultiCurveBundle[nUnits];
    for (int i = 0; i < nUnits; i++) {
      final int nCurves = definitions[i].length;
      final SingleCurveBundle<GeneratorCurve>[] singleCurves = new SingleCurveBundle[nCurves];
      for (int j = 0; j < nCurves; j++) {
        final int nInstruments = definitions[i][j].length;
        final InstrumentDerivative[] derivatives = new InstrumentDerivative[nInstruments];
        final double[] initialGuess = new double[nInstruments];
        for (int k = 0; k < nInstruments; k++) {
          derivatives[k] = convert(definitions[i][j][k]);
          initialGuess[k] = initialGuess(definitions[i][j][k]);
        }
        final GeneratorCurve generator = curveGenerators[i][j].finalGenerator(derivatives);
        singleCurves[j] =
            new SingleCurveBundle<>(curveNames[i][j], derivatives, initialGuess, generator);
      }
      curveBundles[i] = new MultiCurveBundle<>(singleCurves);
    }
    return CURVE_BUILDING_REPOSITORY.makeCurvesFromDerivatives(
        curveBundles,
        knownData,
        DSC_MAP,
        FWD_ON_MAP,
        US_CPI_MAP,
        calculator,
        sensitivityCalculator);
  }

  private static InstrumentDerivative[][] convert(final InstrumentDefinition<?>[][] definitions) {
    final InstrumentDerivative[][] instruments = new InstrumentDerivative[definitions.length][];
    for (int loopcurve = 0; loopcurve < definitions.length; loopcurve++) {
      instruments[loopcurve] = new InstrumentDerivative[definitions[loopcurve].length];
      int loopins = 0;
      for (final InstrumentDefinition<?> instrument : definitions[loopcurve]) {
        InstrumentDerivative ird;
        if (instrument instanceof SwapFixedInflationZeroCouponDefinition) {
          final Annuity<? extends Payment> ird1 =
              ((SwapFixedInflationZeroCouponDefinition) instrument).getFirstLeg().toDerivative(NOW);
          final Annuity<? extends Payment> ird2 =
              ((SwapFixedInflationZeroCouponDefinition) instrument)
                  .getSecondLeg()
                  .toDerivative(NOW, TS_PRICE_INDEX_USD_WITH_TODAY);
          ird = new Swap<>(ird1, ird2);
        } else {
          ird = instrument.toDerivative(NOW);
        }
        instruments[loopcurve][loopins++] = ird;
      }
    }
    return instruments;
  }

  private static InstrumentDerivative convert(final InstrumentDefinition<?> instrument) {
    InstrumentDerivative ird;
    if (instrument instanceof SwapFixedInflationZeroCouponDefinition) {
      final Annuity<? extends Payment> ird1 =
          ((SwapFixedInflationZeroCouponDefinition) instrument).getFirstLeg().toDerivative(NOW);
      final Annuity<? extends Payment> ird2 =
          ((SwapFixedInflationZeroCouponDefinition) instrument)
              .getSecondLeg()
              .toDerivative(NOW, TS_PRICE_INDEX_USD_WITH_TODAY);
      ird = new Swap<>(ird1, ird2);
    } else {
      ird = instrument.toDerivative(NOW);
    }
    return ird;
  }

  private static double initialGuess(final InstrumentDefinition<?> instrument) {
    if (instrument instanceof SwapFixedONDefinition) {
      return ((SwapFixedONDefinition) instrument).getFixedLeg().getNthPayment(0).getRate();
    }
    if (instrument instanceof SwapFixedIborDefinition) {
      return ((SwapFixedIborDefinition) instrument).getFixedLeg().getNthPayment(0).getRate();
    }
    if (instrument instanceof SwapFixedInflationZeroCouponDefinition) {

      if (((SwapFixedInflationZeroCouponDefinition) instrument).getFirstLeg().getNthPayment(0)
          instanceof CouponInflationZeroCouponMonthlyDefinition) {
        return 100.0;
      }
      if (((SwapFixedInflationZeroCouponDefinition) instrument).getFirstLeg().getNthPayment(0)
          instanceof CouponInflationZeroCouponInterpolationDefinition) {
        return 100.0;
      }
      return 100;
    }
    if (instrument instanceof ForwardRateAgreementDefinition) {
      return ((ForwardRateAgreementDefinition) instrument).getRate();
    }
    if (instrument instanceof CashDefinition) {
      return ((CashDefinition) instrument).getRate();
    }
    return 100;
  }
}
/** Tests the present value of Capital inflation indexed bonds. */
@Test
public class BondCapitalIndexedSecurityDiscountingMethodTest {

  private static final InflationIssuerProviderDiscount MARKET =
      MulticurveProviderDiscountDataSets.createMarket1();
  private static final IndexPrice[] PRICE_INDEXES =
      MulticurveProviderDiscountDataSets.getPriceIndexes();
  private static final IndexPrice PRICE_INDEX_UKRPI = PRICE_INDEXES[1];
  private static final IndexPrice PRICE_INDEX_USCPI = PRICE_INDEXES[2];
  private static final IndexPrice PRICE_INDEX_AUDCPI = PRICE_INDEXES[3];
  private static final String[] ISSUER_NAMES = MulticurveProviderDiscountDataSets.getIssuerNames();
  private static final String ISSUER_US_GOVT = ISSUER_NAMES[0];
  private static final String ISSUER_UK_GOVT = ISSUER_NAMES[1];
  private static final String ISSUER_AUD_GOVT = ISSUER_NAMES[3];

  private static final double SHIFT_FD = 1.0E-9;
  private static final double TOLERANCE_PV_DELTA = 1.0E+2;
  private static final double TOLERANCE_SENSI_DELTA = 1.0E-6;

  private static final ZonedDateTime PRICING_DATE = DateUtils.getUTCDate(2011, 8, 8);
  private static final BondCapitalIndexedSecurityDiscountingMethod METHOD_BOND_INFLATION =
      new BondCapitalIndexedSecurityDiscountingMethod();
  private static final CouponInflationZeroCouponMonthlyGearingDiscountingMethod
      METHOD_INFLATION_ZC_MONTHLY = new CouponInflationZeroCouponMonthlyGearingDiscountingMethod();
  private static final CouponInflationZeroCouponInterpolationGearingDiscountingMethod
      METHOD_INFLATION_ZC_INTERPOLATION =
          new CouponInflationZeroCouponInterpolationGearingDiscountingMethod();
  private static final PresentValueDiscountingInflationCalculator PVDIC =
      PresentValueDiscountingInflationCalculator.getInstance();
  private static final NetAmountInflationCalculator NADIC =
      NetAmountInflationCalculator.getInstance();
  private static final PresentValueDiscountingInflationIssuerCalculator PVDIIC =
      PresentValueDiscountingInflationIssuerCalculator.getInstance();
  private static final ParameterSensitivityInflationMulticurveDiscountInterpolatedFDCalculator
      PS_PV_FDC =
          new ParameterSensitivityInflationMulticurveDiscountInterpolatedFDCalculator(
              PVDIC, SHIFT_FD);
  private static final PresentValueCurveSensitivityDiscountingInflationCalculator PVCSDC =
      PresentValueCurveSensitivityDiscountingInflationCalculator.getInstance();
  private static final ParameterSensitivityInflationParameterCalculator<
          ParameterInflationProviderInterface>
      PSC = new ParameterSensitivityInflationParameterCalculator<>(PVCSDC);

  // Treasury Indexed Bonds CAIN 3% Index-linked Treasury Stock 2025 - AU0000XCLWP8
  private static final HolidayCalendar CALENDAR_AUD = HolidayCalendars.SAT_SUN;
  private static final BusinessDayConvention BUSINESS_DAY_AUD = BusinessDayConventions.FOLLOWING;
  private static final DayCount DAY_COUNT_CAIN = DayCounts.ACT_ACT_ISDA;
  private static final boolean IS_EOM_CAIN = false;
  private static final ZonedDateTime START_DATE_CAIN = DateUtils.getUTCDate(2009, 9, 30);
  private static final ZonedDateTime FIRST_COUPON_DATE_CAIN = DateUtils.getUTCDate(2009, 12, 20);
  private static final ZonedDateTime MATURITY_DATE_CAIN = DateUtils.getUTCDate(2025, 12, 20);
  private static final YieldConvention YIELD_CONVENTION_CAIN =
      YieldConventionFactory.INSTANCE.getYieldConvention("UK:BUMP/DMO METHOD"); // To check
  private static final int MONTH_LAG_CAIN = 6;
  private static final double INDEX_START_CAIN = 173.60; // November 2001
  private static final double NOTIONAL_CAIN = 1.00;
  private static final double REAL_RATE_CAIN = 0.03;
  private static final Period COUPON_PERIOD_CAIN = Period.ofMonths(3);
  private static final int SETTLEMENT_DAYS_CAIN = 2;
  // TODO: ex-coupon 7 days
  private static final BondCapitalIndexedSecurityDefinition<
          CouponInflationZeroCouponMonthlyGearingDefinition>
      BOND_SECURITY_CAIN_DEFINITION =
          BondCapitalIndexedSecurityDefinition.fromMonthly(
              PRICE_INDEX_AUDCPI,
              MONTH_LAG_CAIN,
              START_DATE_CAIN,
              INDEX_START_CAIN,
              FIRST_COUPON_DATE_CAIN,
              MATURITY_DATE_CAIN,
              COUPON_PERIOD_CAIN,
              NOTIONAL_CAIN,
              REAL_RATE_CAIN,
              BUSINESS_DAY_AUD,
              SETTLEMENT_DAYS_CAIN,
              CALENDAR_AUD,
              DAY_COUNT_CAIN,
              YIELD_CONVENTION_CAIN,
              IS_EOM_CAIN,
              ISSUER_AUD_GOVT);
  private static final DoubleTimeSeries<ZonedDateTime> AUD_CPI =
      MulticurveProviderDiscountDataSets.audCPIFrom2009();
  private static final BondCapitalIndexedSecurity<Coupon> BOND_SECURITY_CAIN =
      BOND_SECURITY_CAIN_DEFINITION.toDerivative(PRICING_DATE, AUD_CPI);

  /** Tests the present value computation. */
  public void presentValueCAIN() {
    final InflationProviderDiscount marketUKGovt = new InflationProviderDiscount();
    marketUKGovt.setCurve(
        BOND_SECURITY_CAIN.getCurrency(), MARKET.getCurve(BOND_SECURITY_CAIN.getIssuerEntity()));
    marketUKGovt.setCurve(PRICE_INDEX_AUDCPI, MARKET.getCurve(PRICE_INDEX_AUDCPI));
    final MultiCurrencyAmount pvNominal =
        METHOD_INFLATION_ZC_MONTHLY.presentValue(
            (CouponInflationZeroCouponMonthlyGearing)
                BOND_SECURITY_CAIN.getNominal().getNthPayment(0),
            marketUKGovt);
    MultiCurrencyAmount pvCoupon = MultiCurrencyAmount.of(BOND_SECURITY_CAIN.getCurrency(), 0.0);
    for (int loopcpn = 0;
        loopcpn < BOND_SECURITY_CAIN.getCoupon().getNumberOfPayments();
        loopcpn++) {
      pvCoupon =
          pvCoupon.plus(
              BOND_SECURITY_CAIN.getCoupon().getNthPayment(loopcpn).accept(PVDIC, marketUKGovt));
    }
    final MultiCurrencyAmount pvExpectd = pvNominal.plus(pvCoupon);
    final MultiCurrencyAmount pv = METHOD_BOND_INFLATION.presentValue(BOND_SECURITY_CAIN, MARKET);
    assertEquals(
        "Inflation Capital Indexed bond: present value",
        pvExpectd.getAmount(BOND_SECURITY_CAIN.getCurrency()).getAmount(),
        pv.getAmount(BOND_SECURITY_CAIN.getCurrency()).getAmount(),
        1.0E-2);
  }

  /** Tests the present value Method vs Calculator. */
  public void presentValueMethodVsCalculatorCAIN() {
    final MultiCurrencyAmount pvMethod =
        METHOD_BOND_INFLATION.presentValue(BOND_SECURITY_CAIN, MARKET);
    final MultiCurrencyAmount pvCalculator = BOND_SECURITY_CAIN.accept(PVDIIC, MARKET);
    assertEquals("Inflation Capital Indexed bond: present value", pvMethod, pvCalculator);
  }

  /** Test the present value parameter curves sensitivity. */
  public void presentValueParameterCurveSensitivityCAIN() {

    final MultipleCurrencyParameterSensitivity pvicsFD =
        PS_PV_FDC.calculateSensitivity(
            BOND_SECURITY_CAIN.getCoupon(), MARKET.getInflationProvider());
    final MultipleCurrencyParameterSensitivity pvicsExact =
        PSC.calculateSensitivity(
            BOND_SECURITY_CAIN.getCoupon(), MARKET.getInflationProvider(), MARKET.getAllNames());

    AssertSensitivityObjects.assertEquals(
        "Bond capital indexed security: presentValueParameterCurveSensitivity ",
        pvicsExact,
        pvicsFD,
        TOLERANCE_SENSI_DELTA);
  }

  /** Test the present value curves sensitivity. */
  public void presentValueCurveSensitivityCAIN() {
    MulticurveProviderInterface multicurveDecorated =
        new MulticurveProviderDiscountingDecoratedIssuer(
            MARKET.getIssuerProvider(),
            BOND_SECURITY_CAIN.getCurrency(),
            BOND_SECURITY_CAIN.getIssuerEntity());
    InflationProviderInterface creditDiscounting =
        new InflationProviderDecoratedMulticurve(
            MARKET.getInflationProvider(), multicurveDecorated);
    final MultipleCurrencyInflationSensitivity sensitivityNominal =
        BOND_SECURITY_CAIN.getNominal().accept(PVCSDC, creditDiscounting);
    final MultipleCurrencyInflationSensitivity sensitivityCoupon =
        BOND_SECURITY_CAIN.getCoupon().accept(PVCSDC, creditDiscounting);
    final MultipleCurrencyInflationSensitivity pvcisCalculated =
        sensitivityNominal.plus(sensitivityCoupon);

    final MultipleCurrencyInflationSensitivity pvcisMethod =
        METHOD_BOND_INFLATION.presentValueCurveSensitivity(BOND_SECURITY_CAIN, MARKET);

    AssertSensitivityObjects.assertEquals(
        "Bond capital indexed security: presentValueCurveSensitivity ",
        pvcisCalculated,
        pvcisMethod,
        TOLERANCE_PV_DELTA);
  }

  // Index-Lined Gilt 2% Index-linked Treasury Stock 2035 - GB0031790826
  private static final HolidayCalendar CALENDAR_GBP = HolidayCalendars.SAT_SUN;
  private static final BusinessDayConvention BUSINESS_DAY_GBP = BusinessDayConventions.FOLLOWING;
  private static final DayCount DAY_COUNT_GILT_1 = DayCounts.ACT_ACT_ISDA;
  private static final boolean IS_EOM_GILT_1 = false;
  private static final ZonedDateTime START_DATE_GILT_1 = DateUtils.getUTCDate(2002, 7, 11);
  private static final ZonedDateTime FIRST_COUPON_DATE_GILT_1 = DateUtils.getUTCDate(2003, 1, 26);
  private static final ZonedDateTime MATURITY_DATE_GILT_1 = DateUtils.getUTCDate(2035, 1, 26);
  private static final YieldConvention YIELD_CONVENTION_GILT_1 = SimpleYieldConvention.UK_IL_BOND;
  // YieldConventionFactory.INSTANCE.getYieldConvention("UK:BUMP/DMO METHOD"); // To check
  private static final int MONTH_LAG_GILT_1 = 8;
  private static final double INDEX_START_GILT_1 = 173.60; // November 2001
  private static final double NOTIONAL_GILT_1 = 1.00;
  private static final double REAL_RATE_GILT_1 = 0.02;
  private static final Period COUPON_PERIOD_GILT_1 = Period.ofMonths(6);
  private static final int SETTLEMENT_DAYS_GILT_1 = 2;
  // TODO: ex-coupon 7 days
  private static final BondCapitalIndexedSecurityDefinition<
          CouponInflationZeroCouponMonthlyGearingDefinition>
      BOND_SECURITY_GILT_1_DEFINITION =
          BondCapitalIndexedSecurityDefinition.fromMonthly(
              PRICE_INDEX_UKRPI,
              MONTH_LAG_GILT_1,
              START_DATE_GILT_1,
              INDEX_START_GILT_1,
              FIRST_COUPON_DATE_GILT_1,
              MATURITY_DATE_GILT_1,
              COUPON_PERIOD_GILT_1,
              NOTIONAL_GILT_1,
              REAL_RATE_GILT_1,
              BUSINESS_DAY_GBP,
              SETTLEMENT_DAYS_GILT_1,
              CALENDAR_GBP,
              DAY_COUNT_GILT_1,
              YIELD_CONVENTION_GILT_1,
              IS_EOM_GILT_1,
              ISSUER_UK_GOVT);
  private static final DoubleTimeSeries<ZonedDateTime> UK_RPI =
      MulticurveProviderDiscountDataSets.ukRpiFrom2010();
  private static final BondCapitalIndexedSecurity<Coupon> BOND_SECURITY_GILT_1 =
      BOND_SECURITY_GILT_1_DEFINITION.toDerivative(PRICING_DATE, UK_RPI);

  /** Tests the present value computation. */
  public void presentValueGilt1() {
    final InflationProviderDiscount marketUKGovt = new InflationProviderDiscount();
    marketUKGovt.setCurve(
        BOND_SECURITY_GILT_1.getCurrency(),
        MARKET.getCurve(BOND_SECURITY_GILT_1.getIssuerEntity()));
    marketUKGovt.setCurve(PRICE_INDEX_UKRPI, MARKET.getCurve(PRICE_INDEX_UKRPI));
    final MultiCurrencyAmount pvNominal =
        METHOD_INFLATION_ZC_MONTHLY.presentValue(
            (CouponInflationZeroCouponMonthlyGearing)
                BOND_SECURITY_GILT_1.getNominal().getNthPayment(0),
            marketUKGovt);
    MultiCurrencyAmount pvCoupon = MultiCurrencyAmount.of(BOND_SECURITY_GILT_1.getCurrency(), 0.0);
    for (int loopcpn = 0;
        loopcpn < BOND_SECURITY_GILT_1.getCoupon().getNumberOfPayments();
        loopcpn++) {
      pvCoupon =
          pvCoupon.plus(
              BOND_SECURITY_GILT_1.getCoupon().getNthPayment(loopcpn).accept(PVDIC, marketUKGovt));
    }
    final MultiCurrencyAmount pvExpected = pvNominal.plus(pvCoupon);
    final MultiCurrencyAmount pv = METHOD_BOND_INFLATION.presentValue(BOND_SECURITY_GILT_1, MARKET);
    assertEquals(
        "Inflation Capital Indexed bond: present value",
        pvExpected.getAmount(BOND_SECURITY_GILT_1.getCurrency()).getAmount(),
        pv.getAmount(BOND_SECURITY_GILT_1.getCurrency()).getAmount(),
        1.0E-2);
  }

  /** Tests the present value Method vs Calculator. */
  public void presentValueMethodVsCalculator() {
    final MultiCurrencyAmount pvMethod =
        METHOD_BOND_INFLATION.presentValue(BOND_SECURITY_GILT_1, MARKET);
    final MultiCurrencyAmount pvCalculator = BOND_SECURITY_GILT_1.accept(PVDIIC, MARKET);
    assertEquals("Inflation Capital Indexed bond: present value", pvMethod, pvCalculator);
  }

  // 2% 10-YEAR TREASURY INFLATION-PROTECTED SECURITIES (TIPS) Due January 15, 2016 - US912828ET33
  private static final HolidayCalendar CALENDAR_USD = HolidayCalendars.SAT_SUN;
  private static final BusinessDayConvention BUSINESS_DAY_USD = BusinessDayConventions.FOLLOWING;
  private static final DayCount DAY_COUNT_TIPS_1 = DayCounts.ACT_ACT_ICMA;
  private static final boolean IS_EOM_TIPS_1 = false;
  private static final ZonedDateTime START_DATE_TIPS_1 = DateUtils.getUTCDate(2006, 1, 15);
  private static final ZonedDateTime MATURITY_DATE_TIPS_1 = DateUtils.getUTCDate(2016, 1, 15);
  private static final YieldConvention YIELD_CONVENTION_TIPS_1 = SimpleYieldConvention.US_IL_REAL;
  private static final int MONTH_LAG_TIPS_1 = 3;
  private static final double INDEX_START_TIPS_1 = 198.47742; // Date:
  private static final double NOTIONAL_TIPS_1 = 100.00;
  private static final double REAL_RATE_TIPS_1 = 0.02;
  private static final Period COUPON_PERIOD_TIPS_1 = Period.ofMonths(6);
  private static final int SETTLEMENT_DAYS_TIPS_1 = 1;

  private static final BondCapitalIndexedSecurityDefinition<
          CouponInflationZeroCouponInterpolationGearingDefinition>
      BOND_SECURITY_TIPS_1_DEFINITION =
          BondCapitalIndexedSecurityDefinition.fromInterpolation(
              PRICE_INDEX_USCPI,
              MONTH_LAG_TIPS_1,
              START_DATE_TIPS_1,
              INDEX_START_TIPS_1,
              MATURITY_DATE_TIPS_1,
              COUPON_PERIOD_TIPS_1,
              NOTIONAL_TIPS_1,
              REAL_RATE_TIPS_1,
              BUSINESS_DAY_USD,
              SETTLEMENT_DAYS_TIPS_1,
              CALENDAR_USD,
              DAY_COUNT_TIPS_1,
              YIELD_CONVENTION_TIPS_1,
              IS_EOM_TIPS_1,
              ISSUER_US_GOVT);
  private static final DoubleTimeSeries<ZonedDateTime> US_CPI =
      MulticurveProviderDiscountDataSets.usCpiFrom2009();
  private static final BondCapitalIndexedSecurity<Coupon> BOND_SECURITY_TIPS_1 =
      BOND_SECURITY_TIPS_1_DEFINITION.toDerivative(PRICING_DATE, US_CPI);

  /** Tests the present value computation. */
  public void presentValueTips1() {
    final InflationProviderDiscount marketUSGovt = new InflationProviderDiscount();
    marketUSGovt.setCurve(
        BOND_SECURITY_TIPS_1.getCurrency(),
        MARKET.getCurve(BOND_SECURITY_TIPS_1.getIssuerEntity()));
    marketUSGovt.setCurve(PRICE_INDEX_USCPI, MARKET.getCurve(PRICE_INDEX_USCPI));
    final MultiCurrencyAmount pvNominal =
        METHOD_INFLATION_ZC_INTERPOLATION.presentValue(
            (CouponInflationZeroCouponInterpolationGearing)
                BOND_SECURITY_TIPS_1.getNominal().getNthPayment(0),
            marketUSGovt);
    MultiCurrencyAmount pvCoupon = MultiCurrencyAmount.of(BOND_SECURITY_TIPS_1.getCurrency(), 0.0);
    for (int loopcpn = 0;
        loopcpn < BOND_SECURITY_TIPS_1.getCoupon().getNumberOfPayments();
        loopcpn++) {
      pvCoupon =
          pvCoupon.plus(
              BOND_SECURITY_TIPS_1.getCoupon().getNthPayment(loopcpn).accept(PVDIC, marketUSGovt));
    }
    final MultiCurrencyAmount pvExpected = pvNominal.plus(pvCoupon);
    final MultiCurrencyAmount pv = METHOD_BOND_INFLATION.presentValue(BOND_SECURITY_TIPS_1, MARKET);
    assertEquals(
        "Inflation Capital Indexed bond: present value",
        pvExpected.getAmount(BOND_SECURITY_TIPS_1.getCurrency()).getAmount(),
        pv.getAmount(BOND_SECURITY_TIPS_1.getCurrency()).getAmount(),
        1.0E-2);
  }

  /** Tests the present value computation. */
  public void presentValueFromCleanPriceRealTips1() {
    final double cleanPriceReal = 1.05;
    Currency ccy = BOND_SECURITY_TIPS_1.getCurrency();
    final MultiCurrencyAmount pv =
        METHOD_BOND_INFLATION.presentValueFromCleanRealPrice(
            BOND_SECURITY_TIPS_1, MARKET, cleanPriceReal);
    MultiCurrencyAmount pvPriceReal =
        BOND_SECURITY_TIPS_1.getSettlement().accept(PVDIIC, MARKET).multipliedBy(cleanPriceReal);
    MultiCurrencyAmount pvAccrued =
        BOND_SECURITY_TIPS_1
            .getSettlement()
            .accept(PVDIC, MARKET)
            .multipliedBy(BOND_SECURITY_TIPS_1.getAccruedInterest());
    MultiCurrencyAmount pvExpected = pvPriceReal.plus(pvAccrued);
    assertEquals(
        "Inflation Capital Indexed bond: present value from clean real price",
        pvExpected.getAmount(ccy).getAmount(),
        pv.getAmount(ccy).getAmount(),
        1.0E-6);
  }

  /** Tests the present value computation. */
  public void presentValueFromCleanPriceNominalTips1() {
    final double cleanPriceNominal = 1.05;
    Currency ccy = BOND_SECURITY_TIPS_1.getCurrency();
    final MultiCurrencyAmount pv =
        METHOD_BOND_INFLATION.presentValueFromCleanNominalPrice(
            BOND_SECURITY_TIPS_1, MARKET, cleanPriceNominal);
    MultiCurrencyAmount pvAccrued =
        BOND_SECURITY_TIPS_1
            .getSettlement()
            .accept(PVDIC, MARKET)
            .multipliedBy(BOND_SECURITY_TIPS_1.getAccruedInterest());
    double pvPriceNominal =
        cleanPriceNominal
            * MARKET.getDiscountFactor(ccy, BOND_SECURITY_TIPS_1.getSettlementTime())
            * NOTIONAL_TIPS_1;
    double pvExpected = pvPriceNominal + pvAccrued.getAmount(ccy).getAmount();
    assertEquals(
        "Inflation Capital Indexed bond: present value from clean real price",
        pvExpected,
        pv.getAmount(ccy).getAmount(),
        1.0E-6);
  }

  /** Tests the clean real price from the dirty real price. */
  public void cleanNominalPriceFromDirtyNominalPriceTips1() {
    final double dirtyNominal = 1.01;
    final double cleanReal =
        METHOD_BOND_INFLATION.cleanNominalPriceFromDirtyNominalPrice(
            BOND_SECURITY_TIPS_1, dirtyNominal);
    final double indexRatio = BOND_SECURITY_TIPS_1.getIndexRatio();
    final double cleanRealExpected =
        dirtyNominal - BOND_SECURITY_TIPS_1.getAccruedInterest() / NOTIONAL_TIPS_1 * indexRatio;
    assertEquals(
        "Inflation Capital Indexed bond: clean from dirty", cleanRealExpected, cleanReal, 1.0E-8);
  }

  /** Tests the clean real price from the dirty real price. */
  public void cleanRealFromDirtyRealTips1() {
    final double dirtyReal = 1.01;
    final double cleanReal =
        METHOD_BOND_INFLATION.cleanRealPriceFromDirtyRealPrice(BOND_SECURITY_TIPS_1, dirtyReal);
    final double cleanRealExpected =
        dirtyReal - BOND_SECURITY_TIPS_1.getAccruedInterest() / NOTIONAL_TIPS_1;
    assertEquals(
        "Inflation Capital Indexed bond: clean from dirty", cleanRealExpected, cleanReal, 1.0E-8);
  }

  /** Tests the dirty real price computation from the real yield in the "US I/L real" convention. */
  public void dirtyRealPriceFromRealYieldTips1() {
    final double[] yield = new double[] {-0.01, 0.00, 0.01, 0.02, 0.03};
    final int nbCoupon = BOND_SECURITY_TIPS_1.getCoupon().getNumberOfPayments();
    final double[] dirtyRealPrice = new double[yield.length];
    final double[] dirtyRealPriceExpected = new double[yield.length];
    for (int loopyield = 0; loopyield < yield.length; loopyield++) {
      dirtyRealPrice[loopyield] =
          METHOD_BOND_INFLATION.dirtyPriceFromRealYield(BOND_SECURITY_TIPS_1, yield[loopyield]);

      final double factorOnPeriod = 1 + yield[loopyield] / BOND_SECURITY_TIPS_1.getCouponPerYear();
      double pvAtFirstCoupon = 0;

      for (int loopcpn = 0; loopcpn < nbCoupon; loopcpn++) {
        pvAtFirstCoupon +=
            ((CouponInflationGearing) BOND_SECURITY_TIPS_1.getCoupon().getNthPayment(loopcpn))
                    .getFactor()
                / BOND_SECURITY_TIPS_1.getCouponPerYear()
                / Math.pow(factorOnPeriod, loopcpn);
      }
      pvAtFirstCoupon += 1.0 / Math.pow(factorOnPeriod, nbCoupon - 1);
      dirtyRealPriceExpected[loopyield] =
          pvAtFirstCoupon
              / (1
                  + BOND_SECURITY_TIPS_1.getAccrualFactorToNextCoupon()
                      * yield[loopyield]
                      / BOND_SECURITY_TIPS_1.getCouponPerYear());
      assertEquals(
          "Inflation Capital Indexed bond: yield " + loopyield,
          dirtyRealPriceExpected[loopyield],
          dirtyRealPrice[loopyield],
          1.0E-8);
    }
  }

  /** Tests the clean real price from the dirty real price. */
  public void yieldRealFromDirtyRealTips1() {
    final double[] yield = new double[] {-0.01, 0.00, 0.01, 0.02, 0.03};
    final double[] dirtyRealPrice = new double[yield.length];
    final double[] yieldComputed = new double[yield.length];
    for (int loopyield = 0; loopyield < yield.length; loopyield++) {
      dirtyRealPrice[loopyield] =
          METHOD_BOND_INFLATION.dirtyPriceFromRealYield(BOND_SECURITY_TIPS_1, yield[loopyield]);
      yieldComputed[loopyield] =
          METHOD_BOND_INFLATION.yieldRealFromDirtyRealPrice(
              BOND_SECURITY_TIPS_1, dirtyRealPrice[loopyield]);
      assertEquals(
          "Inflation Capital Indexed bond: yield " + loopyield,
          yield[loopyield],
          yieldComputed[loopyield],
          1.0E-8);
    }
  }

  @Test(enabled = false)
  /** Tests the clean, dirty and yield vs external hard-coded values. */
  public void priceYieldExternalValues1() {
    final double m1 = 1000000; // Notional of the external figures.
    final ZonedDateTime pricingDate20110817 = DateUtils.getUTCDate(2011, 8, 16); // Spot 18-Aug-2011
    final InflationIssuerProviderDiscount market =
        MulticurveProviderDiscountDataSets.createMarket1(pricingDate20110817);
    final double cleanRealPrice = 1.00;
    final BondCapitalIndexedSecurity<Coupon> bond_110817 =
        BOND_SECURITY_TIPS_1_DEFINITION.toDerivative(pricingDate20110817, US_CPI);
    final double referenceIndexExpected = 225.83129;
    final MultiCurrencyAmount netAmountSettle =
        bond_110817.getSettlement().accept(NADIC, market.getInflationProvider());
    final double referenceIndexComputed =
        netAmountSettle.getAmount(bond_110817.getCurrency()).getAmount()
            * BOND_SECURITY_TIPS_1_DEFINITION.getIndexStartValue()
            / bond_110817.getSettlement().getNotional();
    assertEquals(
        "Inflation Capital Indexed bond: index",
        referenceIndexExpected,
        referenceIndexComputed,
        1.0E-5);
    final double indexRatioExpected = 1.13782;
    final MultiCurrencyAmount indexRatioCalculated =
        bond_110817.getSettlement().accept(NADIC, market.getInflationProvider());
    assertEquals(
        "Inflation Capital Indexed bond: indexRatio",
        indexRatioExpected,
        indexRatioCalculated.getAmount(PRICE_INDEX_USCPI.getCurrency()).getAmount()
            / NOTIONAL_TIPS_1,
        1.0E-5);
    final double yieldExpected = 1.999644 / 100.0;
    final double dirtyRealPriceComputed =
        METHOD_BOND_INFLATION.dirtyRealPriceFromCleanRealPrice(bond_110817, cleanRealPrice);
    final double yieldComputed =
        METHOD_BOND_INFLATION.yieldRealFromDirtyRealPrice(bond_110817, dirtyRealPriceComputed);
    assertEquals("Inflation Capital Indexed bond: yield ", yieldExpected, yieldComputed, 1.0E-8);
    final double accruedExpected = 2102.49;
    final double accruedRealExpected = accruedExpected / m1 / indexRatioExpected;
    final double accruedReal = bond_110817.getAccruedInterest();
    assertEquals(
        "Inflation Capital Indexed bond: accrued",
        accruedRealExpected,
        accruedReal / NOTIONAL_TIPS_1,
        1.0E-8);
    final double netAmountExpected = 1139922.49; // For 1m; uses the rounding rules.
    final double netAmount2 = indexRatioExpected * m1 * cleanRealPrice + accruedExpected;
    assertEquals(
        "Inflation Capital Indexed bond: net amount", netAmountExpected, netAmount2, 1.0E-2);
    final MultiCurrencyAmount netAmount =
        METHOD_BOND_INFLATION.netAmount(bond_110817, market, cleanRealPrice);
    assertEquals(
        "Inflation Capital Indexed bond: net amount",
        netAmountExpected,
        netAmount.getAmount(PRICE_INDEX_USCPI.getCurrency()).getAmount() * m1 / NOTIONAL_TIPS_1,
        2.0E+0); // The difference is due to rounding.
  }

  @Test(enabled = false)
  /** Tests the clean, dirty and yield vs external hard-coded values. */
  public void priceYieldExternalValues2() {
    final double m1 = 1000000; // Notional of the external figures.
    final ZonedDateTime pricingDate20110817 = DateUtils.getUTCDate(2011, 8, 17); // Spot 18-Aug-2011
    final InflationIssuerProviderDiscount market =
        MulticurveProviderDiscountDataSets.createMarket1(pricingDate20110817);
    final double cleanRealPrice = 1.13 + 0.01 / 32;
    final BondCapitalIndexedSecurity<Coupon> bond_110817 =
        BOND_SECURITY_TIPS_1_DEFINITION.toDerivative(pricingDate20110817, US_CPI);
    final double referenceIndexExpected = 225.83129;
    final MultiCurrencyAmount netAmountSettle =
        bond_110817.getSettlement().accept(NADIC, market.getInflationProvider());
    final double referenceIndexComputed =
        netAmountSettle.getAmount(bond_110817.getCurrency()).getAmount()
            * BOND_SECURITY_TIPS_1_DEFINITION.getIndexStartValue()
            / bond_110817.getSettlement().getNotional();
    assertEquals(
        "Inflation Capital Indexed bond: index",
        referenceIndexExpected,
        referenceIndexComputed,
        1.0E-5);
    final double indexRatioExpected = 1.13782;
    assertEquals(
        "Inflation Capital Indexed bond: indexRatio",
        indexRatioExpected,
        referenceIndexComputed / INDEX_START_TIPS_1,
        1.0E-5);
    final double yieldExpected = -0.892152 / 100.0;
    final double dirtyRealPriceComputed =
        METHOD_BOND_INFLATION.dirtyRealPriceFromCleanRealPrice(bond_110817, cleanRealPrice);
    final double yieldComputed =
        METHOD_BOND_INFLATION.yieldRealFromDirtyRealPrice(bond_110817, dirtyRealPriceComputed);
    assertEquals("Inflation Capital Indexed bond: yield ", yieldExpected, yieldComputed, 1.0E-8);
    final double accruedExpected = 2102.49;
    final double accruedRealExpected = accruedExpected / m1 / indexRatioExpected;
    final double accruedReal = bond_110817.getAccruedInterest();
    assertEquals(
        "Inflation Capital Indexed bond: accrued",
        accruedRealExpected,
        accruedReal / NOTIONAL_TIPS_1,
        1.0E-8);
    final double netAmountExpected = 1288194.66; // For 1m; uses the rounding rules.
    final double netAmount2 = indexRatioExpected * m1 * cleanRealPrice + accruedExpected;
    assertEquals(
        "Inflation Capital Indexed bond: net amount", netAmountExpected, netAmount2, 1.0E-2);
    final MultiCurrencyAmount netAmount =
        METHOD_BOND_INFLATION.netAmount(bond_110817, market, cleanRealPrice);
    assertEquals(
        "Inflation Capital Indexed bond: net amount",
        netAmountExpected,
        netAmount.getAmount(PRICE_INDEX_USCPI.getCurrency()).getAmount() * m1 / NOTIONAL_TIPS_1,
        2.0E+0); // The difference is due to rounding.
  }

  @Test(enabled = false)
  /** Tests the clean, dirty and yield vs external hard-coded values. */
  public void priceYieldExternalValues3() {
    final double m1 = 1000000; // Notional of the external figures.
    final ZonedDateTime pricingDate20110817 = DateUtils.getUTCDate(2011, 8, 18); // Spot 19-Aug-2011
    final InflationIssuerProviderDiscount market =
        MulticurveProviderDiscountDataSets.createMarket1(pricingDate20110817);
    final double cleanRealPrice = 1.00;
    final BondCapitalIndexedSecurity<Coupon> bond_110817 =
        BOND_SECURITY_TIPS_1_DEFINITION.toDerivative(pricingDate20110817, US_CPI);
    final double referenceIndexExpected = 225.82348;
    final MultiCurrencyAmount netAmountSettle =
        bond_110817.getSettlement().accept(NADIC, market.getInflationProvider());
    final double referenceIndexComputed =
        netAmountSettle.getAmount(bond_110817.getCurrency()).getAmount()
            * BOND_SECURITY_TIPS_1_DEFINITION.getIndexStartValue()
            / bond_110817.getSettlement().getNotional();
    assertEquals(
        "Inflation Capital Indexed bond: index",
        referenceIndexExpected,
        referenceIndexComputed,
        1.0E-5);
    final double indexRatioExpected = 1.13778;
    final double yieldExpected = 1.999636 / 100.0;
    final double dirtyRealPriceComputed =
        METHOD_BOND_INFLATION.dirtyRealPriceFromCleanRealPrice(bond_110817, cleanRealPrice);
    final double yieldComputed =
        METHOD_BOND_INFLATION.yieldRealFromDirtyRealPrice(bond_110817, dirtyRealPriceComputed);
    assertEquals("Inflation Capital Indexed bond: yield ", yieldExpected, yieldComputed, 1.0E-8);
    final double accruedExpected = 2164.26;
    final double accruedRealExpected = accruedExpected / m1 / indexRatioExpected;
    final double accruedReal = bond_110817.getAccruedInterest();
    assertEquals(
        "Inflation Capital Indexed bond: accrued",
        accruedRealExpected,
        accruedReal / NOTIONAL_TIPS_1,
        1.0E-8);
    final double netAmountExpected = 1139944.26; // For 1m; uses the rounding rules.
    final double netAmount2 = indexRatioExpected * m1 * cleanRealPrice + accruedExpected;
    assertEquals(
        "Inflation Capital Indexed bond: net amount", netAmountExpected, netAmount2, 1.0E-2);
    final MultiCurrencyAmount netAmount =
        METHOD_BOND_INFLATION.netAmount(bond_110817, market, cleanRealPrice);
    assertEquals(
        "Inflation Capital Indexed bond: net amount",
        netAmountExpected,
        netAmount.getAmount(PRICE_INDEX_USCPI.getCurrency()).getAmount() * m1 / NOTIONAL_TIPS_1,
        2.0E+0); // The difference is due to rounding.
  }

  /** Test the present value parameter curves sensitivity. */
  public void presentValueParameterCurveSensitivity() {

    final MultipleCurrencyParameterSensitivity pvicsFD =
        PS_PV_FDC.calculateSensitivity(
            BOND_SECURITY_GILT_1.getCoupon(), MARKET.getInflationProvider());
    final MultipleCurrencyParameterSensitivity pvicsExact =
        PSC.calculateSensitivity(
            BOND_SECURITY_GILT_1.getCoupon(), MARKET.getInflationProvider(), MARKET.getAllNames());

    AssertSensitivityObjects.assertEquals(
        "Bond capital indexed security: presentValueParameterCurveSensitivity ",
        pvicsExact,
        pvicsFD,
        TOLERANCE_PV_DELTA);
  }

  /** Test the present value curves sensitivity. */
  public void presentValueCurveSensitivity() {
    MulticurveProviderInterface multicurveDecorated =
        new MulticurveProviderDiscountingDecoratedIssuer(
            MARKET.getIssuerProvider(),
            BOND_SECURITY_GILT_1.getCurrency(),
            BOND_SECURITY_GILT_1.getIssuerEntity());
    InflationProviderInterface inflationDecorated =
        new InflationProviderDecoratedMulticurve(
            MARKET.getInflationProvider(), multicurveDecorated);
    final MultipleCurrencyInflationSensitivity sensitivityNominal =
        BOND_SECURITY_GILT_1.getNominal().accept(PVCSDC, inflationDecorated);
    final MultipleCurrencyInflationSensitivity sensitivityCoupon =
        BOND_SECURITY_GILT_1.getCoupon().accept(PVCSDC, inflationDecorated);
    final MultipleCurrencyInflationSensitivity pvcisCalculated =
        sensitivityNominal.plus(sensitivityCoupon);
    final MultipleCurrencyInflationSensitivity pvcisMethod =
        METHOD_BOND_INFLATION.presentValueCurveSensitivity(BOND_SECURITY_GILT_1, MARKET);
    AssertSensitivityObjects.assertEquals(
        "Bond capital indexed security: presentValueCurveSensitivity ",
        pvcisCalculated,
        pvcisMethod,
        TOLERANCE_PV_DELTA);
  }
}