@Override
  public MulticurveSensitivity visitSwapFuturesPriceDeliverableSecurity(
      final SwapFuturesPriceDeliverableSecurity futures,
      final ParameterProviderInterface multicurve) {
    ArgChecker.notNull(futures, "futures");
    ArgChecker.notNull(multicurve, "multi-curve provider");
    double dfInv =
        1.0
            / multicurve
                .getMulticurveProvider()
                .getDiscountFactor(futures.getCurrency(), futures.getDeliveryTime());
    MulticurveSensitivity pvcs =
        futures
            .getUnderlyingSwap()
            .accept(PVCSDC, multicurve.getMulticurveProvider())
            .getSensitivity(futures.getCurrency())
            .multipliedBy(dfInv);

    final PresentValueDiscountingCalculator pvCalc =
        PresentValueDiscountingCalculator.getInstance();
    double pv =
        futures
            .getUnderlyingSwap()
            .accept(pvCalc, multicurve.getMulticurveProvider())
            .getAmount(futures.getCurrency())
            .getAmount();
    final Map<String, List<DoublesPair>> resultMap = new HashMap<>();
    final List<DoublesPair> listDf = new ArrayList<>();
    listDf.add(DoublesPair.of(futures.getDeliveryTime(), futures.getDeliveryTime() * pv * dfInv));
    resultMap.put(multicurve.getMulticurveProvider().getName(futures.getCurrency()), listDf);
    MulticurveSensitivity result = MulticurveSensitivity.ofYieldDiscounting(resultMap);
    return result.plus(pvcs);
  }
/**
 * Method to compute the price for an deliverable swap futures with convexity adjustment from a
 * Hull-White one factor model.
 *
 * <p>Reference: Henrard M., Deliverable Interest Rate Swap Futures: pricing in Gaussian HJM model,
 * September 2012.
 */
public final class SwapFuturesPriceDeliverableSecurityHullWhiteMethod
    extends FuturesSecurityHullWhiteMethod {

  /** The unique instance of the calculator. */
  private static final SwapFuturesPriceDeliverableSecurityHullWhiteMethod INSTANCE =
      new SwapFuturesPriceDeliverableSecurityHullWhiteMethod();

  /** Constructor. */
  private SwapFuturesPriceDeliverableSecurityHullWhiteMethod() {}

  /**
   * Gets the calculator instance.
   *
   * @return The calculator.
   */
  public static SwapFuturesPriceDeliverableSecurityHullWhiteMethod getInstance() {
    return INSTANCE;
  }

  /** The present value calculator by discounting. */
  private static final PresentValueDiscountingCalculator PVDC =
      PresentValueDiscountingCalculator.getInstance();

  /**
   * Returns the convexity adjustment, i.e. the difference between the adjusted price and the
   * present value of the underlying swap.
   *
   * @param futures The swap futures.
   * @param hwMulticurves The multi-curve and parameters provider.
   * @return The adjustment.
   */
  public double convexityAdjustment(
      final SwapFuturesPriceDeliverableSecurity futures,
      final HullWhiteOneFactorProviderInterface hwMulticurves) {
    ArgChecker.notNull(futures, "swap futures");
    ArgChecker.notNull(hwMulticurves, "parameter provider");
    MultiCurrencyAmount pv =
        futures.getUnderlyingSwap().accept(PVDC, hwMulticurves.getMulticurveProvider());
    double price = price(futures, hwMulticurves);
    return price - (1.0d + pv.getAmount(futures.getCurrency()).getAmount());
  }
}
/** Tests related to the pricing of physical delivery swaption in Hull-White one factor model. */
public class SwaptionPhysicalFixedIborHullWhiteMethodTest {

  private static final MulticurveProviderDiscount MULTICURVES =
      MulticurveProviderDiscountDataSets.createMulticurveEurUsd();
  private static final IborIndex EURIBOR6M =
      MulticurveProviderDiscountDataSets.getIndexesIborMulticurveEurUsd()[1];

  private static final Currency EUR = EURIBOR6M.getCurrency();
  private static final Calendar CALENDAR = MulticurveProviderDiscountDataSets.getEURCalendar();

  private static final HullWhiteOneFactorPiecewiseConstantParameters HW_PARAMETERS =
      HullWhiteDataSets.createHullWhiteParameters();
  private static final HullWhiteOneFactorProviderDiscount HW_MULTICURVES =
      new HullWhiteOneFactorProviderDiscount(MULTICURVES, HW_PARAMETERS, EUR);

