@Test public void testGetFirstNElements(){ List<Integer> list1To15 = ListTool.createArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); List<Integer> list1To10 = ListTool.getFirstNElements(list1To15, 10); List<Integer> list1To5 = ListTool.getFirstNElements(list1To10, 5); List<Integer> list1To5TestLimit200 = ListTool.getFirstNElements(list1To5, 200); List<Integer> list1To5TestLimit0 = ListTool.getFirstNElements(list1To5TestLimit200, 0); List<Integer> list1To5TestLimitNeg1 = ListTool.getFirstNElements(list1To5TestLimit200, -1); Assert.assertEquals(10, list1To10.size()); ArrayAsserts.assertArrayEquals(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, list1To10.toArray()); Assert.assertEquals(5, list1To5.size()); ArrayAsserts.assertArrayEquals(new Integer[]{1, 2, 3, 4, 5}, list1To5.toArray()); Assert.assertEquals(list1To5.size(), list1To5TestLimit200.size()); ArrayAsserts.assertArrayEquals(list1To5.toArray(), list1To5TestLimit200.toArray()); Assert.assertEquals(0, list1To5TestLimit0.size()); Assert.assertEquals(0, list1To5TestLimitNeg1.size()); }
@Test public void test() { assertFalse(DEFAULT_USD_CONFIG.equals(EXTRA_USD_CONFIG)); assertFalse(DEFAULT_USD_CONFIG.equals(DEFAULT_INR_CONFIG)); final String name = "Extra"; final String[] curveNames = new String[] {"FORWARD_6M", "FORWARD_12M", "FORWARD_1M" }; final ComputationTargetSpecification target = ComputationTargetSpecification.of(Currency.USD); final LinkedHashMap<String, String[]> exogenousCurves = new LinkedHashMap<String, String[]>(); exogenousCurves.put(DEFAULT_USD_CONFIG_NAME, new String[] {"FUNDING" }); final MultiCurveCalculationConfig config = new MultiCurveCalculationConfig(name, curveNames, target, "Par Rate", CURVE_EXPOSURES, exogenousCurves); assertEquals(EXTRA_USD_CONFIG, config); assertEquals(config.getCalculationMethod(), "Par Rate"); assertEquals(config.getCalculationConfigName(), name); assertEquals(config.getTarget(), target); ArrayAsserts.assertArrayEquals(config.getYieldCurveNames(), curveNames); assertEquals(config.getExogenousConfigData(), exogenousCurves); }
/** Tests input sensitivity when all values are 0. */ @Test public void sensitivityAll0() { double[] xData = new double[] {1.0, 2.0, 3.0, 4.0 }; double[] yData = new double[] {0.0, 0.0, 0.0, 0.0 }; Interpolator1DDataBundle bundle = INTERP.getDataBundle(xData, yData); int nbData = yData.length; double[] xTest = new double[] {1.0, 1.1, 2.5, 3.0 - 1.0E-13, 3.0, 3.0 + 1.0E-13, 3.5, 4.0 }; int nbTest = xTest.length; double shift = 1.0E-8; for(int i=0; i<nbTest; i++) { double[] sensiAD = INTERP.getNodeSensitivitiesForValue(bundle, xTest[i]); double y = INTERP.interpolate(bundle, xTest[i]); double[] sensiFD = new double[nbData]; for(int j=0; j<nbData; j++) { double[] yDataBumped = yData.clone(); yDataBumped[j] += shift; Interpolator1DDataBundle bundleBumped = INTERP.getDataBundle(xData, yDataBumped); double yBumped = INTERP.interpolate(bundleBumped, xTest[i]); sensiFD[j] = (yBumped - y)/ shift; } ArrayAsserts.assertArrayEquals("SquareLinearInterpolator1DTest - " + i, sensiFD, sensiAD, TOLERANCE_DELTA); } }
/** Tests input sensitivity when all values are 0. */ @Test public void sensitivityOne0() { double[] xData = new double[] {1.0, 2.0, 3.0, 4.0 }; double[] yData = new double[] {0.1, 0.0, 0.1, 1.0 }; Interpolator1DDataBundle bundle = INTERP.getDataBundle(xData, yData); int nbData = yData.length; double[] xTest = new double[] {1.0, 1.1, 2.0 - 1.0E-14, 2.0, 2.0 + 1.0E-14, 2.5, 3.1, 3.5, 4.0}; int nbTest = xTest.length; double shift = 1.0E-4; for(int i=0; i<nbTest; i++) { double[] sensiAD = INTERP.getNodeSensitivitiesForValue(bundle, xTest[i]); double y = INTERP.interpolate(bundle, xTest[i]); double[] sensiFD = new double[nbData]; for(int j=0; j<nbData; j++) { double[] yDataBumped = yData.clone(); yDataBumped[j] += shift; Interpolator1DDataBundle bundleBumped = INTERP.getDataBundle(xData, yDataBumped); double yBumped = INTERP.interpolate(bundleBumped, xTest[i]); sensiFD[j] = (yBumped - y)/ shift; } ArrayAsserts.assertArrayEquals("SquareLinearInterpolator1DTest - " + i, sensiFD, sensiAD, TOLERANCE_DELTA_0); } }
/** * Tests creation of a forward-starting variance swap derivative */ @SuppressWarnings("deprecation") @Test public void testForwardStarting() { final VarianceSwap varianceSwap = DEFINITION.toDerivative(NOW, ImmutableLocalDateDoubleTimeSeries.EMPTY_SERIES); assertEquals(OBS_PER_YEAR, varianceSwap.getAnnualizationFactor()); assertEquals(CCY, varianceSwap.getCurrency()); assertEquals(0, varianceSwap.getObsDisrupted()); ArrayAsserts.assertArrayEquals(new double[0], varianceSwap.getObservations(), 0); ArrayAsserts.assertArrayEquals(new double[0], varianceSwap.getObservationWeights(), 0); assertEquals(1303, varianceSwap.getObsExpected()); assertEquals(5, varianceSwap.getTimeToObsEnd(), 0); assertEquals(2. / 365, varianceSwap.getTimeToObsStart(), 0); assertEquals(5, varianceSwap.getTimeToSettlement(), 0); assertEquals(VOL_NOTIONAL / VOL_STRIKE / 2, varianceSwap.getVarNotional(), 0); assertEquals(VOL_STRIKE * VOL_STRIKE, varianceSwap.getVarStrike()); assertEquals(VOL_NOTIONAL, varianceSwap.getVolNotional()); assertEquals(VOL_STRIKE, varianceSwap.getVolStrike(), 0); assertEquals(varianceSwap, DEFINITION.toDerivative(NOW)); }
@Test public void generateCurve() { String name = "CRV"; double[] values = new double[NB_NODES]; PriceIndexCurveSimple generated = GENERATOR.generateCurve(name, values); assertTrue("GeneratorPriceIndexCurveInterpolatedAnchorNode", generated.getCurve() instanceof DoublesCurveInterpolatedAnchor); DoublesCurveInterpolatedAnchor curveAnchor = (DoublesCurveInterpolatedAnchor) generated.getCurve(); assertTrue("GeneratorPriceIndexCurveInterpolatedAnchorNode", curveAnchor.getInterpolator().equals(INTERPOLATOR_LINEAR)); assertTrue("GeneratorPriceIndexCurveInterpolatedAnchorNode", curveAnchor.getXData().length == 3); ArrayAsserts.assertArrayEquals("GeneratorPriceIndexCurveInterpolatedAnchorNode", curveAnchor.getXDataAsPrimitive(), ArrayUtils.addAll(new double[]{ANCHOR_NODE}, NODES), TOLERANCE_NODE); ArrayAsserts.assertArrayEquals("GeneratorPriceIndexCurveInterpolatedAnchorNode", curveAnchor.getYDataAsPrimitive(), ArrayUtils.addAll(new double[]{ANCHOR_VALUE}, values), TOLERANCE_NODE); }
@Test /** * Tests the class setters. */ public void setter() { double[][] volReplaced = new double[][] { {0.01, 0.01}, {0.011, 0.009}, {0.012, 0.008}}; int indexStart = 10; double[][] vol2 = new double[NB_PERIOD][2]; for (int loopperiod = 0; loopperiod < NB_PERIOD; loopperiod++) { vol2[loopperiod][0] = 0.02; vol2[loopperiod][1] = -0.02 + loopperiod * 0.002; } LiborMarketModelDisplacedDiffusionParameters parameterLmm = new LiborMarketModelDisplacedDiffusionParameters(TIME_IBOR, DELTA, DISPLACEMENT, vol2, MEAN_REVERSION); parameterLmm.setVolatility(volReplaced, indexStart); for (int loopperiod = 0; loopperiod < NB_PERIOD; loopperiod++) { if (loopperiod >= indexStart && loopperiod < indexStart + volReplaced.length) { // Replaced vol ArrayAsserts.assertArrayEquals("LMM getter", volReplaced[loopperiod - indexStart], parameterLmm.getVolatility()[loopperiod], 1.0E-10); } else {// Original vol ArrayAsserts.assertArrayEquals("LMM getter", VOL[loopperiod], parameterLmm.getVolatility()[loopperiod], 1.0E-10); } } }
/** * Note: this test relies on the content of the test resource files */ @Test public void testGenotyperInitialization() { final Set<String> ploidyTags = genotyper.getSexGenotypeIdentifiers(); final int[] autosomalTargetPloidies = genotyper.getAutosomalTargetGermlinePloidies(); final Map<String, int[]> allosomalTargetPloidies = genotyper.getAllosomalTargetGermlinePloidiesMap(); /* assert all ploidy tags are present */ Assert.assertTrue(ploidyTags.equals(Arrays.stream(GENOTYPES).collect(Collectors.toSet()))); /* assert ploidy on autosomal targets */ ArrayAsserts.assertArrayEquals( IntStream.range(0, autosomalTargetPloidies.length).map(i -> AUTOSOME_PLOIDY).toArray(), autosomalTargetPloidies); /* assert ploidy on allosomal targets */ int[] expected; final List<Target> allosomalTargetList = genotyper.getAllosomalTargetList(); expected = allosomalTargetList.stream().mapToInt(t -> t.getContig().equals("X") ? SEX_XX_PLOIDY_ON_X : SEX_XX_PLOIDY_ON_Y).toArray(); ArrayAsserts.assertArrayEquals(expected, allosomalTargetPloidies.get("SEX_XX")); expected = allosomalTargetList.stream().mapToInt(t -> t.getContig().equals("X") ? SEX_XY_PLOIDY_ON_X : SEX_XY_PLOIDY_ON_Y).toArray(); ArrayAsserts.assertArrayEquals(expected, allosomalTargetPloidies.get("SEX_XY")); }
/** Tests the correctness of the tape record, interpretation and derivatives on the AdStarter function. */ @Test public void derivativesCorrectnessTape() { for (int looptest = 0; looptest < NB_TESTS; looptest++) { TapeAad tape = new TapeAad(); DoubleAad[] a = new DoubleAad[4]; for (int loopi = 0; loopi < 4; loopi++) { int va = tape.addEntry(new TapeEntryAad(OperationTypeAad.INPUT, A[looptest][loopi])); a[loopi] = new DoubleAad(A[looptest][loopi], va); } DoubleDerivatives dAad = AdStarter.f_Aad(A[looptest]); DoubleAad dAadA = AdStarter.f_Aad_Automatic(a, tape); assertEquals("adStarterAnalysis " + looptest, dAad.value(), dAadA.value(), TOLERANCE_VALUE); TapeUtils.interpret(tape); double[] d = TapeUtils.extractDerivatives(tape); ArrayAsserts.assertArrayEquals("adStarterAnalysis " + looptest, dAad.derivatives(), d, TOLERANCE_DELTA_2); } }
/** Tests the implementation of the AD by comparison to finite difference. */ @Test public void derivativesCorrectness() { boolean[] callPut = {true, false }; for (int looptest = 0; looptest < NB_TESTS; looptest++) { for (int looppc = 0; looppc < 2; looppc++) { double[] d4Call = FiniteDifferenceFirstOrder.differentiate(callPut[looppc] ? new blackCall2() : new blackPut2(), DATA[looptest], EPSILON, FiniteDifferenceSchemes.FOURTH_ORDER); DoubleDerivatives callPriceSad = BlackFormula.price_Sad(DATA[looptest][0], DATA[looptest][1], DATA[looptest][2], DATA[looptest][3], DATA[looptest][4], callPut[looppc]); ArrayAsserts.assertArrayEquals("BlackFormula SAD " + looptest, d4Call, callPriceSad.derivatives(), TOLERANCE_DELTA); DoubleSad callPriceSadA = BlackFormula.price_Sad_Automatic(DATA[looptest][0], DATA[looptest][1], DATA[looptest][2], DATA[looptest][3], DATA[looptest][4], callPut[looppc]); ArrayAsserts.assertArrayEquals("BlackFormula SAD " + looptest, d4Call, callPriceSadA.derivatives(), TOLERANCE_DELTA); DoubleDerivatives callPriceAad = BlackFormula.price_Aad(DATA[looptest][0], DATA[looptest][1], DATA[looptest][2], DATA[looptest][3], DATA[looptest][4], callPut[looppc]); ArrayAsserts.assertArrayEquals("BlackFormula AAD " + looptest, d4Call, callPriceAad.derivatives(), TOLERANCE_DELTA); DoubleDerivatives callPriceAadOpt = BlackFormula.price_Aad_Optimized(DATA[looptest][0], DATA[looptest][1], DATA[looptest][2], DATA[looptest][3], DATA[looptest][4], callPut[looppc]); ArrayAsserts.assertArrayEquals("BlackFormula AAD " + looptest, d4Call, callPriceAadOpt.derivatives(), TOLERANCE_DELTA); } } }
@Test public void derivativesCorrectnessTape() { boolean[] callPut = {true, false }; for (int looptest = 0; looptest < NB_TESTS; looptest++) { for (int looppc = 0; looppc < 2; looppc++) { DoubleDerivatives callPriceAad_Optimized = BlackFormula.price_Aad_Optimized(DATA[looptest][0], DATA[looptest][1], DATA[looptest][2], DATA[looptest][3], DATA[looptest][4], callPut[looppc]); DoubleAad callPriceAad_Automatic = BlackFormula.price_Aad_Automatic(DATA_AAD[looptest][0][looppc], DATA_AAD[looptest][1][looppc], DATA_AAD[looptest][2][looppc], DATA_AAD[looptest][3][looppc], DATA_AAD[looptest][4][looppc], callPut[looppc], TAPE[looptest][looppc]); assertEquals("BlackFormula AAD " + looptest, callPriceAad_Optimized.value(), callPriceAad_Automatic.value(), TOLERANCE_PRICE); double[] d1 = TapeUtils.interpret(TAPE[looptest][looppc]); double[] d2 = TapeUtils.extractDerivatives(TAPE[looptest][looppc]); ArrayAsserts.assertArrayEquals("BlackFormula AAD " + looptest, callPriceAad_Optimized.derivatives(), d1, TOLERANCE_DELTA); ArrayAsserts.assertArrayEquals("BlackFormula AAD " + looptest, callPriceAad_Optimized.derivatives(), d2, TOLERANCE_DELTA); } } }
@Test public void stickyStrike() { boolean[] callPut = {true, false}; for (int looptest = 0; looptest < NB_TESTS; looptest++) { double volatility = INTERPOLATION.interpolate(DATA_OTHER[looptest][2], DATA_SMILE); for (int looppc = 0; looppc < 2; looppc++) { DoubleDerivatives priceComputed = FORMULA.price_Aad_StickyStrike(DATA_OTHER[looptest][0], SMILE_DES_STRIKE, DATA_OTHER[looptest][1], DATA_OTHER[looptest][2], DATA_OTHER[looptest][3], callPut[looppc]); DoubleDerivatives priceExpected = BlackFormula.price_Aad(DATA_OTHER[looptest][0], volatility, DATA_OTHER[looptest][1], DATA_OTHER[looptest][2], DATA_OTHER[looptest][3], callPut[looppc]); assertEquals("Black Smile Formula - sticky strike", priceExpected.value(), priceComputed.value(), TOLERANCE_PRICE); ArrayAsserts.assertArrayEquals("Black Smile Formula - sticky strike", priceExpected.derivatives(), priceComputed.derivatives(), TOLERANCE_DELTA); } } }
/** Tests the implementation of the AD by comparison to finite difference. * @throws MathException */ @Test public void derivativesCorrectness() { boolean[] callPut = {true, false }; for (int looptest = 0; looptest < NB_TESTS; looptest++) { for (int looppc = 0; looppc < 2; looppc++) { double[] d3Call = FiniteDifferenceFirstOrder.differentiate(callPut[looppc] ? new blackCall() : new blackPut(), DATA[looptest], EPSILON, FiniteDifferenceSchemes.FOURTH_ORDER); DoubleDerivatives callPriceSad = BlackFormula2.price_Sad(DATA[looptest][0], DATA[looptest][1], DATA[looptest][2], DATA[looptest][3], DATA[looptest][4], callPut[looppc]); ArrayAsserts.assertArrayEquals("BlackFormula SAD " + looptest, d3Call, callPriceSad.derivatives(), TOLERANCE_DELTA); DoubleSad callPriceSadA = BlackFormula2.price_Sad_Automatic(DATA[looptest][0], DATA[looptest][1], DATA[looptest][2], DATA[looptest][3], DATA[looptest][4], callPut[looppc]); ArrayAsserts.assertArrayEquals("BlackFormula SAD " + looptest, d3Call, callPriceSadA.derivatives(), TOLERANCE_DELTA); DoubleDerivatives callPriceAad = BlackFormula2.price_Aad(DATA[looptest][0], DATA[looptest][1], DATA[looptest][2], DATA[looptest][3], DATA[looptest][4], callPut[looppc]); ArrayAsserts.assertArrayEquals("BlackFormula AAD " + looptest, d3Call, callPriceAad.derivatives(), TOLERANCE_DELTA); DoubleDerivatives callPriceAadOpt = BlackFormula2.price_Aad_Optimized(DATA[looptest][0], DATA[looptest][1], DATA[looptest][2], DATA[looptest][3], DATA[looptest][4], callPut[looppc]); ArrayAsserts.assertArrayEquals("BlackFormula AAD " + looptest, d3Call, callPriceAadOpt.derivatives(), TOLERANCE_DELTA); } } }
@Test public void derivativesCorrectnessTape() { boolean[] callPut = {true, false }; for (int looptest = 0; looptest < NB_TESTS; looptest++) { for (int looppc = 0; looppc < 2; looppc++) { DoubleDerivatives callPriceAad_Optimized = BlackFormula2.price_Aad_Optimized(DATA[looptest][0], DATA[looptest][1], DATA[looptest][2], DATA[looptest][3], DATA[looptest][4], callPut[looppc]); DoubleAad callPriceAad_Automatic = BlackFormula2.price_Aad_Automatic(DATA_AAD[looptest][0][looppc], DATA_AAD[looptest][1][looppc], DATA_AAD[looptest][2][looppc], DATA_AAD[looptest][3][looppc], DATA_AAD[looptest][4][looppc], callPut[looppc], TAPE[looptest][looppc]); assertEquals("BlackFormula AAD " + looptest, callPriceAad_Optimized.value(), callPriceAad_Automatic.value(), TOLERANCE_DELTA); TapeUtils.interpret(TAPE[looptest][looppc]); double[] d = TapeUtils.extractDerivatives(TAPE[looptest][looppc]); ArrayAsserts.assertArrayEquals("BlackFormula AAD " + looptest, callPriceAad_Optimized.derivatives(), d, TOLERANCE_PRICE); } } }
@Test public void derivativesCorrectnessTape() { for (int looptest = 0; looptest < NB_TESTS; looptest++) { TapeAad tape = new TapeAad(); DoubleAad[] dataAad = new DoubleAad[7]; for (int loopi = 0; loopi < 7; loopi++) { int index = tape.addEntry(new TapeEntryAad(OperationTypeAad.INPUT, DATA[looptest][loopi])); dataAad[loopi] = new DoubleAad(DATA[looptest][loopi], index); } DoubleDerivatives priceAad = SabrVolatilityFormula.volatility_Aad(DATA[looptest][0], DATA[looptest][1], DATA[looptest][2], DATA[looptest][3], DATA[looptest][4], DATA[looptest][5], DATA[looptest][6]); DoubleAad priceAadAutomatic = SabrVolatilityFormula.volatility_Aad_Automatic( dataAad[0], dataAad[1], dataAad[2], dataAad[3], dataAad[4], dataAad[5], dataAad[6], tape); assertEquals("SabrVolatilityFormula AAD " + looptest, priceAad.value(), priceAadAutomatic.value(), TOLERANCE_PRICE); TapeUtils.interpret(tape); double[] dAadAutomatic = TapeUtils.extractDerivatives(tape); ArrayAsserts.assertArrayEquals("SabrVolatilityFormula AAD " + looptest, priceAad.derivatives(), dAadAutomatic, TOLERANCE_DELTA); } }
@Test public void derivativesCorrectnessTape2() { for (int looptest = 0; looptest < NB_TESTS; looptest++) { TapeAad tape = new TapeAad(); DoubleAad[] dataAad = new DoubleAad[7]; for (int loopi = 0; loopi < 7; loopi++) { int index = tape.addEntry(new TapeEntryAad(OperationTypeAad.INPUT, DATA[looptest][loopi])); dataAad[loopi] = new DoubleAad(DATA[looptest][loopi], index); } DoubleDerivatives priceAad = SabrVolatilityFormula.volatility_Aad(DATA[looptest][0], DATA[looptest][1], DATA[looptest][2], DATA[looptest][3], DATA[looptest][4], DATA[looptest][5], DATA[looptest][6]); DoubleAad priceAadAutomatic = SabrVolatilityFormula.volatility_Aad_Automatic2( dataAad[0], dataAad[1], dataAad[2], dataAad[3], dataAad[4], dataAad[5], dataAad[6], tape); assertEquals("SabrVolatilityFormula AAD " + looptest, priceAad.value(), priceAadAutomatic.value(), TOLERANCE_PRICE); TapeUtils.interpret(tape); double[] dAadAutomatic = TapeUtils.extractDerivatives(tape); ArrayAsserts.assertArrayEquals("SabrVolatilityFormula AAD " + looptest, priceAad.derivatives(), dAadAutomatic, TOLERANCE_DELTA); } }
@Test public void testMessageParse() throws IOException { try (InputStream stream = new ByteArrayInputStream("( 2 ( edit-pipeline svndiff1 absent-entries depth mergeinfo log-revprops ) 15:svn://localhost 31:SVN/1.8.8 (x86_64-pc-linux-gnu) ( ) ) test ".getBytes(StandardCharsets.UTF_8))) { final SvnServerParser parser = new SvnServerParser(stream); ClientInfo req = MessageParser.parse(ClientInfo.class, parser); Assert.assertEquals(req.getProtocolVersion(), 2); Assert.assertEquals(req.getUrl().toString(), "svn://localhost"); Assert.assertEquals(req.getUserAgent(), "SVN/1.8.8 (x86_64-pc-linux-gnu)"); ArrayAsserts.assertArrayEquals(new String[]{ "edit-pipeline", "svndiff1", "absent-entries", "depth", "mergeinfo", "log-revprops" }, req.getCapabilities()); Assert.assertEquals(parser.readText(), "test"); } }
@Test public void testMessageParse2() throws IOException { try (InputStream stream = new ByteArrayInputStream("( 2 ( edit-pipeline svndiff1 absent-entries depth mergeinfo log-revprops ) 15:svn://localhost ) test ".getBytes(StandardCharsets.UTF_8))) { final SvnServerParser parser = new SvnServerParser(stream); ClientInfo req = MessageParser.parse(ClientInfo.class, parser); Assert.assertEquals(req.getProtocolVersion(), 2); Assert.assertEquals(req.getUrl().toString(), "svn://localhost"); Assert.assertEquals(req.getUserAgent(), ""); ArrayAsserts.assertArrayEquals(new String[]{ "edit-pipeline", "svndiff1", "absent-entries", "depth", "mergeinfo", "log-revprops" }, req.getCapabilities()); Assert.assertEquals(parser.readText(), "test"); } }
@Test public void testSplitOnCharNoRegex(){ ArrayAsserts.assertArrayEquals(new String[]{""}, splitOnCharNoRegex("", '/').toArray()); ArrayAsserts.assertArrayEquals(new String[]{}, splitOnCharNoRegex(null, '/').toArray()); ArrayAsserts.assertArrayEquals(new String[]{"", ""}, splitOnCharNoRegex("/", '/').toArray()); ArrayAsserts.assertArrayEquals(new String[]{" ", ""}, splitOnCharNoRegex(" /", '/').toArray()); ArrayAsserts.assertArrayEquals(new String[]{"abc", "def", "g"}, splitOnCharNoRegex("abc.def.g", '.') .toArray()); ArrayAsserts.assertArrayEquals(new String[]{"", "", "def", "g", ""}, splitOnCharNoRegex("..def.g.", '.') .toArray()); }
@Test /** * Tests solve Ax = b from A and b. */ public void solveVector() { final CholeskyDecompositionResult result = CDOG.evaluate(A5); double[] b = new double[] {1.0, 2.0, 3.0, 4.0, -1.0}; double[] x = result.solve(b); DoubleMatrix1D ax = (DoubleMatrix1D) ALGEBRA.multiply(A5, new DoubleMatrix1D(x)); ArrayAsserts.assertArrayEquals("Cholesky decomposition OpenGamma - solve", b, ax.getData(), 1.0E-10); }
@Test /** * Tests solve AX = B from A and B. */ public void solveMatrix() { final CholeskyDecompositionResult result = CDOG.evaluate(A5); double[][] b = new double[][] { {1.0, 2.0}, {2.0, 3.0}, {3.0, 4.0}, {4.0, -2.0}, {-1.0, -1.0}}; DoubleMatrix2D x = result.solve(new DoubleMatrix2D(b)); DoubleMatrix2D ax = (DoubleMatrix2D) ALGEBRA.multiply(A5, x); ArrayAsserts.assertArrayEquals("Cholesky decomposition OpenGamma - solve", b[0], ax.getData()[0], 1.0E-10); ArrayAsserts.assertArrayEquals("Cholesky decomposition OpenGamma - solve", b[1], ax.getData()[1], 1.0E-10); }
@Test public void testKnots() { BasisFunctionKnots knots = BasisFunctionKnots.fromKnots(KNOTS, 3); assertEquals(3, knots.getDegree()); assertEquals(11, knots.getNumKnots()); assertEquals(7, knots.getNumSplines()); ArrayAsserts.assertArrayEquals(KNOTS, knots.getKnots(), 1e-15); }
/** * Tests creation of a seasoned variance swap derivative */ @Test public void testSeasoned() { final VarianceSwapDefinition definition = new VarianceSwapDefinition(NOW, PLUS_5Y, PLUS_5Y, CCY, new NoHolidayCalendar(), OBS_PER_YEAR, VOL_STRIKE, VOL_NOTIONAL); final LocalDate[] dates = new LocalDate[365]; final double[] vars = new double[365]; LocalDate date = NOW.toLocalDate(); for (int i = 0; i < 365; i++) { dates[i] = date; vars[i] = 0.01; date = date.plusDays(1); } final LocalDateDoubleTimeSeries ts = ImmutableLocalDateDoubleTimeSeries.of(dates, vars); final VarianceSwap varianceSwap = definition.toDerivative(NOW.plusYears(1), ts); assertEquals(OBS_PER_YEAR, varianceSwap.getAnnualizationFactor()); assertEquals(CCY, varianceSwap.getCurrency()); assertEquals(0, varianceSwap.getObsDisrupted()); ArrayAsserts.assertArrayEquals(vars, varianceSwap.getObservations(), 0); ArrayAsserts.assertArrayEquals(new double[0], varianceSwap.getObservationWeights(), 0); assertEquals(1827, varianceSwap.getObsExpected()); assertEquals(4, varianceSwap.getTimeToObsEnd(), 0); assertEquals(-1, varianceSwap.getTimeToObsStart(), 0); assertEquals(4, varianceSwap.getTimeToSettlement(), 0); assertEquals(VOL_NOTIONAL / VOL_STRIKE / 2, varianceSwap.getVarNotional(), 0); assertEquals(VOL_STRIKE * VOL_STRIKE, varianceSwap.getVarStrike()); assertEquals(VOL_NOTIONAL, varianceSwap.getVolNotional()); assertEquals(VOL_STRIKE, varianceSwap.getVolStrike(), 0); }
/** * */ @Test public void getter() { ArrayAsserts.assertArrayEquals("CouponIborAverageFlatCompoundingSpreadDefinition: getter", FIXING_DATES, DFN2.getFixingDates()); ArrayAsserts.assertArrayEquals("CouponIborAverageFlatCompoundingSpreadDefinition: getter", WEIGHTS, DFN2.getWeight()); ArrayAsserts.assertArrayEquals("CouponIborAverageFlatCompoundingSpreadDefinition: getter", EXP_START_DATES, DFN2.getFixingPeriodStartDates()); ArrayAsserts.assertArrayEquals("CouponIborAverageFlatCompoundingSpreadDefinition: getter", EXP_END_DATES, DFN2.getFixingPeriodEndDates()); ArrayAsserts.assertArrayEquals("CouponIborAverageFlatCompoundingSpreadDefinition: getter", FIX_ACC_FACTORS, DFN2.getFixingPeriodAccrualFactor()); ArrayAsserts.assertArrayEquals("CouponIborAverageFlatCompoundingSpreadDefinition: getter", FIXING_DATES_3, DFN3.getFixingDates()); }
@Test public void toDerivativeBeforeFirstFixing() { final Coupon derivative1 = DFN1.toDerivative(REFERENCE_DATE_BEFORE_FISRT_FIXING, FIXING_TS1); assertTrue((derivative1 instanceof CouponIborAverageFixingDates)); final CouponIborAverageFixingDates coupon = (CouponIborAverageFixingDates) derivative1; double[] fixingTime = TimeCalculator.getTimeBetween(REFERENCE_DATE_BEFORE_FISRT_FIXING, FIXING_DATES); double[] fixingStart = TimeCalculator.getTimeBetween(REFERENCE_DATE_BEFORE_FISRT_FIXING, DFN1.getFixingPeriodStartDate()); double[] fixingEnd = TimeCalculator.getTimeBetween(REFERENCE_DATE_BEFORE_FISRT_FIXING, DFN1.getFixingPeriodEndDate()); ArrayAsserts.assertArrayEquals("CouponIborAverageFixingDatesDefinition: toDerivative", coupon.getFixingTime(), fixingTime, TOLERANCE_TIME); ArrayAsserts.assertArrayEquals("CouponIborAverageFixingDatesDefinition: toDerivative", coupon.getFixingPeriodStartTime(), fixingStart, TOLERANCE_TIME); ArrayAsserts.assertArrayEquals("CouponIborAverageFixingDatesDefinition: toDerivative", coupon.getFixingPeriodEndTime(), fixingEnd, TOLERANCE_TIME); assertEquals("CouponIborAverageFixingDatesDefinition: toDerivative", coupon.getNotional(), NOTIONAL); }
/** * */ @Test public void getter() { ArrayAsserts.assertArrayEquals("CouponIborAverageCompoundingDefinition: getter", FIXING_DATES, DFN2.getFixingDates()); ArrayAsserts.assertArrayEquals("CouponIborAverageCompoundingDefinition: getter", WEIGHTS, DFN2.getWeight()); ArrayAsserts.assertArrayEquals("CouponIborAverageCompoundingDefinition: getter", EXP_START_DATES, DFN2.getFixingPeriodStartDates()); ArrayAsserts.assertArrayEquals("CouponIborAverageCompoundingDefinition: getter", EXP_END_DATES, DFN2.getFixingPeriodEndDates()); ArrayAsserts.assertArrayEquals("CouponIborAverageCompoundingDefinition: getter", FIX_ACC_FACTORS, DFN2.getFixingPeriodAccrualFactor()); ArrayAsserts.assertArrayEquals("CouponIborAverageCompoundingDefinition: getter", FIXING_DATES_3, DFN3.getFixingDates()); }
@Test public void finalGenerator() { GeneratorPriceIndexCurve finalGen = GENERATOR.finalGenerator(new InstrumentDerivative[] {FRA_1, FRA_2}); assertTrue("GeneratorPriceIndexCurveInterpolatedAnchor: final generator", finalGen instanceof GeneratorPriceIndexCurveInterpolatedAnchorNode); GeneratorPriceIndexCurveInterpolatedAnchorNode genNode = (GeneratorPriceIndexCurveInterpolatedAnchorNode) finalGen; assertTrue("GeneratorPriceIndexCurveInterpolatedAnchor: final generator", genNode.getNumberOfParameter() == 2); assertEquals("GeneratorPriceIndexCurveInterpolatedAnchor: final generator", ANCHOR_NODE, genNode.getAnchorNode()); assertEquals("GeneratorPriceIndexCurveInterpolatedAnchor: final generator", ANCHOR_VALUE, genNode.getAnchorValue()); double[] nodePointsExpected = new double[2]; nodePointsExpected[0] = FRA_1.accept(LAST_FIXING_END_CALCULATOR); nodePointsExpected[1] = FRA_2.accept(LAST_FIXING_END_CALCULATOR); ArrayAsserts.assertArrayEquals(nodePointsExpected, genNode.getNodePoints(), TOLERANCE_NODE); }
@Test /** * Tests the class setters. */ public void setter() { final double[] volReplaced = new double[] {0.02, 0.01 }; MODEL_PARAMETERS.setLastVolatilities(volReplaced); ArrayAsserts.assertArrayEquals("G2++: setter", volReplaced, MODEL_PARAMETERS.getLastVolatilities(), 1.0E-10); MODEL_PARAMETERS.setLastVolatilities(new double[] {VOLATILITY[0][VOLATILITY[0].length - 1], VOLATILITY[1][VOLATILITY[0].length - 1] }); for (int loopperiod = 0; loopperiod < VOLATILITY[0].length; loopperiod++) { assertEquals("G2++: setter " + loopperiod, VOLATILITY[0][loopperiod], MODEL_PARAMETERS.getVolatility()[0].get(loopperiod)); assertEquals("G2++: setter " + loopperiod, VOLATILITY[1][loopperiod], MODEL_PARAMETERS.getVolatility()[1].get(loopperiod)); } }
@Test /** * Tests the volatilityMaturityPart method. */ public void volatilityMaturityPart() { final double u = 0.75; final double[] v = new double[] {2.0, 4.0, 7.0 }; final double[][] h = MODEL_G2PP.volatilityMaturityPart(MODEL_PARAMETERS, u, v); final double[][] hExpected = new double[][] { {1.232938151, 3.173861567, 6.013423491 }, {0.832348609, 1.657740023, 2.253532635 } }; ArrayAsserts.assertArrayEquals("G2++: maturity dependent volatility part", hExpected[0], h[0], 1.0E-7); ArrayAsserts.assertArrayEquals("G2++: maturity dependent volatility part", hExpected[1], h[1], 1.0E-7); final double[] hVector = MODEL_G2PP.volatilityMaturityPart(MODEL_PARAMETERS, u, v[0]); assertEquals("G2++: maturity dependent volatility part", hExpected[0][0], hVector[0], 1.0E-7); assertEquals("G2++: maturity dependent volatility part", hExpected[1][0], hVector[1], 1.0E-7); }
@Test /** * Tests the class getters. */ public void getter() { assertEquals("LMM getter", MEAN_REVERSION, PARAMETER_LMM.getMeanReversion()); ArrayAsserts.assertArrayEquals("LMM getter", DISPLACEMENT, PARAMETER_LMM.getDisplacement(), 1.0E-10); ArrayAsserts.assertArrayEquals("LMM getter", DELTA, PARAMETER_LMM.getAccrualFactor(), 1.0E-10); ArrayAsserts.assertArrayEquals("LMM getter", TIME_IBOR, PARAMETER_LMM.getIborTime(), 1.0E-10); for (int loopperiod = 0; loopperiod < NB_PERIOD; loopperiod++) { ArrayAsserts.assertArrayEquals("LMM getter", VOL[loopperiod], PARAMETER_LMM.getVolatility()[loopperiod], 1.0E-10); } }
@Test public void testNearestNeighborUniform1DInterpolate() { ArrayAsserts.assertArrayEquals(new double[]{0.0, 1.0, 2.0}, GATKProtectedMathUtils.nearestNeighborUniform1DInterpolate(new double[]{0.0, 1.0, 2.0}, 3), 1e-6); ArrayAsserts.assertArrayEquals(new double[]{0.0, 1.0, 1.0, 2.0}, GATKProtectedMathUtils.nearestNeighborUniform1DInterpolate(new double[]{0.0, 1.0, 2.0}, 4), 1e-6); ArrayAsserts.assertArrayEquals(new double[]{0.0, 0.0, 1.0, 1.0, 2.0, 2.0}, GATKProtectedMathUtils.nearestNeighborUniform1DInterpolate(new double[]{0.0, 1.0, 2.0}, 6), 1e-6); }
@Test public void testSumArrayFunction(){ final int min = 0; final int max = 5; // use 1 + 2 + ... + n = n(n+1)/2 // [0,1,2] + [1,2,3] + ... + [4,5,6] = [0 + 1 + ... + 4, 1 + ... + 5, 2 + ... + 6] = [10, 15, 21 - 1] = [10, 15, 20] final double[] array1 = { 10, 15, 20 }; ArrayAsserts.assertArrayEquals(GATKProtectedMathUtils.sumArrayFunction(min, max, i -> new double[]{ (double)i, i + 1.0, i + 2.0 }), array1, 1e-8); }
@Test public void testBasicSoundness() { for (final RealMatrix transitionMatrix : TRANSITION_MATRICES) { final IntegerCopyNumberTransitionProbabilityCache cache = new IntegerCopyNumberTransitionProbabilityCache( new IntegerCopyNumberTransitionMatrix(transitionMatrix, 0)); for (final int dist : DISTANCES) { final RealMatrix transitionMatrixExponentiated = cache.getTransitionProbabilityMatrix(dist); /* assert positivity */ Assert.assertTrue(Arrays.stream(transitionMatrixExponentiated.getData()) .flatMapToDouble(Arrays::stream) .allMatch(d -> d >= 0)); /* assert conservation of probability */ for (int c = 0; c < transitionMatrix.getColumnDimension(); c++) { Assert.assertEquals(Arrays.stream(transitionMatrixExponentiated.getColumn(c)).sum(), 1.0, EPSILON); } /* assert correctness, T(2*d) = T(d)*T(d) */ assertEqualMatrices(cache.getTransitionProbabilityMatrix(2*dist), transitionMatrixExponentiated.multiply(transitionMatrixExponentiated)); } /* assert loss of initial state over long distances, i.e. all columns must be equal */ final RealMatrix longRangeTransitionMatrix = cache.getTransitionProbabilityMatrix(Integer.MAX_VALUE); final double[] firstColumn = longRangeTransitionMatrix.getColumn(0); final RealMatrix syntheticLongRangeTransitionMatrix = new Array2DRowRealMatrix(firstColumn.length, firstColumn.length); for (int i = 0; i < firstColumn.length; i++) { syntheticLongRangeTransitionMatrix.setColumn(i, firstColumn); } assertEqualMatrices(longRangeTransitionMatrix, syntheticLongRangeTransitionMatrix); final double[] stationary = cache.getStationaryProbabilityVector().toArray(); ArrayAsserts.assertArrayEquals(stationary, firstColumn, EPSILON); } }
@Test public void testStationaryProbabilities() { for (final int padding : PADDINGS) { for (final RealMatrix transitionMatrix : TRANSITION_MATRICES) { final IntegerCopyNumberTransitionProbabilityCache cache = new IntegerCopyNumberTransitionProbabilityCache( new IntegerCopyNumberTransitionMatrix(transitionMatrix, padding)); final double[] stationary = cache.getStationaryProbabilityVector().toArray(); final double[] stationaryFromMultiplication = cache.getTransitionProbabilityMatrix(Integer.MAX_VALUE) .getColumn(0); ArrayAsserts.assertArrayEquals(stationary, stationaryFromMultiplication, EPSILON); Assert.assertEquals(Arrays.stream(stationary).sum(), 1.0, EPSILON); } } }
@Test(dataProvider = "getColumnOnSpecifiedTargetsTestData") public void testGetColumnOnSpecifiedTargets(final ReadCountCollection rcc, final int columnIndex, final List<Target> targets, final double[] expected) { final double[] result = rcc.getColumnOnSpecifiedTargets(columnIndex, targets, true); ArrayAsserts.assertArrayEquals(expected, result, 1e-12); }
public void tsvMatrixReadWriteAsserter(final INDArray arr) { final File outFile = createTempFile("Nd4j_matrix_tsv_test", ".tsv"); Nd4jIOUtils.writeNDArrayMatrixToTextFile(arr, outFile, "TEST", null, null); final INDArray arrLoaded = Nd4jIOUtils.readNDArrayMatrixFromTextFile(outFile); ArrayAsserts.assertArrayEquals(arr.shape(), arrLoaded.shape()); ArrayAsserts.assertArrayEquals(arr.dup().data().asDouble(), arrLoaded.dup().data().asDouble(), 1e-12); }
public void binaryReadWriteAsserter(final INDArray arr) { final File outFile = createTempFile("Nd4j_binary_dump_test", ".nd4j"); Nd4jIOUtils.writeNDArrayToBinaryDumpFile(arr, outFile); final INDArray arrLoaded = Nd4jIOUtils.readNDArrayFromBinaryDumpFile(outFile); ArrayAsserts.assertArrayEquals(arr.shape(), arrLoaded.shape()); ArrayAsserts.assertArrayEquals(arr.dup().data().asDouble(), arrLoaded.dup().data().asDouble(), 1e-12); }
public void tsvTensorReadWriteAsserter(final INDArray arr) { final File outFile = createTempFile("Nd4j_tensor_tsv_test", ".tsv"); Nd4jIOUtils.writeNDArrayTensorToTextFile(arr, outFile, "TEST", null); final INDArray arrLoaded = Nd4jIOUtils.readNDArrayTensorFromTextFile(outFile); ArrayAsserts.assertArrayEquals(arr.shape(), arrLoaded.shape()); ArrayAsserts.assertArrayEquals(arr.dup().data().asDouble(), arrLoaded.dup().data().asDouble(), 1e-12); }
public void assertINDArrayToApacheMatrixCorrectness(final INDArray arr) { /* brute force result */ final RealMatrix expected = new BlockRealMatrix(arr.rows(), arr.columns()); for (int i = 0; i < arr.rows(); i++) { for (int j = 0; j < arr.columns(); j++) { expected.setEntry(i, j, arr.getDouble(i, j)); } } final RealMatrix result = Nd4jApacheAdapterUtils.convertINDArrayToApacheMatrix(arr); Assert.assertEquals(result.getColumnDimension(), expected.getColumnDimension()); Assert.assertEquals(result.getRowDimension(), expected.getRowDimension()); for (int i = 0; i < expected.getRowDimension(); i++) { ArrayAsserts.assertArrayEquals(result.getData()[i], expected.getData()[i], EPS); } }
/** Tests the implementation of the AD by comparison to finite difference. */ @Test public void derivativesCorrectness() { for(int looptest=0; looptest < NB_TESTS; looptest++) { double f = AdStarter.f(A[looptest]); double[] dFwd = FiniteDifferenceFirstOrder.differentiate(new f_Function(), A[looptest], EPSILON, FiniteDifferenceSchemes.FORWARD); double[] dBac = FiniteDifferenceFirstOrder.differentiate(new f_Function(), A[looptest], EPSILON, FiniteDifferenceSchemes.BACKWARD); double[] dSym = FiniteDifferenceFirstOrder.differentiate(new f_Function(), A[looptest], EPSILON, FiniteDifferenceSchemes.SYMMETRICAL); double[] d3Or = FiniteDifferenceFirstOrder.differentiate(new f_Function(), A[looptest], EPSILON, FiniteDifferenceSchemes.FOURTH_ORDER); DoubleDerivatives dSad = AdStarter.f_Sad(A[looptest]); DoubleDerivatives dSad2 = AdStarter.f_Sad_Optimized(A[looptest]); DoubleSad[] aSad = DoubleSad.init(A[looptest]); DoubleSad dSadA = AdStarter.f_Sad_Automatic(aSad); DoubleDerivatives dAad = AdStarter.f_Aad(A[looptest]); DoubleDerivatives dAad2 = AdStarter.f_Aad_Optimized(A[looptest]); assertEquals("adStarterAnalysis " + looptest, f, dSad.value(), TOLERANCE_VALUE); ArrayAsserts.assertArrayEquals("adStarterAnalysis " + looptest, dFwd, dSad.derivatives(), TOLERANCE_DELTA_1); ArrayAsserts.assertArrayEquals("adStarterAnalysis " + looptest, dBac, dSad.derivatives(), TOLERANCE_DELTA_1); ArrayAsserts.assertArrayEquals("adStarterAnalysis " + looptest, dSym, dSad.derivatives(), TOLERANCE_DELTA_2); ArrayAsserts.assertArrayEquals("adStarterAnalysis " + looptest, d3Or, dSad.derivatives(), TOLERANCE_DELTA_2); assertEquals("adStarterAnalysis " + looptest, f, dSad2.value(), TOLERANCE_VALUE); ArrayAsserts.assertArrayEquals("adStarterAnalysis " + looptest, dSad.derivatives(), dSad2.derivatives(), TOLERANCE_DELTA_2); assertEquals("adStarterAnalysis " + looptest, f, dSadA.value(), TOLERANCE_VALUE); ArrayAsserts.assertArrayEquals("adStarterAnalysis " + looptest, dSad.derivatives(), dSadA.derivatives(), TOLERANCE_DELTA_2); assertEquals("adStarterAnalysis " + looptest, f, dAad.value(), TOLERANCE_VALUE); ArrayAsserts.assertArrayEquals("adStarterAnalysis " + looptest, dSad.derivatives(), dAad.derivatives(), TOLERANCE_DELTA_2); assertEquals("adStarterAnalysis " + looptest, f, dAad2.value(), TOLERANCE_VALUE); ArrayAsserts.assertArrayEquals("adStarterAnalysis " + looptest, dAad.derivatives(), dAad2.derivatives(), TOLERANCE_DELTA_2); } }