  private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2011, 7, 7);
  // Swaption 5Yx5Y
  private static final int SPOT_LAG = EURIBOR6M.getSpotLag();
  private static final int SWAP_TENOR_YEAR = 5;
  private static final Period SWAP_TENOR = Period.ofYears(SWAP_TENOR_YEAR);
  private static final GeneratorSwapFixedIbor EUR1YEURIBOR6M =
      GeneratorSwapFixedIborMaster.getInstance().getGenerator("EUR1YEURIBOR6M", CALENDAR);
  private static final ZonedDateTime EXPIRY_DATE = DateUtils.getUTCDate(2016, 7, 7);
  private static final boolean IS_LONG = true;
  private static final ZonedDateTime SETTLEMENT_DATE =
      ScheduleCalculator.getAdjustedDate(EXPIRY_DATE, SPOT_LAG, CALENDAR);
  private static final double NOTIONAL = 100000000; // 100m
  private static final double RATE = 0.0175;
  private static final boolean FIXED_IS_PAYER = true;
  private static final SwapFixedIborDefinition SWAP_PAYER_DEFINITION =
      SwapFixedIborDefinition.from(
          SETTLEMENT_DATE, SWAP_TENOR, EUR1YEURIBOR6M, NOTIONAL, RATE, FIXED_IS_PAYER);
  private static final SwapFixedIborDefinition SWAP_RECEIVER_DEFINITION =
      SwapFixedIborDefinition.from(
          SETTLEMENT_DATE, SWAP_TENOR, EUR1YEURIBOR6M, NOTIONAL, RATE, !FIXED_IS_PAYER);

  private static final SwaptionPhysicalFixedIborDefinition SWAPTION_LONG_PAYER_DEFINITION =
      SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, SWAP_PAYER_DEFINITION, IS_LONG);
  private static final SwaptionPhysicalFixedIborDefinition SWAPTION_LONG_RECEIVER_DEFINITION =
      SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, SWAP_RECEIVER_DEFINITION, IS_LONG);
  private static final SwaptionPhysicalFixedIborDefinition SWAPTION_SHORT_PAYER_DEFINITION =
      SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, SWAP_PAYER_DEFINITION, !IS_LONG);
  private static final SwaptionPhysicalFixedIborDefinition SWAPTION_SHORT_RECEIVER_DEFINITION =
      SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, SWAP_RECEIVER_DEFINITION, !IS_LONG);

  private static final SwapFixedCoupon<Coupon> SWAP_RECEIVER =
      SWAP_RECEIVER_DEFINITION.toDerivative(REFERENCE_DATE);
  private static final SwaptionPhysicalFixedIbor SWAPTION_LONG_PAYER =
      SWAPTION_LONG_PAYER_DEFINITION.toDerivative(REFERENCE_DATE);
  private static final SwaptionPhysicalFixedIbor SWAPTION_LONG_RECEIVER =
      SWAPTION_LONG_RECEIVER_DEFINITION.toDerivative(REFERENCE_DATE);
  private static final SwaptionPhysicalFixedIbor SWAPTION_SHORT_PAYER =
      SWAPTION_SHORT_PAYER_DEFINITION.toDerivative(REFERENCE_DATE);
  private static final SwaptionPhysicalFixedIbor SWAPTION_SHORT_RECEIVER =
      SWAPTION_SHORT_RECEIVER_DEFINITION.toDerivative(REFERENCE_DATE);

  // Calculator
  private static final SwaptionPhysicalFixedIborHullWhiteMethod METHOD_HW =
      SwaptionPhysicalFixedIborHullWhiteMethod.getInstance();
  private static final SwapFixedCouponDiscountingMethod METHOD_SWAP =
      SwapFixedCouponDiscountingMethod.getInstance();

  private static final CashFlowEquivalentCalculator CFEC =
      CashFlowEquivalentCalculator.getInstance();
  private static final ParRateDiscountingCalculator PRDC =
      ParRateDiscountingCalculator.getInstance();
  private static final PresentValueDiscountingCalculator PVDC =
      PresentValueDiscountingCalculator.getInstance();
  private static final PresentValueCurveSensitivityDiscountingCalculator PVCSDC =
      PresentValueCurveSensitivityDiscountingCalculator.getInstance();
  private static final PresentValueHullWhiteCalculator PVHWC =
      PresentValueHullWhiteCalculator.getInstance();
  private static final PresentValueCurveSensitivityHullWhiteCalculator PVCSHWC =
      PresentValueCurveSensitivityHullWhiteCalculator.getInstance();

  private static final double SHIFT = 1.0E-6;
  private static final ParameterSensitivityParameterCalculator<HullWhiteOneFactorProviderInterface>
      PS_HW_C = new ParameterSensitivityParameterCalculator<>(PVCSHWC);
  private static final ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator PS_HW_FDC =
      new ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator(PVHWC, SHIFT);

  private static final SwaptionPhysicalFixedIborHullWhiteNumericalIntegrationMethod
      METHOD_HW_INTEGRATION =
          SwaptionPhysicalFixedIborHullWhiteNumericalIntegrationMethod.getInstance();
  private static final SwaptionPhysicalFixedIborHullWhiteApproximationMethod
      METHOD_HW_APPROXIMATION = SwaptionPhysicalFixedIborHullWhiteApproximationMethod.getInstance();
  private static final int NB_PATH = 12500;
  private static final HullWhiteMonteCarloMethod METHOD_HW_MONTECARLO =
      new HullWhiteMonteCarloMethod(new NormalRandomNumberGenerator(0.0, 1.0), NB_PATH);

  private static final HullWhiteOneFactorPiecewiseConstantInterestRateModel MODEL =
      new HullWhiteOneFactorPiecewiseConstantInterestRateModel();
  private static final ProbabilityDistribution<Double> NORMAL = new NormalDistribution(0, 1);

  private static final double TOLERANCE_PV = 1.0E-2;
  private static final double TOLERANCE_PV_DELTA =
      1.0E+0; // Testing note: Sensitivity is for a movement of 1. 1E+2 = 1 cent for a 1 bp move.

  @Test
  /** Test the present value. */
  public void presentValueExplicit() {
    final MultipleCurrencyAmount pv = METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final double timeToExpiry = SWAPTION_LONG_PAYER.getTimeToExpiry();
    final AnnuityPaymentFixed cfe =
        CFEC.visitSwap(SWAPTION_LONG_PAYER.getUnderlyingSwap(), MULTICURVES);
    final int numberOfPayments = cfe.getNumberOfPayments();
    final double alpha[] = new double[numberOfPayments];
    final double disccf[] = new double[numberOfPayments];
    for (int loopcf = 0; loopcf < numberOfPayments; loopcf++) {
      alpha[loopcf] =
          MODEL.alpha(
              HW_PARAMETERS,
              0.0,
              timeToExpiry,
              timeToExpiry,
              cfe.getNthPayment(loopcf).getPaymentTime());
      disccf[loopcf] =
          MULTICURVES.getDiscountFactor(EUR, cfe.getNthPayment(loopcf).getPaymentTime())
              * cfe.getNthPayment(loopcf).getAmount();
    }
    final double kappa = MODEL.kappa(disccf, alpha);
    double pvExpected = 0.0;
    for (int loopcf = 0; loopcf < numberOfPayments; loopcf++) {
      pvExpected += disccf[loopcf] * NORMAL.getCDF(-kappa - alpha[loopcf]);
    }
    assertEquals(
        "Swaption physical - Hull-White - present value", pvExpected, pv.getAmount(EUR), 1E-2);
    final MultipleCurrencyAmount pv2 =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, cfe, HW_MULTICURVES);
    assertEquals("Swaption physical - Hull-White - present value", pv, pv2);
  }

  @Test
  /** Tests long/short parity. */
  public void longShortParityExplicit() {
    final MultipleCurrencyAmount pvLong =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvShort =
        METHOD_HW.presentValue(SWAPTION_SHORT_PAYER, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - long/short parity",
        pvLong.getAmount(EUR),
        -pvShort.getAmount(EUR),
        TOLERANCE_PV);
  }

  @Test
  /** Tests payer/receiver/swap parity. */
  public void payerReceiverParityExplicit() {
    final MultipleCurrencyAmount pvReceiverLong =
        METHOD_HW.presentValue(SWAPTION_LONG_RECEIVER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvPayerShort =
        METHOD_HW.presentValue(SWAPTION_SHORT_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvSwap = SWAP_RECEIVER.accept(PVDC, MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - payer/receiver/swap parity",
        pvReceiverLong.getAmount(EUR) + pvPayerShort.getAmount(EUR),
        pvSwap.getAmount(EUR),
        TOLERANCE_PV);
  }

  @Test
  /** Tests the method against the present value calculator. */
  public void presentValueMethodVsCalculator() {
    final MultipleCurrencyAmount pvMethod =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvCalculator = SWAPTION_LONG_PAYER.accept(PVHWC, HW_MULTICURVES);
    assertEquals(
        "SwaptionPhysicalFixedIborSABRMethod: present value : method and calculator",
        pvMethod,
        pvCalculator);
  }

  @Test
  /** Compare explicit formula with numerical integration. */
  public void presentValueNumericalIntegration() {
    final MultipleCurrencyAmount pvPayerLongExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvPayerLongIntegration =
        METHOD_HW_INTEGRATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/numerical integration",
        pvPayerLongExplicit.getAmount(EUR),
        pvPayerLongIntegration.getAmount(EUR),
        TOLERANCE_PV);
    final MultipleCurrencyAmount pvPayerShortExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvPayerShortIntegration =
        METHOD_HW_INTEGRATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/numerical integration",
        pvPayerShortExplicit.getAmount(EUR),
        pvPayerShortIntegration.getAmount(EUR),
        TOLERANCE_PV);
    final MultipleCurrencyAmount pvReceiverLongExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvReceiverLongIntegration =
        METHOD_HW_INTEGRATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/numerical integration",
        pvReceiverLongExplicit.getAmount(EUR),
        pvReceiverLongIntegration.getAmount(EUR),
        TOLERANCE_PV);
    final MultipleCurrencyAmount pvReceiverShortExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvReceiverShortIntegration =
        METHOD_HW_INTEGRATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/numerical integration",
        pvReceiverShortExplicit.getAmount(EUR),
        pvReceiverShortIntegration.getAmount(EUR),
        TOLERANCE_PV);
  }

  @Test
  /** Compare explicit formula with approximated formula. */
  public void presentValueApproximation() {
    final BlackImpliedVolatilityFormula implied = new BlackImpliedVolatilityFormula();
    final double forward =
        SWAPTION_LONG_PAYER
            .getUnderlyingSwap()
            .accept(ParRateDiscountingCalculator.getInstance(), MULTICURVES);
    final double pvbp =
        METHOD_SWAP.presentValueBasisPoint(SWAPTION_LONG_PAYER.getUnderlyingSwap(), MULTICURVES);
    final MultipleCurrencyAmount pvPayerLongExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvPayerLongApproximation =
        METHOD_HW_APPROXIMATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final BlackFunctionData data = new BlackFunctionData(forward, pvbp, 0.20);
    final double volExplicit =
        implied.getImpliedVolatility(data, SWAPTION_LONG_PAYER, pvPayerLongExplicit.getAmount(EUR));
    final double volApprox =
        implied.getImpliedVolatility(
            data, SWAPTION_LONG_PAYER, pvPayerLongApproximation.getAmount(EUR));
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/approximation",
        pvPayerLongExplicit.getAmount(EUR),
        pvPayerLongApproximation.getAmount(EUR),
        5.0E+2);
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/approximation",
        volExplicit,
        volApprox,
        2.5E-4); // 0.025%
    final MultipleCurrencyAmount pvReceiverLongExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvReceiverLongApproximation =
        METHOD_HW_APPROXIMATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/numerical integration",
        pvReceiverLongExplicit.getAmount(EUR),
        pvReceiverLongApproximation.getAmount(EUR),
        5.0E+2);
  }

  @Test
  /** Approximation analysis. */
  public void presentValueApproximationAnalysis() {
    final NormalImpliedVolatilityFormula implied = new NormalImpliedVolatilityFormula();
    final int nbStrike = 20;
    final double[] pvExplicit = new double[nbStrike + 1];
    final double[] pvApproximation = new double[nbStrike + 1];
    final double[] strike = new double[nbStrike + 1];
    final double[] volExplicit = new double[nbStrike + 1];
    final double[] volApprox = new double[nbStrike + 1];
    final double strikeRange = 0.010;
    final SwapFixedCoupon<Coupon> swap = SWAP_PAYER_DEFINITION.toDerivative(REFERENCE_DATE);
    final double forward = swap.accept(PRDC, MULTICURVES);
    final double pvbp = METHOD_SWAP.presentValueBasisPoint(swap, MULTICURVES);
    for (int loopstrike = 0; loopstrike <= nbStrike; loopstrike++) {
      strike[loopstrike] =
          forward
              - strikeRange
              + 3
                  * strikeRange
                  * loopstrike
                  / nbStrike; // From forward-strikeRange to forward+2*strikeRange
      final SwapFixedIborDefinition swapDefinition =
          SwapFixedIborDefinition.from(
              SETTLEMENT_DATE,
              SWAP_TENOR,
              EUR1YEURIBOR6M,
              NOTIONAL,
              strike[loopstrike],
              FIXED_IS_PAYER);
      final SwaptionPhysicalFixedIborDefinition swaptionDefinition =
          SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, swapDefinition, IS_LONG);
      final SwaptionPhysicalFixedIbor swaption = swaptionDefinition.toDerivative(REFERENCE_DATE);
      pvExplicit[loopstrike] = METHOD_HW.presentValue(swaption, HW_MULTICURVES).getAmount(EUR);
      pvApproximation[loopstrike] =
          METHOD_HW_APPROXIMATION.presentValue(swaption, HW_MULTICURVES).getAmount(EUR);
      final NormalFunctionData data = new NormalFunctionData(forward, pvbp, 0.01);
      volExplicit[loopstrike] =
          implied.getImpliedVolatility(data, swaption, pvExplicit[loopstrike]);
      volApprox[loopstrike] =
          implied.getImpliedVolatility(data, swaption, pvApproximation[loopstrike]);
      assertEquals(
          "Swaption physical - Hull-White - implied volatility - explicit/approximation",
          volExplicit[loopstrike],
          volApprox[loopstrike],
          1.0E-3); // 0.10%
    }
  }

  @Test(enabled = true)
  /** Compare explicit formula with Monte-Carlo and long/short and payer/receiver parities. */
  public void presentValueMonteCarlo() {
    HullWhiteMonteCarloMethod methodMC;
    methodMC =
        new HullWhiteMonteCarloMethod(
            new NormalRandomNumberGenerator(0.0, 1.0, new MersenneTwister()), NB_PATH);
    // Seed fixed to the DEFAULT_SEED for testing purposes.
    final MultipleCurrencyAmount pvPayerLongExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvPayerLongMC =
        methodMC.presentValue(SWAPTION_LONG_PAYER, EUR, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - Monte Carlo",
        pvPayerLongExplicit.getAmount(EUR),
        pvPayerLongMC.getAmount(EUR),
        1.0E+4);
    final double pvMCPreviousRun = 4221400.891;
    assertEquals(
        "Swaption physical - Hull-White - Monte Carlo",
        pvMCPreviousRun,
        pvPayerLongMC.getAmount(EUR),
        TOLERANCE_PV);
    methodMC =
        new HullWhiteMonteCarloMethod(
            new NormalRandomNumberGenerator(0.0, 1.0, new MersenneTwister()), NB_PATH);
    final MultipleCurrencyAmount pvPayerShortMC =
        methodMC.presentValue(SWAPTION_SHORT_PAYER, EUR, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - Monte Carlo",
        -pvPayerLongMC.getAmount(EUR),
        pvPayerShortMC.getAmount(EUR),
        TOLERANCE_PV);
    final MultipleCurrencyAmount pvReceiverLongMC =
        methodMC.presentValue(SWAPTION_LONG_RECEIVER, EUR, HW_MULTICURVES);
    final MultipleCurrencyAmount pvSwap = SWAP_RECEIVER.accept(PVDC, MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - Monte Carlo - payer/receiver/swap parity",
        pvReceiverLongMC.getAmount(EUR) + pvPayerShortMC.getAmount(EUR),
        pvSwap.getAmount(EUR),
        1.0E+5);
  }

  @Test
  /** Tests the Hull-White parameters sensitivity for the explicit formula. */
  public void presentValueHullWhiteSensitivityExplicit() {
    final double[] hwSensitivity =
        METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final int nbVolatility = HW_PARAMETERS.getVolatility().length;
    final double shiftVol = 1.0E-6;
    final double[] volatilityBumped = new double[nbVolatility];
    System.arraycopy(HW_PARAMETERS.getVolatility(), 0, volatilityBumped, 0, nbVolatility);
    final double[] volatilityTime = new double[nbVolatility - 1];
    System.arraycopy(HW_PARAMETERS.getVolatilityTime(), 1, volatilityTime, 0, nbVolatility - 1);
    final double[] pvBumpedPlus = new double[nbVolatility];
    final double[] pvBumpedMinus = new double[nbVolatility];
    final HullWhiteOneFactorPiecewiseConstantParameters parametersBumped =
        new HullWhiteOneFactorPiecewiseConstantParameters(
            HW_PARAMETERS.getMeanReversion(), volatilityBumped, volatilityTime);
    final HullWhiteOneFactorProviderDiscount bundleBumped =
        new HullWhiteOneFactorProviderDiscount(MULTICURVES, parametersBumped, EUR);
    for (int loopvol = 0; loopvol < nbVolatility; loopvol++) {
      volatilityBumped[loopvol] += shiftVol;
      parametersBumped.setVolatility(volatilityBumped);
      pvBumpedPlus[loopvol] =
          METHOD_HW.presentValue(SWAPTION_LONG_PAYER, bundleBumped).getAmount(EUR);
      volatilityBumped[loopvol] -= 2 * shiftVol;
      parametersBumped.setVolatility(volatilityBumped);
      pvBumpedMinus[loopvol] =
          METHOD_HW.presentValue(SWAPTION_LONG_PAYER, bundleBumped).getAmount(EUR);
      assertEquals(
          "Swaption - Hull-White sensitivity adjoint: derivative "
              + loopvol
              + " - difference:"
              + ((pvBumpedPlus[loopvol] - pvBumpedMinus[loopvol]) / (2 * shiftVol)
                  - hwSensitivity[loopvol]),
          (pvBumpedPlus[loopvol] - pvBumpedMinus[loopvol]) / (2 * shiftVol),
          hwSensitivity[loopvol],
          TOLERANCE_PV_DELTA);
      volatilityBumped[loopvol] = HW_PARAMETERS.getVolatility()[loopvol];
    }
  }

  @Test
  /** Tests long/short parity. */
  public void presentValueHullWhiteSensitivitylongShortParityExplicit() {
    final double[] pvhwsLong =
        METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final double[] pvhwsShort =
        METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_SHORT_PAYER, HW_MULTICURVES);
    for (int loophw = 0; loophw < pvhwsLong.length; loophw++) {
      assertEquals(
          "Swaption physical - Hull-White - presentValueHullWhiteSensitivity - long/short parity",
          pvhwsLong[loophw],
          -pvhwsShort[loophw],
          TOLERANCE_PV_DELTA);
    }
  }

  @Test
  /** Tests payer/receiver/swap parity. */
  public void presentValueHullWhiteSensitivitypayerReceiverParityExplicit() {
    final double[] pvhwsReceiverLong =
        METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_RECEIVER, HW_MULTICURVES);
    final double[] pvhwsPayerShort =
        METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_SHORT_PAYER, HW_MULTICURVES);
    for (int loophw = 0; loophw < pvhwsReceiverLong.length; loophw++) {
      assertEquals(
          "Swaption physical - Hull-White - present value - payer/receiver/swap parity",
          0,
          pvhwsReceiverLong[loophw] + pvhwsPayerShort[loophw],
          TOLERANCE_PV_DELTA);
    }
  }

  @Test
  /** Tests present value curve sensitivity when the valuation date is on trade date. */
  public void presentValueCurveSensitivity() {
    final MultipleCurrencyParameterSensitivity pvpsExact =
        PS_HW_C.calculateSensitivity(
            SWAPTION_SHORT_RECEIVER,
            HW_MULTICURVES,
            HW_MULTICURVES.getMulticurveProvider().getAllNames());
    final MultipleCurrencyParameterSensitivity pvpsFD =
        PS_HW_FDC.calculateSensitivity(SWAPTION_SHORT_RECEIVER, HW_MULTICURVES);
    AssertSensivityObjects.assertEquals(
        "SwaptionPhysicalFixedIborSABRMethod: presentValueCurveSensitivity ",
        pvpsExact,
        pvpsFD,
        TOLERANCE_PV_DELTA);
  }

  @Test(enabled = false)
  /** Tests present value curve sensitivity when the valuation date is on trade date. */
  public void presentValueCurveSensitivityStability() {
    // 5Yx5Y
    final MultipleCurrencyParameterSensitivity pvpsExact =
        PS_HW_C.calculateSensitivity(
            SWAPTION_SHORT_RECEIVER,
            HW_MULTICURVES,
            HW_MULTICURVES.getMulticurveProvider().getAllNames());
    final double derivativeExact = pvpsExact.totalSensitivity(MULTICURVES.getFxRates(), EUR);
    final double startingShift = 1.0E-4;
    final double ratio = Math.sqrt(2.0);
    final int nbShift = 55;
    final double[] eps = new double[nbShift + 1];
    final double[] derivative_FD = new double[nbShift];
    final double[] diff = new double[nbShift];
    eps[0] = startingShift;
    for (int loopshift = 0; loopshift < nbShift; loopshift++) {
      final ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator fdShift =
          new ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator(PVHWC, eps[loopshift]);
      final MultipleCurrencyParameterSensitivity pvpsFD =
          fdShift.calculateSensitivity(SWAPTION_SHORT_RECEIVER, HW_MULTICURVES);
      derivative_FD[loopshift] = pvpsFD.totalSensitivity(MULTICURVES.getFxRates(), EUR);
      diff[loopshift] = derivative_FD[loopshift] - derivativeExact;
      eps[loopshift + 1] = eps[loopshift] / ratio;
    }
    // 1Mx5Y
    final Period expirationPeriod =
        Period.ofDays(
            1); // Period.ofDays(1); Period.ofDays(7); Period.ofMonths(1); Period.ofYears(1);
    // Period.ofYears(10);
    final ZonedDateTime expiryDateExp =
        ScheduleCalculator.getAdjustedDate(REFERENCE_DATE, expirationPeriod, EURIBOR6M, CALENDAR);
    final ZonedDateTime settlementDateExp =
        ScheduleCalculator.getAdjustedDate(expiryDateExp, SPOT_LAG, CALENDAR);
    final double ATM = 0.0151; //  1W: 1.52% - 1M: 1.52% - 1Y: 1.51% - 10Y: 1.51%
    final SwapFixedIborDefinition swapExpx5YDefinition =
        SwapFixedIborDefinition.from(
            settlementDateExp, SWAP_TENOR, EUR1YEURIBOR6M, NOTIONAL, ATM, !FIXED_IS_PAYER);
    final SwaptionPhysicalFixedIborDefinition swaptionExpx5YDefinition =
        SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, swapExpx5YDefinition, !IS_LONG);
    final SwaptionPhysicalFixedIbor swaptionExpx5Y =
        swaptionExpx5YDefinition.toDerivative(REFERENCE_DATE);
    //    final double forward = swaptionExpx5Y.getUnderlyingSwap().accept(PRDC, MULTICURVES);
    final MultipleCurrencyParameterSensitivity pvpsExactExp =
        PS_HW_C.calculateSensitivity(
            swaptionExpx5Y, HW_MULTICURVES, HW_MULTICURVES.getMulticurveProvider().getAllNames());
    final double derivativeExactExp = pvpsExactExp.totalSensitivity(MULTICURVES.getFxRates(), EUR);
    final double[] derivative_FDExp = new double[nbShift];
    final double[] diffExp = new double[nbShift];
    for (int loopshift = 0; loopshift < nbShift; loopshift++) {
      final ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator fdShift =
          new ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator(PVHWC, eps[loopshift]);
      final MultipleCurrencyParameterSensitivity pvpsFD =
          fdShift.calculateSensitivity(swaptionExpx5Y, HW_MULTICURVES);
      derivative_FDExp[loopshift] = pvpsFD.totalSensitivity(MULTICURVES.getFxRates(), EUR);
      diffExp[loopshift] = derivative_FDExp[loopshift] - derivativeExactExp;
    }
    //    int t = 0;
    //    t++;
  }

  @Test
  /** Tests long/short parity. */
  public void presentValueCurveSensitivityLongShortParityExplicit() {
    final MultipleCurrencyMulticurveSensitivity pvhwsLong =
        METHOD_HW.presentValueCurveSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyMulticurveSensitivity pvhwsShort =
        METHOD_HW.presentValueCurveSensitivity(SWAPTION_SHORT_PAYER, HW_MULTICURVES);
    AssertSensivityObjects.assertEquals(
        "Swaption physical - Hull-White - presentValueCurveSensitivity - long/short parity",
        pvhwsLong,
        pvhwsShort.multipliedBy(-1.0),
        TOLERANCE_PV_DELTA);
  }

  @Test
  /** Tests payer/receiver/swap parity. */
  public void presentValueCurveSensitivityPayerReceiverParityExplicit() {
    final MultipleCurrencyMulticurveSensitivity pvhwsReceiverLong =
        METHOD_HW.presentValueCurveSensitivity(SWAPTION_LONG_RECEIVER, HW_MULTICURVES);
    final MultipleCurrencyMulticurveSensitivity pvhwsPayerShort =
        METHOD_HW.presentValueCurveSensitivity(SWAPTION_SHORT_PAYER, HW_MULTICURVES);
    final MultipleCurrencyMulticurveSensitivity pvSwap = SWAP_RECEIVER.accept(PVCSDC, MULTICURVES);
    AssertSensivityObjects.assertEquals(
        "Swaption physical - Hull-White - presentValueCurveSensitivity - payer/receiver/swap parity",
        pvSwap.cleaned(TOLERANCE_PV_DELTA),
        pvhwsReceiverLong.plus(pvhwsPayerShort).cleaned(TOLERANCE_PV_DELTA),
        TOLERANCE_PV_DELTA);
  }

  @Test
  /** Tests the curve sensitivity in Monte Carlo approach. */
  public void presentValueCurveSensitivityMonteCarlo() {
    final double toleranceDelta = 1.0E+6; // 100 USD by bp
    final MultipleCurrencyMulticurveSensitivity pvcsExplicit =
        METHOD_HW
            .presentValueCurveSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES)
            .cleaned(TOLERANCE_PV_DELTA);
    final HullWhiteMonteCarloMethod methodMC =
        new HullWhiteMonteCarloMethod(
            new NormalRandomNumberGenerator(0.0, 1.0, new MersenneTwister()), NB_PATH);
    final MultipleCurrencyMulticurveSensitivity pvcsMC =
        methodMC
            .presentValueCurveSensitivity(SWAPTION_LONG_PAYER, EUR, HW_MULTICURVES)
            .cleaned(TOLERANCE_PV_DELTA);
    AssertSensivityObjects.assertEquals(
        "Swaption physical - Hull-White - presentValueCurveSensitivity - payer/receiver/swap parity",
        pvcsExplicit,
        pvcsMC,
        toleranceDelta);
  }

  @Test(enabled = false)
  /** Tests of performance. "enabled = false" for the standard testing. */
  public void performance() {
    long startTime, endTime;
    final int nbTest = 1000;
    MultipleCurrencyAmount pvPayerLongExplicit = MultipleCurrencyAmount.of(EUR, 0.0);
    MultipleCurrencyAmount pvPayerLongIntegration = MultipleCurrencyAmount.of(EUR, 0.0);
    MultipleCurrencyAmount pvPayerLongApproximation = MultipleCurrencyAmount.of(EUR, 0.0);
    @SuppressWarnings("unused")
    MultipleCurrencyAmount pvPayerLongMC = MultipleCurrencyAmount.of(EUR, 0.0);
    double[] pvhws =
        METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    MultipleCurrencyMulticurveSensitivity pvcs =
        METHOD_HW.presentValueCurveSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);

    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvPayerLongExplicit = METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest + " pv swaption Hull-White explicit method: " + (endTime - startTime) + " ms");
    // Performance note: HW price: 19-Nov-2012: On Mac Pro 3.2 GHz Quad-Core Intel Xeon: 380 ms for
    // 10000 swaptions.
    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvhws = METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " HW sensitivity swaption Hull-White explicit method: "
            + (endTime - startTime)
            + " ms");
    // Performance note: HW sensitivity (3): 19-Nov-2012: On Mac Pro 3.2 GHz Quad-Core Intel Xeon:
    // 430 ms for 10000 swaptions.
    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvcs = METHOD_HW.presentValueCurveSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " curve sensitivity swaption Hull-White explicit method: "
            + (endTime - startTime)
            + " ms");
    // Performance note: curve sensitivity (40): 19-Nov-2012: On Mac Pro 3.2 GHz Quad-Core Intel
    // Xeon: 855 ms for 10000 swaptions.
    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvhws = METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
      pvcs = METHOD_HW.presentValueCurveSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
      pvhws = METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " price/delta/vega swaption Hull-White explicit method: "
            + (endTime - startTime)
            + " ms");
    // Performance note: present value/delta/vega: 19-Nov-2012: On Mac Pro 3.2 GHz Quad-Core Intel
    // Xeon: 1730 ms for 10000 swaptions.
    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvPayerLongIntegration =
          METHOD_HW_INTEGRATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " swaption Hull-White numerical integration method: "
            + (endTime - startTime)
            + " ms");
    // Performance note: HW numerical integration: 19-Nov-2012: On Mac Pro 3.2 GHz Quad-Core Intel
    // Xeon: 1700 ms for 10000 swaptions.
    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvPayerLongApproximation =
          METHOD_HW_APPROXIMATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest + " swaption Hull-White approximation method: " + (endTime - startTime) + " ms");
    // Performance note: HW approximation: 19-Nov-2012: On Mac Pro 3.2 GHz Quad-Core Intel Xeon: 250
    // ms for 10000 swaptions.

    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvPayerLongMC = METHOD_HW_MONTECARLO.presentValue(SWAPTION_LONG_PAYER, EUR, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " swaption Hull-White Monte Carlo method ("
            + NB_PATH
            + " paths): "
            + (endTime - startTime)
            + " ms");
    // Performance note: HW approximation: 18-Aug-11: On Mac Pro 3.2 GHz Quad-Core Intel Xeon: 9200
    // ms for 1000 swaptions (12500 paths).

    final double difference =
        pvPayerLongExplicit.getAmount(EUR) - pvPayerLongIntegration.getAmount(EUR);
    final double difference2 =
        pvPayerLongExplicit.getAmount(EUR) - pvPayerLongApproximation.getAmount(EUR);
    //      double difference3 = pvPayerLongExplicit.getAmount(CUR) - pvPayerLongMC.getAmount(CUR);
    System.out.println("Difference explicit-integration: " + difference);
    System.out.println("Difference explicit-approximation: " + difference2);
    //      System.out.println("Difference explicit-Monte Carlo: " + difference3);
    System.out.println("Curve sensitivity: " + pvcs.toString());
    System.out.println("HW sensitivity: " + Arrays.toString(pvhws));
  }

  @Test(enabled = false)
  /** Tests of performance. "enabled = false" for the standard testing. */
  public void performanceCurveSensitivity() {
    long startTime, endTime;
    final int nbTest = 25;
    MultipleCurrencyAmount pvMC = MultipleCurrencyAmount.of(EUR, 0.0);
    final MultipleCurrencyMulticurveSensitivity pvcsExplicit =
        METHOD_HW.presentValueCurveSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    MultipleCurrencyMulticurveSensitivity pvcsMC = pvcsExplicit;
    final HullWhiteMonteCarloMethod methodMC =
        new HullWhiteMonteCarloMethod(
            new NormalRandomNumberGenerator(0.0, 1.0, new MersenneTwister()), NB_PATH);

    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvMC = METHOD_HW_MONTECARLO.presentValue(SWAPTION_LONG_PAYER, EUR, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " swaption Hull-White Monte Carlo method ("
            + NB_PATH
            + " paths): "
            + (endTime - startTime)
            + " ms / price:"
            + pvMC.toString());
    // Performance note: HW approximation: 03-Dec-2012: On Mac Pro 3.2 GHz Quad-Core Intel Xeon: 250
    // ms for 25 swaptions (12500 paths).
    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvcsMC = methodMC.presentValueCurveSensitivity(SWAPTION_LONG_PAYER, EUR, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " curve sensitivity swaption Hull-White MC method: ("
            + NB_PATH
            + " paths) "
            + (endTime - startTime)
            + " ms / risk:"
            + pvcsMC.toString());
    // Performance note: curve sensitivity (40): 03-Dec-2012: On Mac Pro 3.2 GHz Quad-Core Intel
    // Xeon: 600 ms for 25 swaptions (12500 paths).

  }
}
/** Test the swaps with multiple legs present value and related figures. */
@Test(groups = TestGroup.UNIT)
public class SwapMultilegCalculatorTest {

  private static final MulticurveProviderDiscount MULTICURVES =
      MulticurveProviderDiscountDataSets.createMulticurveEurUsd();

  private static final Calendar TARGET = new MondayToFridayCalendar("TRAGET");
  private static final IndexIborMaster INDEX_MASTER = IndexIborMaster.getInstance();
  private static final IborIndex EURIBOR3M = INDEX_MASTER.getIndex("EURIBOR3M");
  private static final IborIndex EURIBOR6M = INDEX_MASTER.getIndex("EURIBOR6M");
  private static final GeneratorSwapFixedIborMaster SWAP_MASTER =
      GeneratorSwapFixedIborMaster.getInstance();
  private static final GeneratorSwapFixedIbor EUR1YEURIBOR6M =
      SWAP_MASTER.getGenerator("EUR1YEURIBOR6M", TARGET);
  private static final Period ANNUITY_TENOR = Period.ofYears(2);
  private static final Currency EUR = EURIBOR3M.getCurrency();

  private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2013, 3, 20);
  private static final ZonedDateTime SETTLEMENT_DATE = DateUtils.getUTCDate(2013, 10, 16);
  private static final double NOTIONAL = 100000000; // 100 m
  private static final double SPREAD = 0.0010; // 10 bps
  private static final StubType STUB = StubType.SHORT_START;

  // Swap represeting a EUR basis swap: 1 spread leg and 2 Euribor leg.
  private static final boolean IS_PAYER_SPREAD = true;
  private static final ZonedDateTime MATURITY_DATE = SETTLEMENT_DATE.plus(ANNUITY_TENOR);
  private static final int NB_LEGS = 3;

  @SuppressWarnings("rawtypes")
  private static final AnnuityDefinition[] LEGS_DEFINITION = new AnnuityDefinition[NB_LEGS];

  static {
    LEGS_DEFINITION[0] =
        AnnuityDefinitionBuilder.couponFixed(
            EUR,
            SETTLEMENT_DATE,
            MATURITY_DATE,
            EUR1YEURIBOR6M.getFixedLegPeriod(),
            TARGET,
            EUR1YEURIBOR6M.getFixedLegDayCount(),
            EUR1YEURIBOR6M.getBusinessDayConvention(),
            EUR1YEURIBOR6M.isEndOfMonth(),
            NOTIONAL,
            SPREAD,
            IS_PAYER_SPREAD,
            STUB,
            0);
    LEGS_DEFINITION[1] =
        AnnuityDefinitionBuilder.couponIbor(
            SETTLEMENT_DATE,
            MATURITY_DATE,
            EURIBOR3M.getTenor(),
            NOTIONAL,
            EURIBOR3M,
            IS_PAYER_SPREAD,
            EURIBOR3M.getDayCount(),
            EURIBOR3M.getBusinessDayConvention(),
            EURIBOR3M.isEndOfMonth(),
            TARGET,
            STUB,
            0);
    LEGS_DEFINITION[2] =
        AnnuityDefinitionBuilder.couponIbor(
            SETTLEMENT_DATE,
            MATURITY_DATE,
            EURIBOR6M.getTenor(),
            NOTIONAL,
            EURIBOR6M,
            !IS_PAYER_SPREAD,
            EURIBOR6M.getDayCount(),
            EURIBOR6M.getBusinessDayConvention(),
            EURIBOR6M.isEndOfMonth(),
            TARGET,
            STUB,
            0);
  }

  @SuppressWarnings("unchecked")
  private static final SwapMultilegDefinition SWAP_MULTI_LEG_DEFINITION =
      new SwapMultilegDefinition(LEGS_DEFINITION);

  private static final SwapMultileg SWAP_MULTI_LEG =
      SWAP_MULTI_LEG_DEFINITION.toDerivative(REFERENCE_DATE);

  private static final PresentValueDiscountingCalculator PVDC =
      PresentValueDiscountingCalculator.getInstance();
  private static final PresentValueCurveSensitivityDiscountingCalculator PVCSDC =
      PresentValueCurveSensitivityDiscountingCalculator.getInstance();
  private static final ParSpreadMarketQuoteDiscountingCalculator PSMQDC =
      ParSpreadMarketQuoteDiscountingCalculator.getInstance();
  private static final ParSpreadMarketQuoteCurveSensitivityDiscountingCalculator PSMQCSDC =
      ParSpreadMarketQuoteCurveSensitivityDiscountingCalculator.getInstance();
  private static final PresentValueMarketQuoteSensitivityDiscountingCalculator PVMQSC =
      PresentValueMarketQuoteSensitivityDiscountingCalculator.getInstance();
  private static final PresentValueMarketQuoteSensitivityCurveSensitivityDiscountingCalculator
      PVMQSCSC =
          PresentValueMarketQuoteSensitivityCurveSensitivityDiscountingCalculator.getInstance();

  private static final double TOLERANCE_PV = 1.0E-2;
  private static final double TOLERANCE_PV_DELTA = 1.0E-2;
  private static final double TOLERANCE_RATE = 1.0E-8;
  private static final double TOLERANCE_RATE_DELTA = 1.0E-8;

  @Test
  public void presentValueDiscountingCalculator() {
    final MultipleCurrencyAmount pvSwap = SWAP_MULTI_LEG.accept(PVDC, MULTICURVES);
    MultipleCurrencyAmount pvLegs = MultipleCurrencyAmount.of(EUR, 0.0);
    for (int loopleg = 0; loopleg < NB_LEGS; loopleg++) {
      pvLegs = pvLegs.plus(SWAP_MULTI_LEG.getLegs()[loopleg].accept(PVDC, MULTICURVES));
    }
    assertEquals(
        "SwapMultileg: presentValueDiscountingCalculator",
        pvSwap.getAmount(EUR),
        pvLegs.getAmount(EUR),
        TOLERANCE_PV);
  }

  @Test
  public void presentValueCurveSensitivityDiscountingCalculator() {
    final MultipleCurrencyMulticurveSensitivity pvcsSwap =
        SWAP_MULTI_LEG.accept(PVCSDC, MULTICURVES);
    MultipleCurrencyMulticurveSensitivity pvcsLegs =
        SWAP_MULTI_LEG.getLegs()[0].accept(PVCSDC, MULTICURVES);
    for (int loopleg = 1; loopleg < NB_LEGS; loopleg++) {
      pvcsLegs = pvcsLegs.plus(SWAP_MULTI_LEG.getLegs()[loopleg].accept(PVCSDC, MULTICURVES));
    }
    AssertSensitivityObjects.assertEquals(
        "SwapMultileg: presentValueCurveSensitivityDiscountingCalculator",
        pvcsLegs,
        pvcsSwap,
        TOLERANCE_PV_DELTA);
  }

  @Test
  public void parSpreadMarketQuoteDiscountingCalculator() {
    final double psmq = SWAP_MULTI_LEG.accept(PSMQDC, MULTICURVES);
    final double pv =
        -MULTICURVES
            .getFxRates()
            .convert(
                SWAP_MULTI_LEG.accept(PVDC, MULTICURVES), SWAP_MULTI_LEG.getLegs()[0].getCurrency())
            .getAmount();
    final double pvbp = SWAP_MULTI_LEG.getLegs()[0].accept(PVMQSC, MULTICURVES);
    assertEquals(
        "SwapMultileg: parSpreadMarketQuoteDiscountingCalculator", psmq, pv / pvbp, TOLERANCE_RATE);
  }

  @Test
  public void parSpreadMarketQuoteCurveSensitivityDiscountingCalculator() {
    final double pv =
        MULTICURVES
            .getFxRates()
            .convert(
                SWAP_MULTI_LEG.accept(PVDC, MULTICURVES), SWAP_MULTI_LEG.getLegs()[0].getCurrency())
            .getAmount();
    final double pvbp = SWAP_MULTI_LEG.getLegs()[0].accept(PVMQSC, MULTICURVES);
    final MulticurveSensitivity pvcs =
        SWAP_MULTI_LEG
            .accept(PVCSDC, MULTICURVES)
            .converted(EUR, MULTICURVES.getFxRates())
            .getSensitivity(EUR);
    final MulticurveSensitivity pvbpcs = SWAP_MULTI_LEG.getLegs()[0].accept(PVMQSCSC, MULTICURVES);
    final MulticurveSensitivity psmqcsExpected =
        pvcs.multipliedBy(-1.0d / pvbp).plus(pvbpcs.multipliedBy(pv / (pvbp * pvbp))).cleaned();
    final MulticurveSensitivity psmqcs = SWAP_MULTI_LEG.accept(PSMQCSDC, MULTICURVES).cleaned();
    AssertSensitivityObjects.assertEquals(
        "SwapMultileg: presentValueCurveSensitivityDiscountingCalculator",
        psmqcs,
        psmqcsExpected,
        TOLERANCE_RATE_DELTA);
  }
}
/**
 * Tests related to the pricing methods for Ibor coupon in the discounting method with data in
 * MarketBundle.
 */
public class CouponIborDiscountingProviderMethodTest {

  private static final MulticurveProviderDiscount MULTICURVES =
      MulticurveProviderDiscountDataSets.createMulticurveEurUsd();
  private static final IborIndex[] IBOR_INDEXES =
      MulticurveProviderDiscountDataSets.getIndexesIborMulticurveEurUsd();
  private static final IborIndex EURIBOR3M = IBOR_INDEXES[0];
  private static final Currency EUR = EURIBOR3M.getCurrency();
  private static final Calendar CALENDAR = MulticurveProviderDiscountDataSets.getEURCalendar();

  private static final DayCount DAY_COUNT_COUPON =
      DayCountFactory.INSTANCE.getDayCount("Actual/365");
  private static final ZonedDateTime ACCRUAL_START_DATE = DateUtils.getUTCDate(2011, 5, 23);
  private static final ZonedDateTime ACCRUAL_END_DATE = DateUtils.getUTCDate(2011, 8, 22);
  private static final double ACCRUAL_FACTOR =
      DAY_COUNT_COUPON.getDayCountFraction(ACCRUAL_START_DATE, ACCRUAL_END_DATE);
  private static final double NOTIONAL = 1000000; // 1m
  private static final CouponIborDefinition CPN_IBOR_DEFINITION =
      CouponIborDefinition.from(
          ACCRUAL_START_DATE, ACCRUAL_END_DATE, ACCRUAL_FACTOR, NOTIONAL, EURIBOR3M, CALENDAR);

  private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2010, 12, 27);
  private static final CouponIbor CPN_IBOR =
      (CouponIbor) CPN_IBOR_DEFINITION.toDerivative(REFERENCE_DATE);

  private static final CouponIborDiscountingMethod METHOD_CPN_IBOR =
      CouponIborDiscountingMethod.getInstance();
  private static final PresentValueDiscountingCalculator PVDC =
      PresentValueDiscountingCalculator.getInstance();
  private static final PresentValueCurveSensitivityDiscountingCalculator PVCSDC =
      PresentValueCurveSensitivityDiscountingCalculator.getInstance();

  private static final double TOLERANCE_PV = 1.0E-2;
  private static final double TOLERANCE_PV_DELTA = 1.0E+2;

  @Test
  public void presentValueMarketDiscount() {
    final MultipleCurrencyAmount pvComputed = METHOD_CPN_IBOR.presentValue(CPN_IBOR, MULTICURVES);
    final double forward =
        MULTICURVES.getForwardRate(
            EURIBOR3M,
            CPN_IBOR.getFixingPeriodStartTime(),
            CPN_IBOR.getFixingPeriodEndTime(),
            CPN_IBOR.getFixingAccrualFactor());
    final double df =
        MULTICURVES.getDiscountFactor(EURIBOR3M.getCurrency(), CPN_IBOR.getPaymentTime());
    final double pvExpected = NOTIONAL * ACCRUAL_FACTOR * forward * df;
    assertEquals(
        "CouponIborDiscountingMarketMethod: present value",
        pvExpected,
        pvComputed.getAmount(EURIBOR3M.getCurrency()),
        TOLERANCE_PV);
  }

  @Test
  public void presentValueMethodVsCalculator() {
    final MultipleCurrencyAmount pvMethod = METHOD_CPN_IBOR.presentValue(CPN_IBOR, MULTICURVES);
    final MultipleCurrencyAmount pvCalculator = CPN_IBOR.accept(PVDC, MULTICURVES);
    assertEquals(
        "CouponFixedDiscountingMarketMethod: present value",
        pvMethod.getAmount(EUR),
        pvCalculator.getAmount(EUR),
        TOLERANCE_PV);
  }

  // Testing note: the presentValueMarketSensitivity is tested in
  // ParameterSensitivityProviderCalculatorTest

  @Test
  public void presentValueMarketSensitivityMethodVsCalculator() {
    final MultipleCurrencyMulticurveSensitivity pvcsMethod =
        METHOD_CPN_IBOR.presentValueCurveSensitivity(CPN_IBOR, MULTICURVES);
    final MultipleCurrencyMulticurveSensitivity pvcsCalculator =
        CPN_IBOR.accept(PVCSDC, MULTICURVES);
    AssertSensivityObjects.assertEquals(
        "CouponFixedDiscountingMarketMethod: presentValueMarketSensitivity",
        pvcsMethod,
        pvcsCalculator,
        TOLERANCE_PV_DELTA);
  }
}
public class SwaptionPhysicalFixedIborBlackMethodTest {

  private static final MulticurveProviderDiscount MULTICURVES =
      MulticurveProviderDiscountDataSets.createMulticurveEurUsd();
  private static final IborIndex EURIBOR6M =
      MulticurveProviderDiscountDataSets.getIndexesIborMulticurveEurUsd()[1];
  private static final Calendar CALENDAR = MulticurveProviderDiscountDataSets.getEURCalendar();
  private static final Currency EUR = EURIBOR6M.getCurrency();
  // Data
  private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2012, 1, 10);
  private static final GeneratorSwapFixedIborMaster GENERATOR_SWAP_MASTER =
      GeneratorSwapFixedIborMaster.getInstance();
  private static final GeneratorSwapFixedIbor GENERATOR_EUR1YEURIBOR6M =
      GENERATOR_SWAP_MASTER.getGenerator("EUR1YEURIBOR6M", CALENDAR);

  private static final BlackFlatSwaptionParameters BLACK = BlackDataSets.createBlackSwaptionEUR6();
  private static final BlackSwaptionFlatProviderDiscount BLACK_MULTICURVES =
      new BlackSwaptionFlatProviderDiscount(MULTICURVES, BLACK);
  // Swaption
  private static final Period EXPIRY_TENOR = Period.ofMonths(26); // To be between nodes.
  private static final ZonedDateTime EXPIRY_DATE =
      ScheduleCalculator.getAdjustedDate(
          REFERENCE_DATE,
          EXPIRY_TENOR,
          GENERATOR_EUR1YEURIBOR6M.getBusinessDayConvention(),
          CALENDAR,
          GENERATOR_EUR1YEURIBOR6M.isEndOfMonth());
  private static final ZonedDateTime SETTLE_DATE =
      ScheduleCalculator.getAdjustedDate(
          EXPIRY_DATE, GENERATOR_EUR1YEURIBOR6M.getSpotLag(), CALENDAR);
  private static final int SWAP_TENOR_YEAR = 5;
  private static final Period SWAP_TENOR = Period.ofYears(SWAP_TENOR_YEAR);
  private static final double NOTIONAL = 123456789.0;
  private static final double RATE = 0.02;
  private static final SwapFixedIborDefinition SWAP_DEFINITION_REC =
      SwapFixedIborDefinition.from(
          SETTLE_DATE, SWAP_TENOR, GENERATOR_EUR1YEURIBOR6M, NOTIONAL, RATE, false);
  private static final SwaptionPhysicalFixedIborDefinition SWAPTION_DEFINITION_LONG_REC =
      SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, SWAP_DEFINITION_REC, true);
  private static final SwaptionPhysicalFixedIbor SWAPTION_LONG_REC =
      SWAPTION_DEFINITION_LONG_REC.toDerivative(REFERENCE_DATE);
  // Method - calculator
  private static final double TOLERANCE_PV = 1.0E-2;
  private static final double TOLERANCE_PV_DELTA = 1.0E+2;
  // Testing note: Sensitivity is for a movement of 1. 1E+2 = 1 cent for a 1 bp move.

  private static final SwaptionPhysicalFixedIborBlackMethod METHOD_BLACK =
      SwaptionPhysicalFixedIborBlackMethod.getInstance();
  private static final SwapFixedCouponDiscountingMethod METHOD_SWAP =
      SwapFixedCouponDiscountingMethod.getInstance();

  private static final ParRateDiscountingCalculator PRDC =
      ParRateDiscountingCalculator.getInstance();
  private static final PresentValueDiscountingCalculator PVDC =
      PresentValueDiscountingCalculator.getInstance();

  private static final PresentValueBlackSwaptionCalculator PVBSC =
      PresentValueBlackSwaptionCalculator.getInstance();
  private static final PresentValueCurveSensitivityBlackSwaptionCalculator PVCSBSC =
      PresentValueCurveSensitivityBlackSwaptionCalculator.getInstance();
  private static final PresentValueBlackSensitivityBlackSwaptionCalculator PVBSSBSC =
      PresentValueBlackSensitivityBlackSwaptionCalculator.getInstance();

  private static final double SHIFT = 1.0E-6;
  private static final ParameterSensitivityParameterCalculator<BlackSwaptionFlatProviderInterface>
      PS_BS_C = new ParameterSensitivityParameterCalculator<>(PVCSBSC);
  private static final ParameterSensitivityBlackSwaptionDiscountInterpolatedFDCalculator PS_BS_FDC =
      new ParameterSensitivityBlackSwaptionDiscountInterpolatedFDCalculator(PVBSC, SHIFT);

  private static final BlackSwaptionSensitivityNodeCalculator BSSNC =
      new BlackSwaptionSensitivityNodeCalculator();

  @Test
  public void presentValue() {
    final MultipleCurrencyAmount pvMethod =
        METHOD_BLACK.presentValue(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final double forward = SWAPTION_LONG_REC.getUnderlyingSwap().accept(PRDC, MULTICURVES);
    final double pvbp =
        METHOD_SWAP.presentValueBasisPoint(SWAPTION_LONG_REC.getUnderlyingSwap(), MULTICURVES);
    final double volatility =
        BLACK.getVolatility(
            SWAPTION_LONG_REC.getTimeToExpiry(), SWAPTION_LONG_REC.getMaturityTime());
    final BlackPriceFunction blackFunction = new BlackPriceFunction();
    final BlackFunctionData dataBlack = new BlackFunctionData(forward, pvbp, volatility);
    final Function1D<BlackFunctionData, Double> func =
        blackFunction.getPriceFunction(SWAPTION_LONG_REC);
    final double pvExpected = func.evaluate(dataBlack);
    assertEquals(
        "Swaption Black method: present value", pvExpected, pvMethod.getAmount(EUR), TOLERANCE_PV);
  }

  @Test
  /** Tests the payer/receiver parity for swaptions present value. */
  public void presentValuePayerReceiverParity() {
    final SwapFixedIborDefinition swapDefinitionPay =
        SwapFixedIborDefinition.from(
            SETTLE_DATE, SWAP_TENOR, GENERATOR_EUR1YEURIBOR6M, NOTIONAL, RATE, true);
    final SwaptionPhysicalFixedIborDefinition swaptionDefinitionShortPayer =
        SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, swapDefinitionPay, false);
    final SwaptionPhysicalFixedIbor swaptionShortPayer =
        swaptionDefinitionShortPayer.toDerivative(REFERENCE_DATE);
    final InstrumentDerivative swapRec = SWAP_DEFINITION_REC.toDerivative(REFERENCE_DATE);
    final MultipleCurrencyAmount pvLR =
        METHOD_BLACK.presentValue(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final MultipleCurrencyAmount pvSP =
        METHOD_BLACK.presentValue(swaptionShortPayer, BLACK_MULTICURVES);
    final MultipleCurrencyAmount pvSwap = swapRec.accept(PVDC, MULTICURVES);
    assertEquals(
        "Swaption Black method: present value",
        pvSwap.getAmount(EUR),
        pvLR.getAmount(EUR) + pvSP.getAmount(EUR),
        TOLERANCE_PV);
  }

  @Test
  /** Compare the method figures to the Calculator figures. */
  public void presentValueMethodVsCalculator() {
    final MultipleCurrencyAmount pvMethod =
        METHOD_BLACK.presentValue(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final MultipleCurrencyAmount pvCalculator = SWAPTION_LONG_REC.accept(PVBSC, BLACK_MULTICURVES);
    assertEquals(
        "Swaption Black method: present value",
        pvCalculator.getAmount(EUR),
        pvMethod.getAmount(EUR),
        TOLERANCE_PV);
  }

  @Test
  /** Tests the curve sensitivity for the explicit formula. */
  public void presentValueCurveSensitivity() {
    final MultipleCurrencyParameterSensitivity pvpsExact =
        PS_BS_C.calculateSensitivity(
            SWAPTION_LONG_REC,
            BLACK_MULTICURVES,
            BLACK_MULTICURVES.getMulticurveProvider().getAllNames());
    final MultipleCurrencyParameterSensitivity pvpsFD =
        PS_BS_FDC.calculateSensitivity(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    AssertSensivityObjects.assertEquals(
        "Swaption Black method: presentValueCurveSensitivity ",
        pvpsExact,
        pvpsFD,
        TOLERANCE_PV_DELTA);
  }

  @Test
  /** Compare the method figures to the Calculator figures. */
  public void presentValueCurveSensitivityMethodVsCalculator() {
    final MultipleCurrencyMulticurveSensitivity pvcsMethod =
        METHOD_BLACK.presentValueCurveSensitivity(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final MultipleCurrencyMulticurveSensitivity pvcsCalculator =
        SWAPTION_LONG_REC.accept(PVCSBSC, BLACK_MULTICURVES);
    AssertSensivityObjects.assertEquals(
        "Swaption Black method: present value", pvcsMethod, pvcsCalculator, TOLERANCE_PV_DELTA);
  }

  @Test
  /** Tests the Black volatility sensitivity (vega). */
  public void presentValueBlackSensitivity() {
    final double shift = 1.0E-6;
    final PresentValueBlackSwaptionSensitivity pvbvs =
        METHOD_BLACK.presentValueBlackSensitivity(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final BlackFlatSwaptionParameters BlackP = BlackDataSets.createBlackSwaptionEUR6Shift(shift);
    final BlackSwaptionFlatProviderDiscount curvesBlackP =
        new BlackSwaptionFlatProviderDiscount(MULTICURVES, BlackP);
    final MultipleCurrencyAmount pvP = METHOD_BLACK.presentValue(SWAPTION_LONG_REC, curvesBlackP);
    final BlackFlatSwaptionParameters BlackM = BlackDataSets.createBlackSwaptionEUR6Shift(-shift);
    final BlackSwaptionFlatProviderDiscount curvesBlackM =
        new BlackSwaptionFlatProviderDiscount(MULTICURVES, BlackM);
    final MultipleCurrencyAmount pvM = METHOD_BLACK.presentValue(SWAPTION_LONG_REC, curvesBlackM);
    final DoublesPair point =
        new DoublesPair(SWAPTION_LONG_REC.getTimeToExpiry(), SWAPTION_LONG_REC.getMaturityTime());
    assertEquals(
        "Swaption Black method: present value volatility sensitivity",
        (pvP.getAmount(EUR) - pvM.getAmount(EUR)) / (2 * shift),
        pvbvs.getSensitivity().getMap().get(point),
        TOLERANCE_PV_DELTA);
  }

  @Test
  /** Tests the Black volatility sensitivity (vega). */
  public void presentValueBlackSensitivityMethodVsCalculator() {
    final PresentValueBlackSwaptionSensitivity pvbsMethod =
        METHOD_BLACK.presentValueBlackSensitivity(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final PresentValueBlackSwaptionSensitivity pvbsCalculator =
        SWAPTION_LONG_REC.accept(PVBSSBSC, BLACK_MULTICURVES);
    assertEquals("Swaption Black method: present value", pvbsMethod, pvbsCalculator);
  }

  @Test
  /** Tests the Black volatility sensitivity (vega). */
  public void presentValueBlackNodeSensitivity() {
    final double shift = 1.0E-6;
    final PresentValueBlackSwaptionSensitivity pvbvs =
        METHOD_BLACK.presentValueBlackSensitivity(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final PresentValueBlackSwaptionSensitivity pvbns =
        BSSNC.calculateNodeSensitivities(pvbvs, BLACK);
    final double[] x =
        ((InterpolatedDoublesSurface) BLACK.getVolatilitySurface()).getXDataAsPrimitive();
    final double[] y =
        ((InterpolatedDoublesSurface) BLACK.getVolatilitySurface()).getYDataAsPrimitive();
    for (int loopindex = 0; loopindex < x.length; loopindex++) {
      final BlackFlatSwaptionParameters BlackP =
          BlackDataSets.createBlackSwaptionEUR6Shift(loopindex, shift);
      final BlackSwaptionFlatProviderDiscount curvesBlackP =
          new BlackSwaptionFlatProviderDiscount(MULTICURVES, BlackP);
      final MultipleCurrencyAmount pvP = METHOD_BLACK.presentValue(SWAPTION_LONG_REC, curvesBlackP);
      final BlackFlatSwaptionParameters BlackM =
          BlackDataSets.createBlackSwaptionEUR6Shift(loopindex, -shift);
      final BlackSwaptionFlatProviderDiscount curvesBlackM =
          new BlackSwaptionFlatProviderDiscount(MULTICURVES, BlackM);
      final MultipleCurrencyAmount pvM = METHOD_BLACK.presentValue(SWAPTION_LONG_REC, curvesBlackM);
      assertEquals(
          "Swaption Black method: present value volatility sensitivity",
          (pvP.getAmount(EUR) - pvM.getAmount(EUR)) / (2 * shift),
          pvbns.getSensitivity().getMap().get(new DoublesPair(x[loopindex], y[loopindex])),
          TOLERANCE_PV_DELTA);
    }
  }
}
/** Build of curve in several blocks with relevant Jacobian matrices. */
public class MulticurveBuildingDiscountingDiscountAUDTest {

  private static final Interpolator1D INTERPOLATOR_LINEAR =
      CombinedInterpolatorExtrapolatorFactory.getInterpolator(
          Interpolator1DFactory.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 Calendar SYD = new MondayToFridayCalendar("SYD");
  private static final Currency AUD = Currency.AUD;
  private static final FXMatrix FX_MATRIX = new FXMatrix(AUD);

  private static final double NOTIONAL = 1.0;

  private static final GeneratorSwapFixedON GENERATOR_OIS_AUD =
      GeneratorSwapFixedONMaster.getInstance().getGenerator("AUD1YRBAON", SYD);
  private static final IndexON INDEX_ON_AUD = GENERATOR_OIS_AUD.getIndex();
  private static final GeneratorDepositON GENERATOR_DEPOSIT_ON_AUD =
      new GeneratorDepositON("AUD Deposit ON", AUD, SYD, INDEX_ON_AUD.getDayCount());
  private static final GeneratorSwapFixedIborMaster GENERATOR_SWAP_MASTER =
      GeneratorSwapFixedIborMaster.getInstance();
  private static final GeneratorSwapIborIborMaster GENERATOR_BASIS_MASTER =
      GeneratorSwapIborIborMaster.getInstance();
  private static final GeneratorSwapFixedIbor AUD3MBBSW3M =
      GENERATOR_SWAP_MASTER.getGenerator("AUD3MBBSW3M", SYD);
  private static final GeneratorSwapFixedIbor AUD6MBBSW6M =
      GENERATOR_SWAP_MASTER.getGenerator("AUD6MBBSW6M", SYD);
  private static final GeneratorSwapIborIbor AUDBBSW3MBBSW6M =
      GENERATOR_BASIS_MASTER.getGenerator("AUDBBSW3MBBSW6M", SYD);
  private static final IborIndex AUDBB3M = AUD3MBBSW3M.getIborIndex();
  private static final IborIndex AUDBB6M = AUD6MBBSW6M.getIborIndex();
  private static final GeneratorFRA GENERATOR_FRA_3M =
      new GeneratorFRA("GENERATOR_FRA_3M", AUDBB3M, SYD);
  private static final GeneratorDepositIbor GENERATOR_AUDBB3M =
      new GeneratorDepositIbor("GENERATOR_AUDBB3M", AUDBB3M, SYD);
  private static final GeneratorDepositIbor GENERATOR_AUDBB6M =
      new GeneratorDepositIbor("GENERATOR_AUDBB6M", AUDBB6M, SYD);

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

  private static final ZonedDateTimeDoubleTimeSeries TS_EMPTY =
      ImmutableZonedDateTimeDoubleTimeSeries.ofEmptyUTC();
  private static final ZonedDateTimeDoubleTimeSeries TS_ON_AUD_WITH_TODAY =
      ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
          new ZonedDateTime[] {
            DateUtils.getUTCDate(2011, 9, 27), DateUtils.getUTCDate(2011, 9, 28)
          },
          new double[] {0.07, 0.08});
  private static final ZonedDateTimeDoubleTimeSeries TS_ON_AUD_WITHOUT_TODAY =
      ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
          new ZonedDateTime[] {
            DateUtils.getUTCDate(2011, 9, 27), DateUtils.getUTCDate(2011, 9, 28)
          },
          new double[] {0.07, 0.08});
  private static final ZonedDateTimeDoubleTimeSeries[] TS_FIXED_OIS_AUD_WITH_TODAY =
      new ZonedDateTimeDoubleTimeSeries[] {TS_EMPTY, TS_ON_AUD_WITH_TODAY};
  private static final ZonedDateTimeDoubleTimeSeries[] TS_FIXED_OIS_AUD_WITHOUT_TODAY =
      new ZonedDateTimeDoubleTimeSeries[] {TS_EMPTY, TS_ON_AUD_WITHOUT_TODAY};

  private static final ZonedDateTimeDoubleTimeSeries TS_IBOR_AUD3M_WITH_TODAY =
      ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
          new ZonedDateTime[] {
            DateUtils.getUTCDate(2011, 9, 27), DateUtils.getUTCDate(2011, 9, 28)
          },
          new double[] {0.0035, 0.0036});
  private static final ZonedDateTimeDoubleTimeSeries TS_IBOR_AUD3M_WITHOUT_TODAY =
      ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
          new ZonedDateTime[] {DateUtils.getUTCDate(2011, 9, 27)}, new double[] {0.0035});
  private static final ZonedDateTimeDoubleTimeSeries TS_IBOR_AUD6M_WITH_TODAY =
      ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
          new ZonedDateTime[] {
            DateUtils.getUTCDate(2011, 9, 27), DateUtils.getUTCDate(2011, 9, 28)
          },
          new double[] {0.0035, 0.0036});
  private static final ZonedDateTimeDoubleTimeSeries TS_IBOR_AUD6M_WITHOUT_TODAY =
      ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
          new ZonedDateTime[] {DateUtils.getUTCDate(2011, 9, 27)}, new double[] {0.0035});

  private static final ZonedDateTimeDoubleTimeSeries[] TS_FIXED_IBOR_AUD3M_WITH_TODAY =
      new ZonedDateTimeDoubleTimeSeries[] {TS_IBOR_AUD3M_WITH_TODAY};
  private static final ZonedDateTimeDoubleTimeSeries[] TS_FIXED_IBOR_AUD3M_WITHOUT_TODAY =
      new ZonedDateTimeDoubleTimeSeries[] {TS_IBOR_AUD3M_WITHOUT_TODAY};
  private static final ZonedDateTimeDoubleTimeSeries[] TS_FIXED_IBOR_AUD3M6M_WITH_TODAY =
      new ZonedDateTimeDoubleTimeSeries[] {TS_IBOR_AUD3M_WITH_TODAY, TS_IBOR_AUD6M_WITH_TODAY};
  private static final ZonedDateTimeDoubleTimeSeries[] TS_FIXED_IBOR_AUD3M6M_WITHOUT_TODAY =
      new ZonedDateTimeDoubleTimeSeries[] {
        TS_IBOR_AUD3M_WITHOUT_TODAY, TS_IBOR_AUD6M_WITHOUT_TODAY
      };

  private static final String CURVE_NAME_DSC_AUD = "AUD Dsc";
  private static final String CURVE_NAME_FWD3_AUD = "AUD Fwd 3M";
  private static final String CURVE_NAME_FWD6_AUD = "AUD Fwd 6M";

  //  /** Simplified versions for the note */
  //  /** Market values for the dsc USD curve */
  //  private static final double[] DSC_AUD_MARKET_QUOTES = new double[] {0.0400, 0.0400, 0.0400,
  // 0.0400, 0.0400};
  //  /** Generators for the dsc USD curve */
  //  private static final GeneratorInstrument[] DSC_USD_GENERATORS = new GeneratorInstrument[]
  // {GENERATOR_DEPOSIT_ON_AUD, GENERATOR_OIS_AUD, GENERATOR_OIS_AUD, GENERATOR_OIS_AUD,
  // GENERATOR_OIS_AUD};
  //  /** Tenors for the dsc USD curve */
  //  private static final Period[] DSC_AUD_TENOR = new Period[] {Period.ofDays(0),
  // Period.ofMonths(1), Period.ofMonths(6), Period.ofYears(1), Period.ofYears(5)};
  //
  //  /** Market values for the Fwd 3M USD curve */
  //  private static final double[] FWD3_AUD_MARKET_QUOTES = new double[] {0.0420, 0.0420, 0.0470,
  // 0.0020};
  //  /** Generators for the Fwd 3M USD curve */
  //  private static final GeneratorInstrument[] FWD3_AUD_GENERATORS = new GeneratorInstrument[]
  // {GENERATOR_AUDBB3M, GENERATOR_FRA_3M, AUD3MBBSW3M, AUDBBSW3MBBSW6M};
  //  /** Tenors for the Fwd 3M USD curve */
  //  private static final Period[] FWD3_AUD_TENOR = new Period[] {Period.ofMonths(0),
  // Period.ofMonths(6), Period.ofYears(1), Period.ofYears(5)};
  //
  //  /** Market values for the Fwd 3M USD curve */
  //  private static final double[] FWD6_AUD_MARKET_QUOTES = new double[] {0.0440, 0.0020, 0.0560};
  //  /** Generators for the Fwd 3M USD curve */
  //  private static final GeneratorInstrument[] FWD6_AUD_GENERATORS = new GeneratorInstrument[]
  // {GENERATOR_AUDBB6M, AUDBBSW3MBBSW6M, AUD6MBBSW6M};
  //  /** Tenors for the Fwd 3M USD curve */
  //  private static final Period[] FWD6_AUD_TENOR = new Period[] {Period.ofMonths(0),
  // Period.ofYears(1), Period.ofYears(5)};

  /** Market values for the dsc USD curve */
  private static final double[] DSC_AUD_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_AUD,
        GENERATOR_OIS_AUD,
        GENERATOR_OIS_AUD,
        GENERATOR_OIS_AUD,
        GENERATOR_OIS_AUD,
        GENERATOR_OIS_AUD,
        GENERATOR_OIS_AUD,
        GENERATOR_OIS_AUD,
        GENERATOR_OIS_AUD,
        GENERATOR_OIS_AUD,
        GENERATOR_OIS_AUD,
        GENERATOR_OIS_AUD
      };
  /** Tenors for the dsc USD curve */
  private static final Period[] DSC_AUD_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_AUD_ATTR =
      new GeneratorAttributeIR[DSC_AUD_TENOR.length];

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

  /** Market values for the Fwd 3M USD curve */
  private static final double[] FWD3_AUD_MARKET_QUOTES =
      new double[] {0.0420, 0.0420, 0.0420, 0.0420, 0.0430, 0.0470, 0.0020, 0.0020, 0.0020};
  /** Generators for the Fwd 3M USD curve */
  private static final GeneratorInstrument<? extends GeneratorAttribute>[] FWD3_AUD_GENERATORS =
      new GeneratorInstrument<?>[] {
        GENERATOR_AUDBB3M,
        GENERATOR_FRA_3M,
        GENERATOR_FRA_3M,
        AUD3MBBSW3M,
        AUD3MBBSW3M,
        AUD3MBBSW3M,
        AUDBBSW3MBBSW6M,
        AUDBBSW3MBBSW6M,
        AUDBBSW3MBBSW6M
      };
  /** Tenors for the Fwd 3M USD curve */
  private static final Period[] FWD3_AUD_TENOR =
      new Period[] {
        Period.ofMonths(0),
        Period.ofMonths(6),
        Period.ofMonths(9),
        Period.ofYears(1),
        Period.ofYears(2),
        Period.ofYears(3),
        Period.ofYears(5),
        Period.ofYears(7),
        Period.ofYears(10)
      };

  private static final GeneratorAttributeIR[] FWD3_AUD_ATTR =
      new GeneratorAttributeIR[FWD3_AUD_TENOR.length];

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

  /** Market values for the Fwd 3M USD curve */
  private static final double[] FWD6_AUD_MARKET_QUOTES =
      new double[] {0.0440, 0.0020, 0.0020, 0.0020, 0.0560, 0.0610, 0.0620};
  /** Generators for the Fwd 3M USD curve */
  private static final GeneratorInstrument<? extends GeneratorAttribute>[] FWD6_AUD_GENERATORS =
      new GeneratorInstrument<?>[] {
        GENERATOR_AUDBB6M,
        AUDBBSW3MBBSW6M,
        AUDBBSW3MBBSW6M,
        AUDBBSW3MBBSW6M,
        AUD6MBBSW6M,
        AUD6MBBSW6M,
        AUD6MBBSW6M
      };
  /** Tenors for the Fwd 3M USD curve */
  private static final Period[] FWD6_AUD_TENOR =
      new Period[] {
        Period.ofMonths(0),
        Period.ofYears(1),
        Period.ofYears(2),
        Period.ofYears(3),
        Period.ofYears(5),
        Period.ofYears(7),
        Period.ofYears(10)
      };

  private static final GeneratorAttributeIR[] FWD6_AUD_ATTR =
      new GeneratorAttributeIR[FWD6_AUD_TENOR.length];

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

  /** Standard USD discounting curve instrument definitions */
  private static final InstrumentDefinition<?>[] DEFINITIONS_DSC_AUD;
  /** Standard USD Forward 3M curve instrument definitions */
  private static final InstrumentDefinition<?>[] DEFINITIONS_FWD3_AUD;
  /** Standard USD Forward 3M curve instrument definitions */
  private static final InstrumentDefinition<?>[] DEFINITIONS_FWD6_AUD;

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

  private static final int NB_BLOCKS = NB_UNITS.length;
  private static final InstrumentDefinition<?>[][][][] DEFINITIONS_UNITS =
      new InstrumentDefinition<?>[NB_BLOCKS][][][];
  private static final GeneratorYDCurve[][][] GENERATORS_UNITS =
      new GeneratorYDCurve[NB_BLOCKS][][];
  private static final String[][][] NAMES_UNITS = new String[NB_BLOCKS][][];
  private static final MulticurveProviderDiscount KNOWN_DATA =
      new MulticurveProviderDiscount(FX_MATRIX);
  private static final LinkedHashMap<String, Currency> DSC_MAP = new LinkedHashMap<>();
  private static final LinkedHashMap<String, IndexON[]> FWD_ON_MAP = new LinkedHashMap<>();
  private static final LinkedHashMap<String, IborIndex[]> FWD_IBOR_MAP = new LinkedHashMap<>();

  static {
    DEFINITIONS_DSC_AUD = getDefinitions(DSC_AUD_MARKET_QUOTES, DSC_USD_GENERATORS, DSC_AUD_ATTR);
    DEFINITIONS_FWD3_AUD =
        getDefinitions(FWD3_AUD_MARKET_QUOTES, FWD3_AUD_GENERATORS, FWD3_AUD_ATTR);
    DEFINITIONS_FWD6_AUD =
        getDefinitions(FWD6_AUD_MARKET_QUOTES, FWD6_AUD_GENERATORS, FWD6_AUD_ATTR);
    for (int loopblock = 0; loopblock < NB_BLOCKS; loopblock++) {
      DEFINITIONS_UNITS[loopblock] = new InstrumentDefinition<?>[NB_UNITS[loopblock]][][];
      GENERATORS_UNITS[loopblock] = new GeneratorYDCurve[NB_UNITS[loopblock]][];
      NAMES_UNITS[loopblock] = new String[NB_UNITS[loopblock]][];
    }
    DEFINITIONS_UNITS[0][0] = new InstrumentDefinition<?>[][] {DEFINITIONS_DSC_AUD};
    DEFINITIONS_UNITS[0][1] =
        new InstrumentDefinition<?>[][] {DEFINITIONS_FWD3_AUD, DEFINITIONS_FWD6_AUD};
    DEFINITIONS_UNITS[1][0] =
        new InstrumentDefinition<?>[][] {
          DEFINITIONS_DSC_AUD, DEFINITIONS_FWD3_AUD, DEFINITIONS_FWD6_AUD
        };
    final GeneratorYDCurve genIntLin =
        new GeneratorCurveYieldInterpolated(MATURITY_CALCULATOR, INTERPOLATOR_LINEAR);
    GENERATORS_UNITS[0][0] = new GeneratorYDCurve[] {genIntLin};
    GENERATORS_UNITS[0][1] = new GeneratorYDCurve[] {genIntLin, genIntLin};
    GENERATORS_UNITS[1][0] = new GeneratorYDCurve[] {genIntLin, genIntLin, genIntLin};
    NAMES_UNITS[0][0] = new String[] {CURVE_NAME_DSC_AUD};
    NAMES_UNITS[0][1] = new String[] {CURVE_NAME_FWD3_AUD, CURVE_NAME_FWD6_AUD};
    NAMES_UNITS[1][0] = new String[] {CURVE_NAME_DSC_AUD, CURVE_NAME_FWD3_AUD, CURVE_NAME_FWD6_AUD};
    DSC_MAP.put(CURVE_NAME_DSC_AUD, AUD);
    FWD_ON_MAP.put(CURVE_NAME_DSC_AUD, new IndexON[] {INDEX_ON_AUD});
    FWD_IBOR_MAP.put(CURVE_NAME_FWD3_AUD, new IborIndex[] {AUDBB3M});
    FWD_IBOR_MAP.put(CURVE_NAME_FWD6_AUD, new IborIndex[] {AUDBB6M});
  }

  @SuppressWarnings({"rawtypes", "unchecked"})
  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<MulticurveProviderDiscount, CurveBuildingBlockBundle>>
      CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK = new ArrayList<>();

  // Calculator
  private static final PresentValueDiscountingCalculator PVC =
      PresentValueDiscountingCalculator.getInstance();
  private static final ParSpreadMarketQuoteDiscountingCalculator PSMQC =
      ParSpreadMarketQuoteDiscountingCalculator.getInstance();
  private static final ParSpreadMarketQuoteCurveSensitivityDiscountingCalculator PSMQCSC =
      ParSpreadMarketQuoteCurveSensitivityDiscountingCalculator.getInstance();

  private static final MulticurveDiscountBuildingRepository CURVE_BUILDING_REPOSITORY =
      new MulticurveDiscountBuildingRepository(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,
              PSMQC,
              PSMQCSC,
              false));
    }
  }

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

  @Test
  public void comparison1Unit2Units() {
    final MulticurveProviderDiscount[] units = new MulticurveProviderDiscount[2];
    final CurveBuildingBlockBundle[] bb = new CurveBuildingBlockBundle[2];
    final YieldAndDiscountCurve[] curveDsc = new YieldAndDiscountCurve[2];
    final YieldAndDiscountCurve[] curveFwd = new YieldAndDiscountCurve[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(AUD);
      curveFwd[loopblock] = units[loopblock].getCurve(AUDBB3M);
    }
    assertEquals(
        "Curve construction: 1 unit / 2 units ",
        curveDsc[0].getNumberOfParameters(),
        curveDsc[1].getNumberOfParameters());
    assertEquals(
        "Curve construction: 1 unit / 2 units ",
        curveFwd[0].getNumberOfParameters(),
        curveFwd[1].getNumberOfParameters());
    assertArrayEquals(
        "Curve construction: 1 unit / 2 units ",
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[0]).getCurve().getXData()),
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[1]).getCurve().getXData()),
        TOLERANCE_CAL);
    assertArrayEquals(
        "Curve construction: 1 unit / 2 units ",
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[0]).getCurve().getYData()),
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[1]).getCurve().getYData()),
        TOLERANCE_CAL);
    assertArrayEquals(
        "Curve construction: 1 unit / 2 units ",
        ArrayUtils.toPrimitive(((YieldCurve) curveFwd[0]).getCurve().getXData()),
        ArrayUtils.toPrimitive(((YieldCurve) curveFwd[1]).getCurve().getXData()),
        TOLERANCE_CAL);
    assertArrayEquals(
        "Curve construction: 1 unit / 2 units ",
        ArrayUtils.toPrimitive(((YieldCurve) curveFwd[0]).getCurve().getYData()),
        ArrayUtils.toPrimitive(((YieldCurve) curveFwd[1]).getCurve().getYData()),
        TOLERANCE_CAL);

    assertEquals(
        "Curve construction: 1 unit / 2 units ",
        bb[0].getBlock(CURVE_NAME_FWD3_AUD).getFirst(),
        bb[1].getBlock(CURVE_NAME_FWD3_AUD).getFirst());
    // Test note: the discounting curve building blocks are not the same; in one case both curves
    // are build together in the other one after the other.
    final int nbLineDsc = bb[0].getBlock(CURVE_NAME_DSC_AUD).getSecond().getNumberOfRows();
    final int nbLineFwd3 = bb[0].getBlock(CURVE_NAME_FWD3_AUD).getSecond().getNumberOfRows();
    final int nbLineFwd6 = bb[0].getBlock(CURVE_NAME_FWD6_AUD).getSecond().getNumberOfRows();
    assertEquals(
        "Curve construction: 1 unit / 2 units ",
        bb[1].getBlock(CURVE_NAME_DSC_AUD).getSecond().getNumberOfRows(),
        nbLineDsc);
    assertEquals(
        "Curve construction: 1 unit / 2 units ",
        bb[1].getBlock(CURVE_NAME_FWD3_AUD).getSecond().getNumberOfRows(),
        nbLineFwd3);
    assertEquals(
        "Curve construction: 1 unit / 2 units ",
        bb[1].getBlock(CURVE_NAME_FWD6_AUD).getSecond().getNumberOfRows(),
        nbLineFwd6);
  }

  // TODO: test on the correctness of the Jacobian matrix in the CurveBuildingBlock's.

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

    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      makeCurvesFromDefinitions(
          DEFINITIONS_UNITS[0],
          GENERATORS_UNITS[0],
          NAMES_UNITS[0],
          KNOWN_DATA,
          PSMQC,
          PSMQCSC,
          false);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest + " x 3 curves construction / 2 units: " + (endTime - startTime) + " ms");
    // Performance note: Curve construction 2 units: 08-Nov-12: On Mac Pro 3.2 GHz Quad-Core Intel
    // Xeon: 810 ms for 100 sets.

    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      makeCurvesFromDefinitions(
          DEFINITIONS_UNITS[1],
          GENERATORS_UNITS[1],
          NAMES_UNITS[1],
          KNOWN_DATA,
          PSMQC,
          PSMQCSC,
          false);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest + " x 3 curves construction / 1 unit: " + (endTime - startTime) + " ms");
    // Performance note: Curve construction 1 unit: 08-Nov-12: On Mac Pro 3.2 GHz Quad-Core Intel
    // Xeon: 995 ms for 100 sets.

  }

  public void curveConstructionTest(
      final InstrumentDefinition<?>[][][] definitions,
      final MulticurveProviderDiscount 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], 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(PVC, curves), AUD)
                  .getAmount();
          assertEquals(
              "Curve construction: block "
                  + block
                  + ", unit "
                  + loopblock
                  + " - instrument "
                  + loopins,
              0,
              pv[loopcurve][loopins],
              TOLERANCE_CAL);
        }
      }
    }
  }

  @Test(enabled = false)
  /** Analyzes the shape of the forward curve. */
  public void forwardAnalysis() {
    final MulticurveProviderInterface marketDsc =
        CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(0).getFirst();
    final int jump = 1;
    final int startIndex = 0;
    final int nbDate = 2750;
    ZonedDateTime startDate =
        ScheduleCalculator.getAdjustedDate(NOW, AUDBB3M.getSpotLag() + startIndex * jump, SYD);
    final double[] rateDsc = new double[nbDate];
    final double[] startTime = new double[nbDate];
    try {
      final FileWriter writer = new FileWriter("fwd-dsc.csv");
      for (int loopdate = 0; loopdate < nbDate; loopdate++) {
        startTime[loopdate] = TimeCalculator.getTimeBetween(NOW, startDate);
        final ZonedDateTime endDate = ScheduleCalculator.getAdjustedDate(startDate, AUDBB3M, SYD);
        final double endTime = TimeCalculator.getTimeBetween(NOW, endDate);
        final double accrualFactor = AUDBB3M.getDayCount().getDayCountFraction(startDate, endDate);
        rateDsc[loopdate] =
            marketDsc.getForwardRate(AUDBB3M, startTime[loopdate], endTime, accrualFactor);
        startDate = ScheduleCalculator.getAdjustedDate(startDate, jump, SYD);
        writer.append(0.0 + "," + startTime[loopdate] + "," + rateDsc[loopdate] + "\n");
      }
      writer.flush();
      writer.close();
    } catch (final IOException e) {
      e.printStackTrace();
    }
  }

  @SuppressWarnings("unchecked")
  private static Pair<MulticurveProviderDiscount, CurveBuildingBlockBundle>
      makeCurvesFromDefinitions(
          final InstrumentDefinition<?>[][][] definitions,
          final GeneratorYDCurve[][] curveGenerators,
          final String[][] curveNames,
          final MulticurveProviderDiscount knownData,
          final InstrumentDerivativeVisitor<MulticurveProviderInterface, Double> calculator,
          final InstrumentDerivativeVisitor<MulticurveProviderInterface, MulticurveSensitivity>
              sensitivityCalculator,
          final boolean withToday) {
    final int nUnits = curveGenerators.length;
    final MultiCurveBundle<GeneratorYDCurve>[] curveBundles = new MultiCurveBundle[nUnits];
    for (int i = 0; i < nUnits; i++) {
      final int nCurves = definitions[i].length;
      final SingleCurveBundle<GeneratorYDCurve>[] 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], withToday);
          initialGuess[k] = initialGuess(definitions[i][j][k]);
        }
        final GeneratorYDCurve 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_IBOR_MAP,
        FWD_ON_MAP,
        calculator,
        sensitivityCalculator);
  }

  private static InstrumentDerivative[][] convert(
      final InstrumentDefinition<?>[][] definitions, final boolean withToday) {
    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 SwapFixedONDefinition) {
          ird = ((SwapFixedONDefinition) instrument).toDerivative(NOW, getTSSwapFixedON(withToday));
        } else {
          if (instrument instanceof SwapFixedIborDefinition) {
            ird =
                ((SwapFixedIborDefinition) instrument)
                    .toDerivative(NOW, getTSSwapFixedIbor(withToday));
          } else {
            if (instrument instanceof SwapIborIborDefinition) {
              ird =
                  ((SwapIborIborDefinition) instrument)
                      .toDerivative(NOW, getTSSwapIborIbor(withToday));
            } else {
              ird = instrument.toDerivative(NOW);
            }
          }
        }
        instruments[loopcurve][loopins++] = ird;
      }
    }
    return instruments;
  }

  private static InstrumentDerivative convert(
      final InstrumentDefinition<?> instrument, final boolean withToday) {
    InstrumentDerivative ird;
    if (instrument instanceof SwapFixedONDefinition) {
      ird = ((SwapFixedONDefinition) instrument).toDerivative(NOW, getTSSwapFixedON(withToday));
    } else {
      if (instrument instanceof SwapFixedIborDefinition) {
        ird =
            ((SwapFixedIborDefinition) instrument).toDerivative(NOW, getTSSwapFixedIbor(withToday));
      } else {
        if (instrument instanceof SwapIborIborDefinition) {
          ird =
              ((SwapIborIborDefinition) instrument).toDerivative(NOW, getTSSwapIborIbor(withToday));
        } else {
          ird = instrument.toDerivative(NOW);
        }
      }
    }
    return ird;
  }

  private static ZonedDateTimeDoubleTimeSeries[] getTSSwapFixedON(final Boolean withToday) {
    return withToday ? TS_FIXED_OIS_AUD_WITH_TODAY : TS_FIXED_OIS_AUD_WITHOUT_TODAY;
  }

  private static ZonedDateTimeDoubleTimeSeries[] getTSSwapFixedIbor(final Boolean withToday) {
    return withToday
        ? TS_FIXED_IBOR_AUD3M_WITH_TODAY
        : TS_FIXED_IBOR_AUD3M_WITHOUT_TODAY; // TODO: get the correct fixing
  }

  private static ZonedDateTimeDoubleTimeSeries[] getTSSwapIborIbor(final Boolean withToday) {
    return withToday ? TS_FIXED_IBOR_AUD3M6M_WITH_TODAY : TS_FIXED_IBOR_AUD3M6M_WITHOUT_TODAY;
  }

  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 ForwardRateAgreementDefinition) {
      return ((ForwardRateAgreementDefinition) instrument).getRate();
    }
    if (instrument instanceof CashDefinition) {
      return ((CashDefinition) instrument).getRate();
    } // TODO: What about basis swaps?
    return 0.01;
  }
}