src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
HenselLifting { @SuppressWarnings("unchecked") public static < Term extends AMonomial<Term>, Poly extends AMultivariatePolynomial<Term, Poly>, uPoly extends IUnivariatePolynomial<uPoly>> void bivariateLiftNoLCCorrection0(Poly base, Poly[] factors, IEvaluation<Term, Poly> evaluation, int degreeBound) { Ring<uPoly> uRing = new UnivariateRing<>((uPoly) factors[0].asUnivariate()); UnivariatePolynomial<uPoly>[] res = bivariateLiftDense(seriesExpansionDense(uRing, base, 1, evaluation), asUnivariate(factors, evaluation), degreeBound); for (int i = 0; i < res.length; i++) factors[i].set(denseSeriesToPoly(base, res[i], 1, evaluation)); } private HenselLifting(); @SuppressWarnings("unchecked") static void bivariateLiftNoLCCorrection0(Poly base, Poly[] factors, IEvaluation<Term, Poly> evaluation, int degreeBound); @SuppressWarnings("unchecked") static UnivariatePolynomial<uPoly> seriesExpansionDense(Ring<uPoly> ring, Poly poly, int variable, IEvaluation<Term, Poly> evaluate); static void multivariateLiftAutomaticLC(Poly base, Poly[] factors, IEvaluation<Term, Poly> evaluation); static void multivariateLiftAutomaticLC(Poly base, Poly[] factors, IEvaluation<Term, Poly> evaluation, int from); }
@Test public void testBivariateLiftingRandom2() throws Exception { MultivariateFactorizationTest.lSampleDecompositionSource baseSource = new MultivariateFactorizationTest.lSampleDecompositionSource( 3, 5, 2, 2, 2, 6, 1, 4); baseSource.minModulusBits = 15; baseSource.maxModulusBits = 30; FactorizationInput.SampleDecompositionSource<MultivariatePolynomialZp64> source = orderVarsByDegree( filterMonomialContent( filterNonSquareFree(baseSource))); testHenselLift(source, AbstractTest.its(500, 1000), lEvaluationLoop::new, ((base, factors, factorsLC, evaluation, degreeBounds, from) -> HenselLifting.bivariateLiftNoLCCorrection0(base, factors, evaluation, degreeBounds[1])), false, 1); }
HenselLifting { @SuppressWarnings("unchecked") static <Term extends AMonomial<Term>, Poly extends AMultivariatePolynomial<Term, Poly>> void multivariateLift0(Poly base, Poly[] factors, Poly[] factorsLC, IEvaluation<Term, Poly> evaluation, int[] degreeBounds) { multivariateLift0(base, factors, factorsLC, evaluation, degreeBounds, 1); } private HenselLifting(); @SuppressWarnings("unchecked") static void bivariateLiftNoLCCorrection0(Poly base, Poly[] factors, IEvaluation<Term, Poly> evaluation, int degreeBound); @SuppressWarnings("unchecked") static UnivariatePolynomial<uPoly> seriesExpansionDense(Ring<uPoly> ring, Poly poly, int variable, IEvaluation<Term, Poly> evaluate); static void multivariateLiftAutomaticLC(Poly base, Poly[] factors, IEvaluation<Term, Poly> evaluation); static void multivariateLiftAutomaticLC(Poly base, Poly[] factors, IEvaluation<Term, Poly> evaluation, int from); }
@Test public void test4() throws Exception { PrivateRandom.getRandom().setSeed(50); IntegersZp64 domain = new IntegersZp64(592346501); String[] vars = {"a", "b"}; MultivariatePolynomialZp64 a = MultivariatePolynomialZp64.parse("8864159 + 332216825*a + 307171438*a^2 + 574396609*a^3 + b", domain, vars), b = MultivariatePolynomialZp64.parse("364341910 + 56968290*a + 134477777*a^2 + 264733241*b + 223672725*a*b + 365910146*a^2*b + 448183856*b^2 + 56041492*a*b^2 + 1386*a^2*b^2", domain, vars), base = a.clone().multiply(b); lEvaluation evaluation = new lEvaluation(base.nVariables, new long[]{0}, domain, base.ordering); MultivariatePolynomialZp64[] uFactors = { evaluation.evaluateFrom(a, 1), evaluation.evaluateFrom(b, 1), }; uFactors[1].multiplyByLC(uFactors[0]); uFactors[0].monic(); System.out.println(uFactors[0]); System.out.println(uFactors[1]); MultivariatePolynomialZp64[] factorsLC = { null, base.lc(0) }; HenselLifting.multivariateLift0(base, uFactors, factorsLC, evaluation, base.degrees()); Assert.assertEquals(base, multiply(uFactors)); }
HenselLifting { public static < Term extends AMonomial<Term>, Poly extends AMultivariatePolynomial<Term, Poly>> void multivariateLiftAutomaticLC(Poly base, Poly[] factors, IEvaluation<Term, Poly> evaluation) { Poly lc = base.lc(0); if (lc.isConstant()) multivariateLift0(base, factors, null, evaluation, base.degrees()); else { Poly lcCorrection = evaluation.evaluateFrom(lc, 1); assert lcCorrection.isConstant(); for (Poly factor : factors) { assert factor.lt().exponents[0] == factor.degree(0); factor.monicWithLC(lcCorrection.lcAsPoly()); } base = base.clone().multiply(PolynomialMethods.polyPow(lc, factors.length - 1, true)); multivariateLift0(base, factors, ArraysUtil.arrayOf(lc, factors.length), evaluation, base.degrees()); for (Poly factor : factors) factor.set(primitivePart(factor)); } } private HenselLifting(); @SuppressWarnings("unchecked") static void bivariateLiftNoLCCorrection0(Poly base, Poly[] factors, IEvaluation<Term, Poly> evaluation, int degreeBound); @SuppressWarnings("unchecked") static UnivariatePolynomial<uPoly> seriesExpansionDense(Ring<uPoly> ring, Poly poly, int variable, IEvaluation<Term, Poly> evaluate); static void multivariateLiftAutomaticLC(Poly base, Poly[] factors, IEvaluation<Term, Poly> evaluation); static void multivariateLiftAutomaticLC(Poly base, Poly[] factors, IEvaluation<Term, Poly> evaluation, int from); }
@Test public void test5() throws Exception { IntegersZp64 domain = new IntegersZp64(SmallPrimes.nextPrime(66)); String[] vars = {"a", "b", "c"}; MultivariatePolynomialZp64 factors[] = { parse("a^15*b*c^2 + 2*a*b^4 - 3*b + 2 + b^2*a - b^4", domain, vars), parse("a^5*b^6*c^3 + a*b^2 - 3*b^2 + b + 2 - a^3*b^6", domain, vars), }, base = multiply(factors); assert MultivariateGCD.PolynomialGCD(factors).isConstant(); lEvaluation evaluation = new lEvaluation(base.nVariables, new long[]{1, 2}, domain, base.ordering); MultivariatePolynomialZp64[] uFactors = evaluation.evaluateFrom(factors, 1); HenselLifting.multivariateLiftAutomaticLC(base, uFactors, evaluation); Assert.assertEquals(base, multiply(uFactors)); MultivariatePolynomialZp64[] biFactors = evaluation.evaluateFrom(factors, 2); HenselLifting.multivariateLiftAutomaticLC(base, biFactors, evaluation, 2); Assert.assertEquals(base, multiply(biFactors)); }
AlgebraicNumberField extends SimpleFieldExtension<E> { public AlgebraicNumberField(E minimalPoly) { super(minimalPoly); if (minimalPoly.isOverFiniteField()) throw new IllegalArgumentException("Use FiniteField for constructing extensions of finite fields."); } AlgebraicNumberField(E minimalPoly); @Override boolean isField(); @Override boolean isUnit(E element); @Override E gcd(E a, E b); @Override E[] divideAndRemainder(E a, E b); @Override E remainder(E dividend, E divider); E normalizer(E element); @Override Iterator<E> iterator(); }
@Test public void test1() { AlgebraicNumberField<UnivariatePolynomial<Rational<BigInteger>>> field = AlgebraicNumberField(UnivariatePolynomial.create(Q, Q.valueOf(-2), Q.valueOf(0), Q.valueOf(1))); Coder<UnivariatePolynomial<Rational<BigInteger>>, ?, ?> coder = Coder.mkUnivariateCoder(field, "s"); Assert.assertEquals(coder.parse("2"), coder.parse("s^2")); Assert.assertEquals(coder.parse("s/2"), coder.parse("1/s")); Assert.assertEquals(coder.parse("s - 1"), coder.parse("1/(1 + s)")); Assert.assertEquals(coder.parse("-s"), coder.parse("-s")); }
MultipleFieldExtension extends ImageRing<sPoly, mPoly> implements IPolynomialRing<mPoly> { @SuppressWarnings("unchecked") public static < Term extends AMonomial<Term>, mPoly extends AMultivariatePolynomial<Term, mPoly>, sPoly extends IUnivariatePolynomial<sPoly> > MultipleFieldExtension<Term, mPoly, sPoly> mkMultipleExtension(sPoly a) { return mkMultipleExtension(Rings.SimpleFieldExtension(a)); } MultipleFieldExtension(MultipleFieldExtension<Term, mPoly, sPoly>[] tower, UnivariatePolynomial<mPoly>[] minimalPolynomialsOfGenerators, mPoly primitiveElement, sPoly[] generatorsReps, SimpleFieldExtension<sPoly> simpleExtension); @Override int nVariables(); @Override mPoly factory(); @Override mPoly variable(int variable); sPoly getUnivariateFactory(); mPoly getPrimitiveElement(); int degree(); SimpleFieldExtension<sPoly> getSimpleExtension(); UnivariatePolynomial<mPoly> getGeneratorMinimalPoly(int iGenerator); MultipleFieldExtension<Term, mPoly, sPoly> getSubExtension(int i); sPoly getGeneratorRep(int iGenerator); sPoly[] getGeneratorReps(); MultipleFieldExtension<Term, mPoly, sPoly> joinAlgebraicElement(UnivariatePolynomial<mPoly> algebraicElement); MultipleFieldExtension<Term, mPoly, sPoly> joinAlgebraicElement(sPoly minimalPoly); MultipleFieldExtension<Term, mPoly, sPoly> joinRedundantElement(mPoly element); @Override mPoly valueOf(long val); @Override mPoly valueOfBigInteger(BigInteger val); @Override mPoly getZero(); @Override mPoly getOne(); @Override mPoly copy(mPoly element); @Override boolean isZero(mPoly element); @Override boolean isOne(mPoly element); @Override boolean isUnit(mPoly element); @Override mPoly gcd(mPoly a, mPoly b); @Override mPoly[] extendedGCD(mPoly a, mPoly b); @Override mPoly lcm(mPoly a, mPoly b); @Override mPoly gcd(mPoly... elements); @Override mPoly gcd(Iterable<mPoly> elements); @Override int signum(mPoly element); @Override mPoly factorial(long num); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(IStringifier stringifier); String toString(String... variables); @Override String toString(); @SuppressWarnings("unchecked") static MultipleFieldExtension<Term, mPoly, sPoly> mkMultipleExtension(sPoly a); @SuppressWarnings("unchecked") static MultipleFieldExtension<Term, mPoly, sPoly> mkMultipleExtension(SimpleFieldExtension<sPoly> ext); @SuppressWarnings("unchecked") static MultipleFieldExtension<Term, mPoly, sPoly> mkMultipleExtension(sPoly... minimalPolynomials); @SuppressWarnings("unchecked") static MultipleFieldExtension<Term, mPoly, sPoly> mkSplittingField(sPoly poly); }
@Test public void test1() { UnivariateRing<UnivariatePolynomial<Rational<BigInteger>>> auxRing = UnivariateRing(Q); Coder<UnivariatePolynomial<Rational<BigInteger>>, ?, ?> auxCoder = Coder.mkPolynomialCoder(auxRing, "x"); UnivariatePolynomial<Rational<BigInteger>> minPolySqrt2 = auxCoder.parse("x^2 - 2"), minPolySqrt3 = auxCoder.parse("x^2 + 3"); MultipleFieldExtension< Monomial<Rational<BigInteger>>, MultivariatePolynomial<Rational<BigInteger>>, UnivariatePolynomial<Rational<BigInteger>> > field = MultipleFieldExtension.mkMultipleExtension(minPolySqrt2, minPolySqrt3); Coder<MultivariatePolynomial<Rational<BigInteger>>, ?, ?> coder = Coder.mkPolynomialCoder(field, "s2", "s3"); assertEquals(coder.parse("-6"), field.pow(coder.parse("s2 * s3"), 2)); } @Test @SuppressWarnings("unchecked") public void test2() { UnivariateRing<UnivariatePolynomial<Rational<BigInteger>>> auxRing = UnivariateRing(Q); Coder<UnivariatePolynomial<Rational<BigInteger>>, ?, ?> auxCoder = Coder.mkPolynomialCoder(auxRing, "x"); UnivariatePolynomial<Rational<BigInteger>> minPolySqrt2 = auxCoder.parse("x^2 - 2"), minPolySqrt3 = auxCoder.parse("x^2 + 3"), minPolySqrt5 = auxCoder.parse("x^2 + 5"); for (int i = 0; i < 2; ++i) { long start = System.nanoTime(); MultipleFieldExtension< Monomial<Rational<BigInteger>>, MultivariatePolynomial<Rational<BigInteger>>, UnivariatePolynomial<Rational<BigInteger>> > field = MultipleFieldExtension.mkMultipleExtension(minPolySqrt2, minPolySqrt3, minPolySqrt5); System.out.println("Create extension: " + TimeUnits.nanosecondsToString(System.nanoTime() - start)); Coder<MultivariatePolynomial<Rational<BigInteger>>, ?, ?> coder = Coder.mkPolynomialCoder(field, "s2", "s3", "s5"); assertEquals(coder.parse("(2 * (-3) * (-5)) + 1 / (2 * (-3) * (-5))"), coder.parse("(s2 * s3 * s5)^2 + 1 / (s2 * s3 * s5)^2")); System.out.println("Arithmetic : " + TimeUnits.nanosecondsToString(System.nanoTime() - start)); System.out.println(); } } @Test @SuppressWarnings("unchecked") public void test3() { UnivariateRing<UnivariatePolynomial<Rational<BigInteger>>> auxRing = UnivariateRing(Q); Coder<UnivariatePolynomial<Rational<BigInteger>>, ?, ?> auxCoder = Coder.mkPolynomialCoder(auxRing, "x"); UnivariatePolynomial<Rational<BigInteger>> minPolySqrt2 = auxCoder.parse("x^2 - 2"), minPolySqrt3 = auxCoder.parse("x^2 - 3"), minPolySqrt5 = auxCoder.parse("x^2 - 5"); MultipleFieldExtension< Monomial<Rational<BigInteger>>, MultivariatePolynomial<Rational<BigInteger>>, UnivariatePolynomial<Rational<BigInteger>> > field = MultipleFieldExtension.mkMultipleExtension(minPolySqrt2, minPolySqrt3, minPolySqrt5); Coder<MultivariatePolynomial<Rational<BigInteger>>, ?, ?> cfCoder = Coder.mkPolynomialCoder(field, "s2", "s3", "s5"); UnivariateRing<UnivariatePolynomial<MultivariatePolynomial<Rational<BigInteger>>>> uRing = UnivariateRing(field); Coder<UnivariatePolynomial<MultivariatePolynomial<Rational<BigInteger>>>, ?, ?> coder = Coder.mkUnivariateCoder(uRing, cfCoder, "x"); UnivariatePolynomial<MultivariatePolynomial<Rational<BigInteger>>> poly = coder.parse("((x - s2) * (x - s3) * (x - s5))^2"); PolynomialFactorDecomposition<UnivariatePolynomial<MultivariatePolynomial<Rational<BigInteger>>>> factors = UnivariateFactorization.Factor(poly); assertEquals(3, factors.size()); assertEquals(6, factors.sumExponents()); assertEquals(poly, factors.multiply()); } @Test @SuppressWarnings("unchecked") public void test4() { UnivariateRing<UnivariatePolynomial<Rational<BigInteger>>> auxRing = UnivariateRing(Q); Coder<UnivariatePolynomial<Rational<BigInteger>>, ?, ?> auxCoder = Coder.mkPolynomialCoder(auxRing, "x"); UnivariatePolynomial<Rational<BigInteger>> minPolySqrt2 = auxCoder.parse("x^2 - 2"), minPolySqrt3 = auxCoder.parse("x^2 - 3"), minPolySqrt5 = auxCoder.parse("x^2 - 5"); MultipleFieldExtension< Monomial<Rational<BigInteger>>, MultivariatePolynomial<Rational<BigInteger>>, UnivariatePolynomial<Rational<BigInteger>> > field = MultipleFieldExtension.mkMultipleExtension(minPolySqrt2, minPolySqrt3, minPolySqrt5); Coder<MultivariatePolynomial<Rational<BigInteger>>, ?, ?> cfCoder = Coder.mkPolynomialCoder(field, "s2", "s3", "s5"); MultivariateRing<MultivariatePolynomial<MultivariatePolynomial<Rational<BigInteger>>>> mRing = Rings.MultivariateRing(3, field); Coder<MultivariatePolynomial<MultivariatePolynomial<Rational<BigInteger>>>, ?, ?> coder = Coder.mkMultivariateCoder(mRing, cfCoder, "x", "y", "z"); MultivariatePolynomial<MultivariatePolynomial<Rational<BigInteger>>> poly = coder.parse("((x*y - s2) * (y*z - s3) * (x*z - s5))^2"); PolynomialFactorDecomposition<MultivariatePolynomial<MultivariatePolynomial<Rational<BigInteger>>>> factors = MultivariateFactorization.Factor(poly); assertEquals(3, factors.size()); assertEquals(6, factors.sumExponents()); assertEquals(poly, factors.multiply()); }
ChineseRemainders { private ChineseRemainders() {} private ChineseRemainders(); static long ChineseRemainders(long prime1, long prime2, long remainder1, long remainder2); static BigInteger ChineseRemainders(BigInteger prime1, BigInteger prime2, BigInteger remainder1, BigInteger remainder2); static E ChineseRemainders(Ring<E> ring, E prime1, E prime2, E remainder1, E remainder2); static E ChineseRemainders(Ring<E> ring, ChineseRemaindersMagic<E> magic, E remainder1, E remainder2); static ChineseRemaindersMagic<E> createMagic(Ring<E> ring, E prime1, E prime2); static long ChineseRemainders(ChineseRemaindersMagicZp64 magic, long remainder1, long remainder2); static ChineseRemaindersMagicZp64 createMagic(long prime1, long prime2); static long ChineseRemainders(final long[] primes, final long[] remainders); static BigInteger ChineseRemainders(final BigInteger[] primes, final BigInteger[] remainders); static E ChineseRemainders(Ring<E> ring, E[] primes, E[] remainders); }
@Test public void test1() throws Exception { BigInteger[] coprimes = {BigInteger.valueOf(11), BigInteger.valueOf(13)}; BigInteger[] remainders = {BigInteger.valueOf(2123), BigInteger.valueOf(7213)}; BigInteger crt = ChineseRemainders.ChineseRemainders(coprimes, remainders); BigInteger sup = Arrays.stream(coprimes).reduce(ONE, BigInteger::multiply); assertCRT(coprimes, remainders, crt); crt = toSymMod(crt, sup); assertCRT(coprimes, remainders, crt); } @Test public void test2() throws Exception { BigInteger[] coprimes = {BigInteger.valueOf(121), BigInteger.valueOf(13)}; BigInteger[] remainders = {BigInteger.valueOf(2123), BigInteger.valueOf(7213)}; BigInteger crt = ChineseRemainders.ChineseRemainders(coprimes, remainders); BigInteger sup = Arrays.stream(coprimes).reduce(ONE, BigInteger::multiply); assertCRT(coprimes, remainders, crt); crt = toSymMod(crt, sup); assertCRT(coprimes, remainders, crt); } @Test public void testRandom1() throws Exception { RandomGenerator rnd = getRandom(); int bound = 100; SieveOfAtkin sieve = SieveOfAtkin.createSieve(bound); for (int i = 0; i < 1000; i++) { int n = 2 + rnd.nextInt(9); BitSet used = new BitSet(bound); long[] primes = new long[n]; long[] remainders = new long[n]; for (int j = 0; j < n; j++) { int prime; while (!sieve.isPrime(prime = 1 + rnd.nextInt(bound - 1)) || used.get(prime)) ; used.set(prime); primes[j] = prime; Assert.assertTrue(SmallPrimes.isPrime(prime)); remainders[j] = rnd.nextInt(prime); remainders[j] = rnd.nextBoolean() ? -remainders[j] : remainders[j]; } long crt = ChineseRemainders(primes, remainders); for (int j = 0; j < n; j++) Assert.assertEquals(floorMod(crt, primes[j]), floorMod(remainders[j], primes[j])); crt = ChineseRemainders(Arrays.copyOf(primes, 2), Arrays.copyOf(remainders, 2)); Assert.assertEquals(crt, ChineseRemainders(primes[0], primes[1], remainders[0], remainders[1])); } } @Test public void test3() throws Exception { long crt; crt = ChineseRemainders.ChineseRemainders(284407855036305L, 47, 1, -15); Assert.assertEquals(8532235651089151L, crt); crt = ChineseRemainders.ChineseRemainders(284407855036305L, 47, -2, -17); Assert.assertEquals(9669867071234368L, crt); crt = ChineseRemainders.ChineseRemainders(284407855036305L, 47, 2, 17); Assert.assertEquals(3697302115471967L, crt); } @Test public void test4() throws Exception { BigInteger crt; crt = ChineseRemainders.ChineseRemainders(BigInteger.valueOf(284407855036305L), BigInteger.valueOf(47), ONE, BigInteger.valueOf(-15)); Assert.assertEquals(BigInteger.valueOf(8532235651089151L), crt); crt = ChineseRemainders.ChineseRemainders(BigInteger.valueOf(284407855036305L), BigInteger.valueOf(47), BigInteger.valueOf(-2), BigInteger.valueOf(-17)); Assert.assertEquals(BigInteger.valueOf(9669867071234368L), crt); crt = ChineseRemainders.ChineseRemainders(BigInteger.valueOf(284407855036305L), BigInteger.valueOf(47), BigInteger.valueOf(2), BigInteger.valueOf(17)); Assert.assertEquals(BigInteger.valueOf(3697302115471967L), crt); } @Test public void testRandom2() throws Exception { RandomGenerator rnd = getRandom(); int bound = 10000; SieveOfAtkin primes = SieveOfAtkin.createSieve(bound); for (int i = 0; i < 100; i++) { int n = 1 + rnd.nextInt(100); BitSet used = new BitSet(bound); BigInteger[] comprimes = new BigInteger[n]; BigInteger[] remainders = new BigInteger[n]; for (int j = 0; j < n; j++) { int prime; while (!primes.isPrime(prime = 1 + rnd.nextInt(bound - 1)) || used.get(prime)) ; used.set(prime); comprimes[j] = BigInteger.valueOf(prime); Assert.assertTrue(SmallPrimes.isPrime(prime)); remainders[j] = BigInteger.valueOf(rnd.nextInt(prime)); } BigInteger crt = ChineseRemainders.ChineseRemainders(comprimes, remainders); assertCRT(comprimes, remainders, crt); } } @Test public void test6() throws Exception { UnivariatePolynomialZp64 prime1 = UnivariatePolynomialZ64.create(1, 2, 3, 4).modulus(19), prime2 = UnivariatePolynomialZ64.create(1, 2, 1, 1, 1, 1).modulus(19); UnivariatePolynomialZp64 remainder1 = UnivariatePolynomialZ64.create(1, 2, 3).modulus(19), remainder2 = UnivariatePolynomialZ64.create(1, 2, 3, 4, 5).modulus(19); UnivariateRing<UnivariatePolynomialZp64> domain = new UnivariateRing<>(prime1.createOne()); UnivariatePolynomialZp64 crt = ChineseRemainders.ChineseRemainders(domain, prime1, prime2, remainder1, remainder2); assertCRT(domain, new UnivariatePolynomialZp64[]{prime1, prime2}, new UnivariatePolynomialZp64[]{remainder1, remainder2}, crt); }
PrimesIterator { public long take() { if (smallPrimesPointer < smallPrimes.length) return (pointer = smallPrimes[smallPrimesPointer++] + 1) - 1; for (; pointer < smallSieve.getLimit(); ) { if (smallSieve.isPrime((int) (pointer++))) return pointer - 1; } if (pointer < largeSieveLimit) { if (largeSieve == null) largeSieve = SieveOfAtkin.createSieve(largeSieveLimit); for (; pointer < largeSieve.getLimit(); ) if (largeSieve.isPrime((int) pointer++)) return pointer - 1; } if (pointer < Integer.MAX_VALUE - 1) return pointer = SmallPrimes.nextPrime((int) (pointer + 1)); if (pointer < Long.MAX_VALUE - 1) try { return pointer = BigPrimes.nextPrime(BigInteger.valueOf(pointer + 1)).longValueExact(); } catch (ArithmeticException e) { return -1; } return -1; } PrimesIterator(); PrimesIterator(long from); long take(); }
@Test public void test1() throws Exception { PrimesIterator it = new PrimesIterator(); int v = 0; while (v < 100) { long take = it.take(); if (take == -1) break; Assert.assertEquals(SmallPrimes.SmallPrimes9[v++], take); } } @Test public void test2() throws Exception { PrimesIterator it = new PrimesIterator(Integer.MAX_VALUE - 1000); int v = 0; while (++v < 1000) { long take = it.take(); if (take == -1) break; v++; Assert.assertTrue(BigPrimes.isPrime(take)); } } @Test public void test3() throws Exception { Assert.assertEquals(7, new PrimesIterator(6).take()); Assert.assertEquals(7, new PrimesIterator(7).take()); Assert.assertEquals(4099, new PrimesIterator(4096).take()); Assert.assertEquals(4111, new PrimesIterator(4099 + 1).take()); Assert.assertEquals(1677721, new PrimesIterator(1677721).take()); Assert.assertEquals(1677727, new PrimesIterator(1677722).take()); Assert.assertEquals(1677727, new PrimesIterator(1677722).take()); Assert.assertEquals(16777213, new PrimesIterator(16777210).take()); Assert.assertEquals(16777259, new PrimesIterator(16777214).take()); Assert.assertEquals(17777239, new PrimesIterator(17777214).take()); Assert.assertEquals(1771277227, new PrimesIterator(1771277214).take()); Assert.assertEquals(38873, new PrimesIterator(38873).take()); } @Test public void test4() throws Exception { int mp = SmallPrimes.SmallPrimes12[SmallPrimes.SmallPrimes12.length - 1]; int sp = SieveOfAtkin.SmallPrimesSieve.lastPrime(); for (int start : new int[]{0, mp - 10, mp - 2, mp - 1, mp, mp + 1, mp + 2, sp - 10, sp - 1, sp - 2, sp, sp + 1, sp + 2}) { PrimesIterator it = new PrimesIterator(start); int prev = (int) it.take(); for (int i = 0; i < 100; i++) { int prime = (int) it.take(); Assert.assertEquals(SmallPrimes.nextPrime(prev + 1), prime); prev = prime; } } }
BigPrimes { public static BigInteger nextPrime(BigInteger n) { while (!isPrime(n)) n = n.nextProbablePrime(); return n; } private BigPrimes(); static boolean isPrime(long n); static boolean isPrime(BigInteger n); static boolean LucasPrimalityTest(BigInteger n, int k, RandomGenerator rnd); static BigInteger nextPrime(BigInteger n); static long nextPrime(long n); static BigInteger fermat(BigInteger n, long upperBound); static BigInteger PollardRho(BigInteger n, int attempts, RandomGenerator rn); static BigInteger PollardRho(BigInteger n, long upperBound); static BigInteger PollardP1(BigInteger n, long upperBound); static BigInteger QuadraticSieve(BigInteger n, int bound); static long[] primeFactors(long num); static List<BigInteger> primeFactors(BigInteger num); }
@Test public void test3() throws Exception { for (int i = 0; i < 1000; i++) assertEquals(SmallPrimes.nextPrime(i), BigPrimes.nextPrime(BigInteger.valueOf(i)).intValue()); }
SmallPrimes { public static boolean isPrime(int n) { if (n < 2) return false; for (int p : SmallPrimes12) if (0 == (n % p)) return n == p; return millerRabinPrimeTest(n); } private SmallPrimes(); static boolean isPrime(int n); static int nextPrime(int n); static boolean millerRabinPrimeTest(final int n); static int smallTrialDivision(int n, final TIntArrayList factors); static int boundedTrialDivision(int n, int maxFactor, TIntArrayList factors); static int[] primeFactors(int n); }
@Test public void test1() throws Exception { for (int i : SmallPrimes12) assertTrue(SmallPrimes.isPrime(i)); } @Test public void test5() throws Exception { SieveOfAtkin sieve = SieveOfAtkin.createSieve(PRIMES12_LAST); int p = 0; for (int i = 0; i < PRIMES12_LAST; i++) if (sieve.isPrime(i)) assertEquals(i, SmallPrimes12[p++]); }
SmallPrimes { public static int nextPrime(int n) { if (n < 0) throw new IllegalArgumentException("Negative input: " + n); if (n == 2) return 2; n = n | 1; if (n == 1) { return 2; } if (isPrime(n)) { return n; } final int rem = n % 3; if (0 == rem) { n += 2; } else if (1 == rem) { n += 4; } while (true) { if (isPrime(n)) { return n; } n += 2; if (isPrime(n)) { return n; } n += 4; } } private SmallPrimes(); static boolean isPrime(int n); static int nextPrime(int n); static boolean millerRabinPrimeTest(final int n); static int smallTrialDivision(int n, final TIntArrayList factors); static int boundedTrialDivision(int n, int maxFactor, TIntArrayList factors); static int[] primeFactors(int n); }
@Test public void test6() throws Exception { assertEquals(Integer.MAX_VALUE, SmallPrimes.nextPrime(Integer.MAX_VALUE)); }
LinearSolver { public static <E> E[] solve(Ring<E> ring, E[][] lhs, E[] rhs) { int nUnknowns = lhs[0].length; if (nUnknowns == 0) return ring.createArray(0); E[] result = ring.createArray(nUnknowns); SystemInfo info = solve(ring, lhs, rhs, result); if (info != Consistent) throw new ArithmeticException("singular or under-determined matrix"); return result; } private LinearSolver(); static void transposeSquare(Object[][] matrix); static void transposeSquare(long[][] matrix); static int rowEchelonForm(Ring<E> ring, E[][] matrix); static int rowEchelonForm(Ring<E> ring, E[][] matrix, boolean reduce); static int rowEchelonForm(Ring<E> ring, E[][] lhs, E[] rhs); static int rowEchelonForm(Ring<E> ring, E[][] lhs, E[] rhs, boolean reduce, boolean breakOnUnderDetermined); static void reducedRowEchelonForm(Ring<E> ring, E[][] lhs, E[] rhs); static E[] solve(Ring<E> ring, E[][] lhs, E[] rhs); static SystemInfo solve(Ring<E> ring, E[][] lhs, E[] rhs, E[] result); static SystemInfo solve(Ring<E> ring, E[][] lhs, E[] rhs, E[] result, boolean solveIfUnderDetermined); static SystemInfo solve(Ring<E> ring, ArrayList<E[]> lhs, ArrayList<E> rhs, E[] result); static E[] solveVandermonde(Ring<E> ring, E[] row, E[] rhs); static E[] solveVandermondeT(Ring<E> ring, E[] row, E[] rhs); static SystemInfo solveVandermonde(Ring<E> ring, E[] row, E[] rhs, E[] result); static SystemInfo solveVandermondeT(Ring<E> ring, E[] row, E[] rhs, E[] result); static int rowEchelonForm(IntegersZp64 ring, long[][] matrix); static int rowEchelonForm(IntegersZp64 ring, long[][] matrix, boolean reduce); static int rowEchelonForm(IntegersZp64 ring, long[][] lhs, long[] rhs); static int rowEchelonForm(IntegersZp64 ring, long[][] lhs, long[] rhs, boolean reduce, boolean breakOnUnderDetermined); static void reducedRowEchelonForm(IntegersZp64 ring, long[][] lhs, long[] rhs); static long[] solve(IntegersZp64 ring, long[][] lhs, long[] rhs); static SystemInfo solve(IntegersZp64 ring, long[][] lhs, long[] rhs, long[] result); static SystemInfo solve(IntegersZp64 ring, long[][] lhs, long[] rhs, long[] result, boolean solveIfUnderDetermined); static SystemInfo solve(IntegersZp64 ring, ArrayList<long[]> lhs, TLongArrayList rhs, long[] result); static long[] solveVandermonde(IntegersZp64 ring, long[] row, long[] rhs); static long[] solveVandermondeT(IntegersZp64 ring, long[] row, long[] rhs); static SystemInfo solveVandermonde(IntegersZp64 ring, long[] row, long[] rhs, long[] result); static SystemInfo solveVandermondeT(IntegersZp64 ring, long[] row, long[] rhs, long[] result); }
@Test public void test1() throws Exception { long[][] system = {{1, 2, 13}, {2, 14, 3}, {11, 2, 13}}; long[] rhs = {1, 2, 13}; BigInteger[] r = solve(new IntegersZp(SmallPrimes.nextPrime(12324)), convert(system), convert(rhs)); Assert.assertArrayEquals(convert(new long[]{2467, 9625, 6865}), r); } @Test public void test2() throws Exception { long[][] lhs0 = { {14945154, 0, 0, 0, 0, 0, 0, 0}, {15840518, 0, 0, 0, 0, 0, 0, 23072526}, {0, 1, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 0, 18556231}, {0, 0, 7274769, 0, 0, 0, 0, 0}, {0, 0, 1285016, 0, 0, 0, 0, 2411651}, {0, 0, 0, 9614891, 7274769, 0, 0, 0}, {0, 0, 0, 4514307, 1285016, 0, 0, 17488741}, {0, 0, 0, 0, 0, 9614891, 0, 0}, {0, 0, 0, 0, 0, 4514307, 0, 7852752}, {0, 0, 0, 0, 0, 0, 9614891, 0}, {0, 0, 0, 0, 0, 0, 4514307, 22089485}}; long[] rhs0 = {1, 0, 22655879, 0, 12777324, 0, 1128298, 0, 20152010, 0, 4506067, 0}; long modulus = 23072527; BigInteger[][] lhs = convert(lhs0); BigInteger[] rhs = convert(rhs0); IntegersZp domain = new IntegersZp(modulus); BigInteger[] solution = solve(domain, lhs, rhs); long[] expected = {16402965, 22655879, 11505290, 2916536, 13894224, 7600529, 2132874, 14945154}; Assert.assertArrayEquals(convert(expected), solution); } @Test public void test2a() throws Exception { long[][] lhs0 = { {14945154, 0, 0, 0, 0, 0, 0, 0}, {14945154, 0, 0, 0, 0, 0, 0, 0}, {14945154, 0, 0, 0, 0, 0, 0, 0}, {15840518, 0, 0, 0, 0, 0, 0, 23072526}, {0, 1, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 0, 18556231}, {0, 0, 7274769, 0, 0, 0, 0, 0}, {0, 0, 1285016, 0, 0, 0, 0, 2411651}, {0, 0, 0, 9614891, 7274769, 0, 0, 0}, {0, 0, 0, 4514307, 1285016, 0, 0, 17488741}, {0, 0, 0, 0, 0, 9614891, 0, 0}, {0, 0, 0, 0, 0, 4514307, 0, 7852752}, {0, 0, 0, 0, 0, 0, 9614891, 0}, {0, 0, 0, 0, 0, 0, 4514307, 22089485}}; long[] rhs0 = {1, 1, 1, 0, 22655879, 0, 12777324, 0, 1128298, 0, 20152010, 0, 4506067, 0}; long modulus = 23072527; BigInteger[][] lhs = convert(lhs0); BigInteger[] rhs = convert(rhs0); IntegersZp domain = new IntegersZp(modulus); BigInteger[] solution = solve(domain, lhs, rhs); long[] expected = {16402965, 22655879, 11505290, 2916536, 13894224, 7600529, 2132874, 14945154}; Assert.assertArrayEquals(convert(expected), solution); } @Test public void test3() throws Exception { long[][] lhs0 = { {1, 0, 0, 0, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 0, 5642358}, {0, 1, 1168354, 5331039, 0, 0, 0, 0}, {0, 1, 798805, 1341857, 0, 0, 0, 5298367}, {0, 0, 0, 0, 3103458, 0, 0, 0}, {0, 0, 0, 0, 1168354, 0, 0, 4274594}, {0, 0, 0, 0, 0, 1, 1168354, 0}, {0, 0, 0, 0, 0, 1, 798805, 4627257} }; long[] rhs0 = {1, 0, 740880, 0, 1693671, 0, 810986, 0}; long modulus = 5642359; BigInteger[] solution = new BigInteger[rhs0.length]; SystemInfo r = solve(new IntegersZp(modulus), convert(lhs0), convert(rhs0), solution); assertEquals(SystemInfo.UnderDetermined, r); } @Test public void test4() throws Exception { long[][] lhs = { {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}, {3, 4, 2, 1, 3, 2} }; long[] rhs = {1, 1, 2}; long[] solution = new long[lhs[0].length]; IntegersZp64 ring = new IntegersZp64(17); SystemInfo r = solve(ring, deepClone(lhs), rhs.clone(), solution, true); assertEquals(SystemInfo.Consistent, r); assertTrue(isSolution(ring, lhs, solution, rhs)); } @Test public void test5() { long[][] lhs = {{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 16, 0, 0, 0, 0, 0, 0, 0, 2, 0, 16, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0, 1, 1, 0}, {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 1, 1}, {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; long[] rhs = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; long[] solution = new long[lhs[0].length]; IntegersZp64 ring = new IntegersZp64(17); SystemInfo r = solve(ring, deepClone(lhs), rhs.clone(), solution, true); assertEquals(SystemInfo.Consistent, r); assertTrue(isSolution(ring, lhs, solution, rhs)); } @Test public void test7() { IntegersZp64 ring = new IntegersZp64(SmallPrimes.nextPrime(1000)); long[][] lhs = { {529, 862, 507}, {427, 116, 939}, {281, 3, 477}, }; long[] rhs = {406, 346, 754}; long[] solution = new long[lhs[0].length]; SystemInfo r = solve(ring, deepClone(lhs), rhs.clone(), solution, true); assertEquals(SystemInfo.Consistent, r); assertTrue(isSolution(ring, lhs, solution, rhs)); } @Test public void test8() { IntegersZp64 ring = new IntegersZp64(SmallPrimes.nextPrime(1000)); long[][] lhs = { {927, 433, 167, 418}, {671, 760, 276, 769}, {485, 535, 316, 204}, }; long[] rhs = {437, 433, 646}; long[] solution = new long[lhs[0].length]; SystemInfo r = solve(ring, deepClone(lhs), rhs.clone(), solution, true); assertEquals(SystemInfo.Consistent, r); assertTrue(isSolution(ring, lhs, solution, rhs)); } @Test public void test9() { IntegersZp64 ring = new IntegersZp64(SmallPrimes.nextPrime(1000)); long[][] lhs = { {86, 300, 654}, {421, 15, 279}, {143, 380, 386}, }; long[] rhs = {701, ring.modulus(-1), 499}; long[] solution = new long[lhs[0].length]; SystemInfo r = solve(ring, deepClone(lhs), rhs.clone(), solution, true); assertEquals(SystemInfo.Consistent, r); assertTrue(isSolution(ring, lhs, solution, rhs)); } @Test public void test10() { IntegersZp64 ring = new IntegersZp64(SmallPrimes.nextPrime(1000)); long[][] lhs = { {815, 0, 342}, {170, 536, 982}, {267, 31, 878} }; long[] rhs = {433, 263, 439}; long[] solution = new long[lhs[0].length]; SystemInfo r = solve(ring, deepClone(lhs), rhs.clone(), solution, true); assertEquals(SystemInfo.Inconsistent, r); } @Test public void test11() { IntegersZp64 ring = new IntegersZp64(17); long[][] lhs = { {5, 9, 8, 4, 0, 10, 14, 12, 16, 16}, {2, 11, 6, 2, 9, 16, 11, 2, 4, 15}, {15, 11, 16, 5, 9, 16, 12, 15, 2, 6}, {0, 10, 11, 2, 0, 13, 11, 15, 16, 14}, {8, 6, 12, 7, 2, 2, 14, 14, 6, 16}, {16, 3, 1, 2, 3, 8, 10, 13, 3, 9}, {1, 2, 12, 16, 1, 12, 14, 15, 10, 2}, {6, 5, 5, 15, 11, 3, 15, 15, 3, 14}, {1, 12, 11, 4, 1, 0, 7, 7, 11, 0}, {14, 14, 3, 0, 15, 10, 1, 2, 10, 14} }; long[] rhs = {2, 5, 13, 1, 15, 13, 12, 14, 6, 8}; long[] solution = new long[lhs[0].length]; SystemInfo r = solve(ring, deepClone(lhs), rhs.clone(), solution, true); assertEquals(SystemInfo.Inconsistent, r); } @Test public void test12() { IntegersZp64 ring = new IntegersZp64(17); long[][] lhs = { {8, 9, 6, 13, 4, 8, 11, 12, 15, 9}, {11, 2, 3, 5, 8, 9, 6, 2, 8, 15}, {15, 15, 10, 6, 5, 8, 3, 13, 12, 16}, {15, 2, 14, 14, 0, 5, 5, 0, 9, 15}, {12, 11, 9, 9, 5, 4, 2, 2, 0, 3}, {12, 9, 14, 5, 9, 10, 7, 4, 15, 4}, {2, 16, 16, 5, 16, 10, 3, 0, 15, 3}, {14, 13, 13, 0, 4, 14, 12, 13, 1, 3}, {0, 15, 1, 10, 13, 2, 3, 4, 13, 6}, {6, 7, 2, 11, 14, 1, 6, 6, 7, 5} }; long[] rhs = {6, 10, 5, 2, 8, 8, 8, 14, 8, 5}; long[] solution = new long[lhs[0].length]; SystemInfo r = solve(ring, deepClone(lhs), rhs.clone(), solution, true); assertEquals(SystemInfo.Consistent, r); assertTrue(isSolution(ring, lhs, solution, rhs)); }
RandomUnivariatePolynomials { public static UnivariatePolynomialZp64 randomMonicPoly(int degree, long modulus, RandomGenerator rnd) { UnivariatePolynomialZ64 r = randomPoly(degree, modulus, rnd); while (r.data[degree] % modulus == 0) { r.data[r.degree] = rnd.nextLong(); } return r.modulus(modulus, false).monic(); } private RandomUnivariatePolynomials(); @SuppressWarnings("unchecked") static Poly randomPoly(Poly factory, int degree, RandomGenerator rnd); static UnivariatePolynomialZ64 randomPoly(int degree, RandomGenerator rnd); static UnivariatePolynomialZp64 randomMonicPoly(int degree, long modulus, RandomGenerator rnd); static UnivariatePolynomial<BigInteger> randomMonicPoly(int degree, BigInteger modulus, RandomGenerator rnd); static UnivariatePolynomial<E> randomMonicPoly(int degree, Ring<E> ring, RandomGenerator rnd); static UnivariatePolynomialZ64 randomPoly(int degree, long bound, RandomGenerator rnd); static UnivariatePolynomial<BigInteger> randomPoly(int degree, BigInteger bound, RandomGenerator rnd); static UnivariatePolynomial<E> randomPoly(int degree, Ring<E> ring, RandomGenerator rnd); static UnivariatePolynomial<E> randomPoly(int degree, Ring<E> ring, Function<RandomGenerator, E> method, RandomGenerator rnd); static long[] randomLongArray(int degree, long bound, RandomGenerator rnd); static BigInteger[] randomBigArray(int degree, BigInteger bound, RandomGenerator rnd); static E[] randomArray(int degree, Ring<E> ring, RandomGenerator rnd); static E[] randomArray(int degree, Ring<E> ring, Function<RandomGenerator, E> method, RandomGenerator rnd); }
@Test public void test1() throws Exception { RandomGenerator rnd = getRandom(); rnd.setSeed(94); UnivariatePolynomialZp64 p = RandomUnivariatePolynomials.randomMonicPoly(30, 3816990131L, rnd); assertTrue(p.isMonic()); }
EqualDegreeFactorization { public static <Poly extends IUnivariatePolynomial<Poly>> PolynomialFactorDecomposition<Poly> CantorZassenhaus(Poly input, int d) { Util.ensureOverFiniteField(input); PolynomialFactorDecomposition<Poly> result = PolynomialFactorDecomposition.unit(input.lcAsPoly()); if (!input.coefficientRingCardinality().testBit(0)) CantorZassenhaus(input, d, result, input.coefficientRingPerfectPowerExponent().intValueExact()); else CantorZassenhaus(input, d, result, -1); return result; } private EqualDegreeFactorization(); static PolynomialFactorDecomposition<Poly> CantorZassenhaus(Poly input, int d); }
@Test public void test1() throws Exception { int modulus = 6101; UnivariatePolynomialZp64 a = UnivariatePolynomialZ64.create(5224, 5225, 5225, 5225, 1).modulus(modulus); for (int i = 0; i < 10; i++) Assert.assertEquals(4, EqualDegreeFactorization.CantorZassenhaus(a, 1).size()); } @Test public void test2() throws Exception { int modulus = 13; UnivariatePolynomialZp64 poly = UnivariatePolynomialZ64.create(9, 0, 1).modulus(modulus); Assert.assertEquals(2, EqualDegreeFactorization.CantorZassenhaus(poly, 1).size()); }
Rationals implements Ring<Rational<E>> { @SuppressWarnings("unchecked") private FactorDecomposition<Rational<E>> factor(Rational<E> element, Function<E, FactorDecomposition<E>> factor) { if (element.isZero()) return FactorDecomposition.of(this, element); FactorDecomposition<E> numFactors = element.numerator.stream() .map(factor) .reduce(FactorDecomposition.empty(ring), FactorDecomposition::addAll); FactorDecomposition<Rational<E>> factors = FactorDecomposition.empty(this); for (int i = 0; i < numFactors.size(); i++) factors.addNonUnitFactor(new Rational<>(ring, numFactors.get(i)), numFactors.getExponent(i)); factors.addFactor(new Rational<>(ring, numFactors.unit), 1); FactorDecomposition<E> denFactors = element.denominator.stream() .map(factor) .reduce(FactorDecomposition.empty(ring), FactorDecomposition::addAll); for (int i = 0; i < denFactors.size(); i++) factors.addNonUnitFactor(new Rational<>(ring, ring.getOne(), denFactors.get(i)), denFactors.getExponent(i)); factors.addFactor(new Rational<>(ring, ring.getOne(), denFactors.unit), 1); return factors; } Rationals(Ring<E> ring); Rational<E> mkNumerator(E num); Rational<E> mkNumerator(long num); Rational<E> mkDenominator(E den); Rational<E> mkDenominator(long den); Rational<E> mk(E num, E den); Rational<E> mk(long num, long den); @Override boolean isField(); @Override boolean isEuclideanRing(); @Override BigInteger cardinality(); @Override BigInteger characteristic(); @Override boolean isPerfectPower(); @Override BigInteger perfectPowerBase(); @Override BigInteger perfectPowerExponent(); @Override Rational<E> add(Rational<E> a, Rational<E> b); @Override Rational<E> subtract(Rational<E> a, Rational<E> b); @Override Rational<E> multiply(Rational<E> a, Rational<E> b); @Override Rational<E> negate(Rational<E> element); @Override int signum(Rational<E> element); @Override @SuppressWarnings("unchecked") Rational<E>[] divideAndRemainder(Rational<E> dividend, Rational<E> divider); @Override Rational<E> reciprocal(Rational<E> element); @Override Rational<E> gcd(Rational<E> a, Rational<E> b); @Override FactorDecomposition<Rational<E>> factorSquareFree(Rational<E> element); @Override FactorDecomposition<Rational<E>> factor(Rational<E> element); @Override Rational<E> getZero(); @Override Rational<E> getOne(); @Override boolean isZero(Rational<E> element); @Override boolean isOne(Rational<E> element); @Override boolean isUnit(Rational<E> element); @Override Rational<E> valueOf(long val); @Override Rational<E> valueOfBigInteger(BigInteger val); @Override Rational<E> copy(Rational<E> element); @Override Rational<E> valueOf(Rational<E> val); @Override @SuppressWarnings("unchecked") Rational<E>[][] createArray2d(int length); @Override @SuppressWarnings("unchecked") Rational<E>[][] createArray2d(int m, int n); @Override int compare(Rational<E> o1, Rational<E> o2); @Override Rational<E> getNegativeOne(); @Override @SuppressWarnings("unchecked") Rational<E>[] createArray(int length); @Override Rational<E> randomElement(RandomGenerator rnd); @Override Rational<E> randomElementTree(RandomGenerator rnd); @Override Iterator<Rational<E>> iterator(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(IStringifier<Rational<E>> stringifier); @Override String toString(); final Ring<E> ring; }
@Test public void test5() { Assert.assertEquals(2, Q.factor(Q.parse("4/9")).size()); }
UnivariateInterpolation { public static UnivariatePolynomialZp64 interpolateNewton(long modulus, long[] points, long[] values) { return interpolateNewton(new IntegersZp64(modulus), points, values); } private UnivariateInterpolation(); static UnivariatePolynomialZp64 interpolateLagrange(long modulus, long[] points, long[] values); static UnivariatePolynomial<E> interpolateLagrange(Ring<E> ring, E[] points, E[] values); static UnivariatePolynomialZp64 interpolateNewton(long modulus, long[] points, long[] values); static UnivariatePolynomialZp64 interpolateNewton(IntegersZp64 ring, long[] points, long[] values); static UnivariatePolynomial<E> interpolateNewton(Ring<E> ring, E[] points, E[] values); }
@Test public void test4_random() throws Exception { RandomGenerator rnd = getRandom(); RandomDataGenerator rndd = getRandomData(); DescriptiveStatistics lagrange = new DescriptiveStatistics(), newton = new DescriptiveStatistics(); int nIterations = its(100, 1000); for (int n = 0; n < nIterations; n++) { if (nIterations / 10 == n) { lagrange.clear(); newton.clear(); } BigInteger[] points = RandomUtil.randomBigIntegerArray(rndd.nextInt(15, 25), BigInteger.ZERO, BigInteger.SHORT_MAX_VALUE, rnd); BigInteger[] values = RandomUtil.randomBigIntegerArray(points.length, BigInteger.ZERO, BigInteger.SHORT_MAX_VALUE, rnd); BigInteger modulus = BigInteger.valueOf(getModulusRandom(rndd.nextInt(5, 30))); for (int i = 0; i < points.length; ++i) { points[i] = points[i].mod(modulus); values[i] = values[i].mod(modulus); } points = ArraysUtil.getSortedDistinct(points); values = Arrays.copyOf(values, points.length); long start = System.nanoTime(); UnivariatePolynomial<BigInteger> pNewton = interpolateNewton(new IntegersZp(modulus), points, values); newton.addValue(System.nanoTime() - start); assertInterpolation(pNewton, points, values); } System.out.println("Newton : " + TimeUnits.statisticsNanotime(newton)); }
UnivariateResultants { @SuppressWarnings("unchecked") public static <E> E Resultant(UnivariatePolynomial<E> a, UnivariatePolynomial<E> b) { if (Util.isOverMultipleFieldExtension(a)) return (E) ResultantInMultipleFieldExtension((UnivariatePolynomial) a, (UnivariatePolynomial) b); else if (a.isOverFiniteField()) return ClassicalPRS(a, b).resultant(); else if (Util.isOverRationals(a)) return (E) ResultantInQ((UnivariatePolynomial) a, (UnivariatePolynomial) b); else if (a.isOverZ()) return (E) ModularResultant((UnivariatePolynomial) a, (UnivariatePolynomial) b); else if (Util.isOverSimpleNumberField(a)) return (E) ModularResultantInNumberField((UnivariatePolynomial) a, (UnivariatePolynomial) b); else if (Util.isOverRingOfIntegersOfSimpleNumberField(a)) return (E) ModularResultantInRingOfIntegersOfNumberField((UnivariatePolynomial) a, (UnivariatePolynomial) b); else return PrimitiveResultant(a, b, (p, q) -> SubresultantPRS(p, q).resultant()); } private UnivariateResultants(); @SuppressWarnings("unchecked") static Poly DiscriminantAsPoly(Poly a); @SuppressWarnings("unchecked") static E Discriminant(UnivariatePolynomial<E> a); @SuppressWarnings("unchecked") static long Discriminant(UnivariatePolynomialZp64 a); @SuppressWarnings("unchecked") static Poly ResultantAsPoly(Poly a, Poly b); @SuppressWarnings("unchecked") static E Resultant(UnivariatePolynomial<E> a, UnivariatePolynomial<E> b); static long Resultant(UnivariatePolynomialZp64 a, UnivariatePolynomialZp64 b); static List<E> Subresultants(UnivariatePolynomial<E> a, UnivariatePolynomial<E> b); static BigInteger ModularResultant(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); static UnivariatePolynomial<Rational<BigInteger>> ModularResultantInNumberField( UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> a, UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> b); static BigInteger polyPowNumFieldCfBound(BigInteger maxCf, BigInteger maxMinPolyCf, int minPolyDeg, int exponent); static UnivariatePolynomial<BigInteger> ModularResultantInRingOfIntegersOfNumberField( UnivariatePolynomial<UnivariatePolynomial<BigInteger>> a, UnivariatePolynomial<UnivariatePolynomial<BigInteger>> b); static PolynomialRemainderSequenceZp64 ClassicalPRS(UnivariatePolynomialZp64 a, UnivariatePolynomialZp64 b); static PolynomialRemainderSequence<E> ClassicalPRS(UnivariatePolynomial<E> a, UnivariatePolynomial<E> b); static PolynomialRemainderSequence<E> PseudoPRS(UnivariatePolynomial<E> a, UnivariatePolynomial<E> b); static PolynomialRemainderSequence<E> PrimitivePRS(UnivariatePolynomial<E> a, UnivariatePolynomial<E> b); static PolynomialRemainderSequence<E> ReducedPRS(UnivariatePolynomial<E> a, UnivariatePolynomial<E> b); static PolynomialRemainderSequence<E> SubresultantPRS(UnivariatePolynomial<E> a, UnivariatePolynomial<E> b); }
@Test public void test7() throws Exception { UnivariatePolynomial<Rational<BigInteger>> a = UnivariatePolynomial.parse("1/22 + 13*x^6 - x^10/91", Q, "x"), b = UnivariatePolynomial.parse("22 - 13*x^3/24 - 23*x^11/91", Q, "x"); assertEquals(Q.parse("425247151599448037618564488318977897156050758819345410383614772923/512834526595668226887325363840230565837440811008"), Resultant(a, b)); }
IrreduciblePolynomials { public static <Poly extends IUnivariatePolynomial<Poly>> boolean irreducibleQ(Poly poly) { if (poly.isOverFiniteField()) return finiteFieldIrreducibleQ(poly); else return !poly.isMonomial() && UnivariateFactorization.Factor(poly).isTrivial(); } private IrreduciblePolynomials(); static boolean irreducibleQ(Poly poly); static boolean finiteFieldIrreducibleQ(Poly poly); static boolean finiteFieldIrreducibleViaModularComposition(Poly poly); static boolean finiteFieldIrreducibleBenOr(Poly poly); static UnivariatePolynomialZp64 randomIrreduciblePolynomial(long modulus, int degree, RandomGenerator rnd); static UnivariatePolynomial<E> randomIrreduciblePolynomial(Ring<E> ring, int degree, RandomGenerator rnd); static UnivariatePolynomial<BigInteger> randomIrreduciblePolynomialOverZ(int degree, RandomGenerator rnd); static Poly randomIrreduciblePolynomial(Poly factory, int degree, RandomGenerator rnd); }
@Test public void testIrreducibleRandom1() throws Exception { RandomGenerator rnd = getRandom(); RandomDataGenerator rndd = getRandomData(); int nIterations = its(5000, 1000); for (int i = 0; i < nIterations; i++) { long modulus = getModulusRandom(rndd.nextInt(5, 15)); UnivariatePolynomialZp64 poly = RandomUnivariatePolynomials.randomMonicPoly(rndd.nextInt(5, 15), modulus, rnd); PolynomialFactorDecomposition<UnivariatePolynomialZp64> factors = UnivariateFactorization.Factor(poly); try { Assert.assertEquals(factors.size() == 1, IrreduciblePolynomials.irreducibleQ(poly)); } catch (Throwable e) { System.out.println("Modulus: " + poly.ring.modulus); System.out.println("Poly: " + poly.toStringForCopy()); System.out.println("Factors: " + factors); System.out.println("Irred: " + IrreduciblePolynomials.irreducibleQ(poly)); throw e; } } } @Test public void test1() throws Exception { UnivariatePolynomialZp64 poly = UnivariatePolynomialZ64.create(18, 92, 51, 36, 61, 93, 14, 13, 45, 11, 21, 79, 61, 1).modulus(97); Assert.assertFalse(IrreduciblePolynomials.irreducibleQ(poly)); } @Test public void test2() throws Exception { UnivariatePolynomialZp64 poly = UnivariatePolynomialZ64.create(42, 73, 0, 79, 47, 1).modulus(89); assertTrue(UnivariateFactorization.Factor(poly).toString(), IrreduciblePolynomials.irreducibleQ(poly)); }
IrreduciblePolynomials { static <Poly extends IUnivariatePolynomial<Poly>> Poly composition( Poly xq, int exponent, Poly poly, UnivariateDivision.InverseModMonomial<Poly> invMod, TIntObjectMap<Poly> cache) { assert exponent > 0; Poly cached = cache.get(exponent); if (cached != null) return cached; Poly result = xq.createMonomial(1); Poly k2p = xq; int rExp = 0, kExp = 1; for (; ; ) { if ((exponent & 1) != 0) cache.put(rExp += kExp, result = ModularComposition.composition(k2p, result, poly, invMod)); exponent = exponent >> 1; if (exponent == 0) { cache.put(rExp, result); return result; } cache.put(kExp *= 2, k2p = ModularComposition.composition(k2p, k2p, poly, invMod)); } } private IrreduciblePolynomials(); static boolean irreducibleQ(Poly poly); static boolean finiteFieldIrreducibleQ(Poly poly); static boolean finiteFieldIrreducibleViaModularComposition(Poly poly); static boolean finiteFieldIrreducibleBenOr(Poly poly); static UnivariatePolynomialZp64 randomIrreduciblePolynomial(long modulus, int degree, RandomGenerator rnd); static UnivariatePolynomial<E> randomIrreduciblePolynomial(Ring<E> ring, int degree, RandomGenerator rnd); static UnivariatePolynomial<BigInteger> randomIrreduciblePolynomialOverZ(int degree, RandomGenerator rnd); static Poly randomIrreduciblePolynomial(Poly factory, int degree, RandomGenerator rnd); }
@Test public void test3() throws Exception { UnivariatePolynomialZp64 poly = UnivariatePolynomialZ64.create(952, 1768, 349, 1839, 1538, 1851, 941, 167, 1).modulus(1861); int exponent = 7; UnivariateDivision.InverseModMonomial<UnivariatePolynomialZp64> invMod = UnivariateDivision.fastDivisionPreConditioning(poly); UnivariatePolynomialZp64 xq = createMonomialMod(poly.modulus(), poly, invMod); TIntObjectMap<UnivariatePolynomialZp64> cache = new TIntObjectHashMap<>(); UnivariatePolynomialZp64 actual = IrreduciblePolynomials.composition(xq.clone(), exponent, poly, invMod, cache); UnivariatePolynomialZp64 expected = composition(xq.clone(), exponent, poly, invMod); UnivariatePolynomialZp64 expected0 = createMonomialMod(Rings.Z.pow(BigInteger.valueOf(poly.modulus()), exponent), poly, invMod); Assert.assertEquals(expected, actual); Assert.assertEquals(expected0, actual); } @Test public void testCachedComposition1() throws Exception { RandomGenerator rnd = getRandom(); RandomDataGenerator rndd = getRandomData(); int nIterations = its(100, 1000); for (int i = 0; i < nIterations; i++) { if (i % 10 == 0) System.out.println(i); long modulus = getModulusRandom(rndd.nextInt(5, 15)); UnivariatePolynomialZp64 poly = RandomUnivariatePolynomials.randomMonicPoly(rndd.nextInt(5, 10), modulus, rnd); UnivariateDivision.InverseModMonomial<UnivariatePolynomialZp64> invMod = UnivariateDivision.fastDivisionPreConditioning(poly); UnivariatePolynomialZp64 xq = createMonomialMod(poly.modulus(), poly, invMod); TIntObjectMap<UnivariatePolynomialZp64> cache = new TIntObjectHashMap<>(); int exponent = rndd.nextInt(1, 1024); UnivariatePolynomialZp64 actual = IrreduciblePolynomials.composition(xq.clone(), exponent, poly, invMod, cache); UnivariatePolynomialZp64 expected = composition(xq.clone(), exponent, poly, invMod); String msg = new StringBuilder() .append("\npoly: " + poly.toStringForCopy()) .append("\nmodulus: " + modulus) .append("\nexponent: " + exponent) .toString(); Assert.assertEquals(msg, expected, actual); if (exponent <= 64) Assert.assertEquals(msg, createMonomialMod(Rings.Z.pow(BigInteger.valueOf(poly.modulus()), exponent), poly, invMod), actual); for (int ci : cache.keys()) { msg = msg + "\nexponent: " + ci; Assert.assertEquals(msg, composition(xq.clone(), ci, poly, invMod), cache.get(ci)); if (ci <= 64) Assert.assertEquals(msg, createMonomialMod(Rings.Z.pow(poly.coefficientRingCardinality(), ci), poly, invMod), cache.get(ci)); } } }
UnivariatePolynomialZp64 extends AUnivariatePolynomial64<UnivariatePolynomialZp64> { public static UnivariatePolynomialZp64 create(long modulus, long[] data) { return create(new IntegersZp64(modulus), data); } private UnivariatePolynomialZp64(IntegersZp64 ring, long[] data, int degree); private UnivariatePolynomialZp64(IntegersZp64 ring, long[] data); @Deprecated static UnivariatePolynomialZp64 parse(String string, long modulus); @Deprecated static UnivariatePolynomialZp64 parse(String string, IntegersZp64 modulus); static UnivariatePolynomialZp64 parse(String string, IntegersZp64 modulus, String variable); static UnivariatePolynomialZp64 create(long modulus, long[] data); static UnivariatePolynomialZp64 create(IntegersZp64 ring, long[] data); static UnivariatePolynomialZp64 linear(long cc, long lc, long modulus); static UnivariatePolynomialZp64 createUnsafe(long modulus, long[] data); static UnivariatePolynomialZp64 createUnsafe(IntegersZp64 ring, long[] data); static UnivariatePolynomialZp64 monomial(long modulus, long coefficient, int exponent); static UnivariatePolynomialZp64 constant(long modulus, long value); static UnivariatePolynomialZp64 constant(IntegersZp64 ring, long value); static UnivariatePolynomialZp64 zero(long modulus); static UnivariatePolynomialZp64 zero(IntegersZp64 ring); static UnivariatePolynomialZp64 one(long modulus); static UnivariatePolynomialZp64 one(IntegersZp64 ring); @Override UnivariatePolynomialZp64 setCoefficientRingFrom(UnivariatePolynomialZp64 univariatePolynomialZp64); long modulus(); UnivariatePolynomialZp64 setModulusUnsafe(long newModulus); UnivariatePolynomialZp64 setModulusUnsafe(IntegersZp64 newModulus); UnivariatePolynomialZp64 setModulus(long newModulus); UnivariatePolynomialZp64 setModulus(IntegersZp64 newDomain); @SuppressWarnings("unchecked") UnivariatePolynomialZ64 asPolyZSymmetric(); @SuppressWarnings("unchecked") UnivariatePolynomialZ64 asPolyZ(boolean copy); @Override UnivariatePolynomialZp64[] createArray(int length); @Override UnivariatePolynomialZp64[] createArray(UnivariatePolynomialZp64 a, UnivariatePolynomialZp64 b); @Override UnivariatePolynomialZp64[][] createArray2d(int length); @Override UnivariatePolynomialZp64[][] createArray2d(int length1, int length2); @Override UnivariatePolynomialZp64 getRange(int from, int to); @Override boolean sameCoefficientRingWith(UnivariatePolynomialZp64 oth); @Override UnivariatePolynomialZp64 createFromArray(long[] newData); @Override UnivariatePolynomialZp64 createMonomial(long coefficient, int newDegree); @Override boolean isOverField(); @Override boolean isOverFiniteField(); @Override boolean isOverZ(); @Override BigInteger coefficientRingCardinality(); @Override BigInteger coefficientRingCharacteristic(); @Override boolean isOverPerfectPower(); @Override BigInteger coefficientRingPerfectPowerBase(); @Override BigInteger coefficientRingPerfectPowerExponent(); @Override long content(); @Override UnivariatePolynomialZp64 monic(); @Override UnivariatePolynomialZp64 monic(long factor); @Override UnivariatePolynomialZp64 divideByLC(UnivariatePolynomialZp64 other); UnivariatePolynomialZp64 divide(long val); @Override UnivariatePolynomialZp64 multiplyByBigInteger(BigInteger factor); @Override UnivariatePolynomialZp64 multiply(UnivariatePolynomialZp64 oth); @Override UnivariatePolynomialZp64 square(); @Override UnivariatePolynomialZp64 derivative(); @Override UnivariatePolynomial<BigInteger> toBigPoly(); @Override UnivariatePolynomialZp64 clone(); @Override UnivariatePolynomialZp64 parsePoly(String string); @Override String coefficientRingToString(IStringifier<UnivariatePolynomialZp64> stringifier); @Override MultivariatePolynomialZp64 composition(AMultivariatePolynomial value); @Override MultivariatePolynomialZp64 asMultivariate(); @Override MultivariatePolynomialZp64 asMultivariate(Comparator<DegreeVector> ordering); final IntegersZp64 ring; }
@Test public void test4() throws Exception { System.out.println(UnivariatePolynomialZ64.create(0).firstNonZeroCoefficientPosition()); }
UnivariateDivision { public static UnivariatePolynomialZ64[] divideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, boolean copy) { checkZeroDivider(divider); if (dividend.isZero()) return new UnivariatePolynomialZ64[]{UnivariatePolynomialZ64.zero(), UnivariatePolynomialZ64.zero()}; if (dividend.degree < divider.degree) return new UnivariatePolynomialZ64[]{UnivariatePolynomialZ64.zero(), copy ? dividend.clone() : dividend}; if (divider.degree == 0) { UnivariatePolynomialZ64 div = copy ? dividend.clone() : dividend; div = div.divideOrNull(divider.lc()); if (div == null) return null; return new UnivariatePolynomialZ64[]{div, UnivariatePolynomialZ64.zero()}; } if (divider.degree == 1) return divideAndRemainderLinearDivider(dividend, divider, copy); return divideAndRemainderClassic0(dividend, divider, 1, copy); } private UnivariateDivision(); static T remainderMonomial(T dividend, int xDegree, boolean copy); static UnivariatePolynomialZ64[] divideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, boolean copy); static UnivariatePolynomialZ64[] pseudoDivideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZ64 remainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZ64 quotient(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZp64[] divideAndRemainder(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderClassic(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomial<E>[] divideAndRemainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E>[] pseudoDivideAndRemainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderClassic(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static InverseModMonomial<Poly> fastDivisionPreConditioning(Poly divider); static InverseModMonomial<Poly> fastDivisionPreConditioningWithLCCorrection(Poly divider); static Poly[] divideAndRemainderFast0(Poly dividend, Poly divider, InverseModMonomial<Poly> invRevMod, boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderFast(UnivariatePolynomialZp64 dividend, UnivariatePolynomialZp64 divider, boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderFast(UnivariatePolynomialZp64 dividend, UnivariatePolynomialZp64 divider, InverseModMonomial<UnivariatePolynomialZp64> invMod, boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderFast(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider, boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderFast(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider, InverseModMonomial<UnivariatePolynomial<E>> invMod, boolean copy); static UnivariatePolynomialZp64 remainder(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64 remainderFast(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final InverseModMonomial<UnivariatePolynomialZp64> invMod, final boolean copy); static UnivariatePolynomialZp64 quotient(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64 quotientFast(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final InverseModMonomial<UnivariatePolynomialZp64> invMod, final boolean copy); static UnivariatePolynomial<E> remainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E> remainderFast(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final InverseModMonomial<UnivariatePolynomial<E>> invMod, final boolean copy); static UnivariatePolynomial<E> quotient(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E> quotientFast(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final InverseModMonomial<UnivariatePolynomial<E>> invMod, final boolean copy); @SuppressWarnings("unchecked") static Poly[] pseudoDivideAndRemainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly[] divideAndRemainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly[] divideAndRemainderFast(Poly dividend, Poly divider, InverseModMonomial<Poly> invMod, boolean copy); static Poly divideExact(Poly dividend, Poly divider, boolean copy); static Poly divideOrNull(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly remainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly quotient(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly remainderFast(final Poly dividend, final Poly divider, final InverseModMonomial<Poly> invMod, final boolean copy); static E remainderCoefficientBound(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider); }
@Test @SuppressWarnings("ConstantConditions") public void test1() throws Exception { long modulus = 11; UnivariatePolynomialZp64 a = UnivariatePolynomialZ64.create(3480, 8088, 8742, 13810, 12402, 10418, 8966, 4450, 950).modulus(modulus); UnivariatePolynomialZp64 b = UnivariatePolynomialZ64.create(2204, 2698, 3694, 3518, 5034, 5214, 5462, 4290, 1216).modulus(modulus); UnivariateResultants.APolynomialRemainderSequence<UnivariatePolynomialZp64> prs = UnivariateResultants.ClassicalPRS(a, b); UnivariatePolynomialZp64 gcd = prs.gcd(); assertEquals(3, gcd.degree); assertTrue(UnivariateDivision.divideAndRemainder(a, gcd, true)[1].isZero()); assertTrue(UnivariateDivision.divideAndRemainder(b, gcd, true)[1].isZero()); } @Test public void test3() throws Exception { UnivariatePolynomialZ64 dividend = UnivariatePolynomialZ64.create(28130, 95683, 93697, 176985, 135507, 101513, 75181, 17575); UnivariatePolynomialZ64 divider = UnivariatePolynomialZ64.one(); UnivariatePolynomialZ64[] qr = divideAndRemainder(dividend, divider, true); assertEquals(dividend, qr[0]); assertTrue(qr[1].isZero()); } @Test public void test4_ModularSmallPolynomialsRandom() throws Exception { int thr = 81; RandomGenerator rnd = getRandom(); UnivariatePolynomialZp64[] qd; for (int i = 0; i < its(1000, 10_000); i++) { UnivariatePolynomialZ64 dividend = randomPoly(rnd.nextInt(thr), rnd); UnivariatePolynomialZ64 divider = randomPoly(rnd.nextInt(thr), rnd); for (long prime : getModulusArray(9, 1, 40)) { if (dividend.lc() % prime == 0 || divider.lc() % prime == 0) continue; UnivariatePolynomialZp64 a = dividend.modulus(prime, true); UnivariatePolynomialZp64 b = divider.modulus(prime, true); try { qd = UnivariateDivision.divideAndRemainder(a, b, true); assertQuotientRemainder(a, b, qd); qd = UnivariateDivision.divideAndRemainder(a.clone(), b, false); assertQuotientRemainder(a, b, qd); } catch (Exception err) { System.out.println(dividend.toStringForCopy()); System.out.println(divider.toStringForCopy()); System.out.println(prime); throw err; } } } } @Test public void test4a() throws Exception { long prime = 7; UnivariatePolynomialZp64 dividend = UnivariatePolynomialZ64.create(95, 45, 67, 5, -2, 65, 24, 24, 60).modulus(prime); UnivariatePolynomialZp64 divider = UnivariatePolynomialZ64.create(94, 86).modulus(prime); UnivariatePolynomialZp64[] qd = UnivariateDivision.divideAndRemainder(dividend.clone(), divider, false); assertQuotientRemainder(dividend, divider, qd); } @Test(expected = ArithmeticException.class) public void test8() throws Exception { UnivariatePolynomialZ64 a = UnivariatePolynomialZ64.create(8, -2 * 8, 8, 8 * 2); UnivariatePolynomialZ64 b = UnivariatePolynomialZ64.create(0); divideAndRemainder(a, b, false); } @Test(expected = ArithmeticException.class) public void testDivideByZero() throws Exception { UnivariatePolynomialZp64 poly = UnivariatePolynomialZ64.create(1, 2, 3, 4).modulus(3); System.out.println(Arrays.toString(divideAndRemainder(poly, poly.createZero(), false))); } @Test public void test27_finiteFields() throws Exception { RandomGenerator rnd = getRandom(); RandomDataGenerator rndd = getRandomData(); int minDegree = 5, maxDegree = 15; for (int i = 0; i < its(100, 1000); i++) { UnivariatePolynomial<UnivariatePolynomialZp64> dividend = RandomUnivariatePolynomials.randomMonicPoly(rndd.nextInt(minDegree, maxDegree), FiniteField.GF17p5, rnd), divider = RandomUnivariatePolynomials.randomMonicPoly(rndd.nextInt(1, dividend.degree + 1), FiniteField.GF17p5, rnd); assertQuotientRemainder(dividend, divider, divideAndRemainder(dividend, divider, true)); } }
ArraysUtil { public static void reverse(int[] array, int from, int to) { for (int i = 0; i < (to - from) / 2; ++i) swap(array, from + i, to - 1 - i); } private ArraysUtil(); static int[] flatten(int[][] array); static int[] arrayOf(int val, int len); static long[] arrayOf(long val, int len); static char[] arrayOf(char val, int len); static T[] arrayOf(T val, int len); static int[] negate(int[] arr); static long[] negate(long[] arr); static BigInteger[] negate(BigInteger[] arr); static String toString(long[] a, int from, int to); static String toString(T[] a, int from, int to); static String toString(T[] a, int from, int to, Function<T, String> stringer); static void shuffle(int[] array, RandomGenerator rnd); static int[] getSortedDistinct(int[] values); static BigInteger[] getSortedDistinct(BigInteger[] values); static long[] getSortedDistinct(long[] values); static int[] intSetDifference(int[] main, int[] delete); static int[] intSetUnion(int[] a, int[] b); static int[] insert(int[] array, int position, int value); static int[] insert(int[] array, int position, int value, int length); static long[] insert(long[] array, int position, long value); @SuppressWarnings("unchecked") static T[] insert(T[] array, int position, T value); static void reverse(int[] array, int from, int to); static void reverse(long[] array, int from, int to); static void reverse(T[] array, int from, int to); static void reverse(T[] array); static void reverse(int[] array); static void reverse(long[] array); static int[] short2int(final short[] a); static short[] int2short(final int[] a); static int[] byte2int(final byte[] a); static short[] byte2short(final byte[] a); static byte[] int2byte(final int[] a); static int max(int[] array); static long max(long[] array); static int max(int[] array, int from, int to); static int[] max(int[] a, int[] b); static int min(int[] array); static long min(long[] array); static int min(int[] array, int from, int to); static int[] min(int[] a, int[] b); static int firstIndexOf(int element, int[] array); static int firstIndexOf(Object element, Object[] array); static int indexOfMax(int[] array); static int[] sequence(int size); static int[] sequence(int from, int to); static int[][] deepClone(int[][] input); static Object[][] deepClone(Object[][] input); static int sum(final int[] array); static int[] sum(final int[] a, final int[] b); static int[] multiply(final int[] a, final int[] b); static int[] subtract(final int[] a, final int[] b); static int sum(final int[] array, int from); static int sum(final int[] array, int from, int to); static int multiply(final int[] array, int from, int to); static double multiplyToDouble(final int[] array, int from, int to); static double multiplyToDouble(final int[] array); static double sumToDouble(final int[] array, int from, int to); static double sumToDouble(final int[] array); static int or(final long[] array); static int or(final long[] array, int from); static int or(final long[] array, int from, int to); static int[] bijection(T[] from, T[] to, Comparator<? super T> comparator); static int[] bijection(T[] from, T[] to); static int[] addAll(int[] array1, int... array2); static long[] addAll(long[] array1, long... array2); static int[] addAll(int[]... arrays); static int[] remove(int[] array, int i); static long[] remove(long[] array, int i); static T[] remove(T[] array, int i); @SafeVarargs static T[] addAll(T[] array1, T... array2); static T[] remove(T[] array, int[] positions); static int[] remove(int[] array, int[] positions); static long[] remove(long[] array, int[] positions); static T[] select(T[] array, int[] positions); static int[] select(int[] array, int[] positions); static int[] toArray(Set<Integer> set); static int binarySearch1(int[] a, int key); static int binarySearch1(int[] a, int fromIndex, int toIndex, int key); static int commutativeHashCode(final T[] data); static int commutativeHashCode(T[] data, int from, int to); static int commutativeHashCode(final int[] data); static int commutativeHashCode(int[] data, int from, int to); static void insertionSort(int[] target, int[] coSort); static void insertionSort(int[] target, int fromIndex, int toIndex, int[] coSort); static void insertionSort(int[] target, long[] coSort); static void insertionSort(int[] target, int fromIndex, int toIndex, long[] coSort); static void insertionSort(T[] target, Object[] coSort); static void insertionSort(T[] target, int fromIndex, int toIndex, Object[] coSort); static void insertionSort(T[] target, int[] coSort); static void insertionSort(T[] target, int fromIndex, int toIndex, int[] coSort); static void timSort(int target[], int[] coSort); static void stableSort(int target[], int[] cosort); static int[] quickSortP(int[] target); static void quickSort(int[] target, int[] coSort); static void quickSort(int[] target, int fromIndex, int toIndex, int[] coSort); static void quickSort1(int target[], int fromIndex, int length, int[] coSort); static void swap(int x[], int a, int b); static void quickSort(long[] target, long[] coSort); static void quickSort(long[] target, int fromIndex, int toIndex, long[] coSort); static void quickSort1(long target[], int fromIndex, int length, long[] coSort); static void quickSort(int[] target, long[] coSort); static void quickSort(int[] target, int fromIndex, int toIndex, long[] coSort); static void quickSort1(int target[], int fromIndex, int length, long[] coSort); static void swap(long x[], int a, int b); static void quickSort(T[] target, Object[] coSort); static void quickSort(T[] target, int fromIndex, int toIndex, Object[] coSort); static void quickSort1(T[] target, int fromIndex, int length, Object[] coSort); static void quickSort(T[] target, int[] coSort); static void quickSort(T[] target, int fromIndex, int toIndex, int[] coSort); static void quickSort1(T[] target, int fromIndex, int length, int[] coSort); static void swap(Object[] x, int a, int b); static void quickSort(int[] target, Object[] coSort); static void quickSort(int[] target, int fromIndex, int toIndex, Object[] coSort); static void quickSort1(int target[], int fromIndex, int length, Object[] coSort); static int[] quickSortP(short[] target); static void quickSort(short[] target, int fromIndex, int toIndex, int[] coSort); static void quickSort1(short target[], int fromIndex, int length, int[] coSort); static void quickSort(short[] target, int[] coSort); static void quickSort(int[] target, IntComparator comparator); static void quickSort(int[] target, int fromIndex, int toIndex, IntComparator comparator); static void quickSort1(int target[], int fromIndex, int length, IntComparator comparator); static void quickSort(int[] target, int[] cosort, IntComparator comparator); static void quickSort(int[] target, int fromIndex, int toIndex, int[] cosort, IntComparator comparator); static final Comparator<Object> HASH_COMPARATOR; static final Comparator<int[]> COMPARATOR; static final Comparator<long[]> COMPARATOR_LONG; static final Comparator<Comparable[]> COMPARATOR_GENERIC; }
@Test public void testReverse1() throws Exception { long[] arr = {1, 2, 3}; ArraysUtil.reverse(arr, 0, arr.length); assertArrayEquals(new long[]{3, 2, 1}, arr); arr = new long[]{1, 2, 3, 4}; ArraysUtil.reverse(arr, 0, arr.length); assertArrayEquals(new long[]{4, 3, 2, 1}, arr); }
UnivariateDivision { public static UnivariatePolynomialZ64[] pseudoDivideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy) { checkZeroDivider(divider); if (dividend.isZero()) return new UnivariatePolynomialZ64[]{UnivariatePolynomialZ64.zero(), UnivariatePolynomialZ64.zero()}; if (dividend.degree < divider.degree) return new UnivariatePolynomialZ64[]{UnivariatePolynomialZ64.zero(), copy ? dividend.clone() : dividend}; long factor = MachineArithmetic.safePow(divider.lc(), dividend.degree - divider.degree + 1); if (divider.degree == 0) return new UnivariatePolynomialZ64[]{(copy ? dividend.clone() : dividend).multiply(factor / divider.lc()), UnivariatePolynomialZ64.zero()}; if (divider.degree == 1) return divideAndRemainderLinearDivider0(dividend, divider, factor, copy); return divideAndRemainderClassic0(dividend, divider, factor, copy); } private UnivariateDivision(); static T remainderMonomial(T dividend, int xDegree, boolean copy); static UnivariatePolynomialZ64[] divideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, boolean copy); static UnivariatePolynomialZ64[] pseudoDivideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZ64 remainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZ64 quotient(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZp64[] divideAndRemainder(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderClassic(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomial<E>[] divideAndRemainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E>[] pseudoDivideAndRemainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderClassic(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static InverseModMonomial<Poly> fastDivisionPreConditioning(Poly divider); static InverseModMonomial<Poly> fastDivisionPreConditioningWithLCCorrection(Poly divider); static Poly[] divideAndRemainderFast0(Poly dividend, Poly divider, InverseModMonomial<Poly> invRevMod, boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderFast(UnivariatePolynomialZp64 dividend, UnivariatePolynomialZp64 divider, boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderFast(UnivariatePolynomialZp64 dividend, UnivariatePolynomialZp64 divider, InverseModMonomial<UnivariatePolynomialZp64> invMod, boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderFast(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider, boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderFast(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider, InverseModMonomial<UnivariatePolynomial<E>> invMod, boolean copy); static UnivariatePolynomialZp64 remainder(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64 remainderFast(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final InverseModMonomial<UnivariatePolynomialZp64> invMod, final boolean copy); static UnivariatePolynomialZp64 quotient(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64 quotientFast(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final InverseModMonomial<UnivariatePolynomialZp64> invMod, final boolean copy); static UnivariatePolynomial<E> remainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E> remainderFast(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final InverseModMonomial<UnivariatePolynomial<E>> invMod, final boolean copy); static UnivariatePolynomial<E> quotient(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E> quotientFast(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final InverseModMonomial<UnivariatePolynomial<E>> invMod, final boolean copy); @SuppressWarnings("unchecked") static Poly[] pseudoDivideAndRemainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly[] divideAndRemainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly[] divideAndRemainderFast(Poly dividend, Poly divider, InverseModMonomial<Poly> invMod, boolean copy); static Poly divideExact(Poly dividend, Poly divider, boolean copy); static Poly divideOrNull(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly remainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly quotient(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly remainderFast(final Poly dividend, final Poly divider, final InverseModMonomial<Poly> invMod, final boolean copy); static E remainderCoefficientBound(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider); }
@Test(expected = ArithmeticException.class) public void test2() throws Exception { UnivariatePolynomialZ64 dividend = UnivariatePolynomialZ64.create(28130, 95683, 93697, 176985, 135507, 101513, 75181, 17575, 0); UnivariatePolynomialZ64 divider = UnivariatePolynomialZ64.create(24487310, 38204421, 12930314, 41553770, -1216266, 7382581, 15631547, 0, 0); pseudoDivideAndRemainder(dividend, divider, true); } @Test public void test5_SmallPolynomialsRandom_a() throws Exception { UnivariatePolynomialZ64 dividend = UnivariatePolynomialZ64.create(1, 4, -5, -2, 9, 4, -5, 7, 5, -5, 6, 3, 9, 8, 9, -8); UnivariatePolynomialZ64 divider = UnivariatePolynomialZ64.create(7, 6, -1, 5, 0, 1, 0, 0, 8, 3, 7); UnivariatePolynomialZ64[] qr = pseudoDivideAndRemainder(dividend, divider, true); assertPseudoQuotientRemainder(dividend, divider, qr); } @Test public void test5_SmallPolynomialsRandom_b() throws Exception { UnivariatePolynomialZ64 dividend = UnivariatePolynomialZ64.create(6, 9, 9, 3, 2, 6, -6, 7, -2, 8, 4, -8, 7, 3, 3, -6); UnivariatePolynomialZ64 divider = UnivariatePolynomialZ64.create(0, 0, 0, 3, 1, 8, 8, -5, 6, -7, 9); UnivariatePolynomialZ64[] qr = pseudoDivideAndRemainder(dividend, divider, true); assertPseudoQuotientRemainder(dividend, divider, qr); } @Test public void test5_SmallPolynomialsRandom_с() throws Exception { UnivariatePolynomialZ64 dividend = UnivariatePolynomialZ64.create(5, -6, 0, -9, 3, -1, -5, 8, 0, 1, -1, -8, 8, 2, 0, 2); UnivariatePolynomialZ64 divider = UnivariatePolynomialZ64.create(1, 7, 6, -7, 9, 3, 3, 6, 3, -7, -3); UnivariatePolynomialZ64[] qr = pseudoDivideAndRemainder(dividend, divider, true); UnivariatePolynomialZ64 d = divider.clone().multiply(qr[0]).add(qr[1]); assertPseudoQuotientRemainder(dividend, divider, qr); } @Test public void test26() throws Exception { UnivariatePolynomial<BigInteger> dividend = UnivariatePolynomial.create(Rings.Z, new BigInteger("50924915532280396921059912058744139974274010464717486445566429090906004335144553740099697325823981482217595251233173036221148816419907025031109037285812602964126981398549972404972445712495606246251612602646515107556469916968928792288517114629524761056619784125538889985573728321588316873829401388110009323502747325559537492401603348781184777517075447383315534987333005141430297794452769344710334113504161517191471620923923009168593251562951163703046204657823731073238889133009776679947959284882493347742931374480069087134327139957626655815839165341149468676605096098488269737054120888284410186940922588811865217977201434671980392818129023662348422616219595408007164847429098690018036788941569325028261778694448305169116366300968797299392607269512834399626743351451294227407026614474070168043362619155452474803802317594566620282821580866690460901450722523940253763809526916168510380458823716227207456429213838428363313858223438249583518220909107257207453781168662470638622229018698708892857265124137406565985565106519169754356798964383232"), new BigInteger("37940726704358973981646894376520845717379643722668546596604774191462649371799436327770509765417751410853020097236259181340723780640646980528823132305918233917348431603978910702974168356786878991952039076697435685153720389954147196105732666546398882808075467883408078172773943074952881821883968276970586716085556521926276724965832984764113660527315402786928901376759667964550095121161582001082154197929523015687629358088978002050194666997140380633120191985503069336469087766567723745827536389920145897766163207961925615721265621132693244136269578827145639329792340827479965479742934874844926129035539562075005079119861286286379018264676225498300503424412683235789124363971763488749051910815230910592202224639481529849460050198630242102474952014158371176492350931799358619802630663775654806908014463551827044421713475118514891517003720144816583416199973842512734641894953396023836643821945946850868732474395966931084754653075573569398089513199914298230954227062809869737803168417328622780936780114654437560463636354964403162931061261855232")); UnivariatePolynomial<BigInteger> divider = UnivariatePolynomial.create(Rings.Z, new BigInteger("-425784855629707210539690417657285596009748771201595246777393523226748147711074288140558389550043516613530500261798739170010747708483239470487926534197999795185337107301428405197650111401424401453281285342023506707519100774028143103154883688933695208217191334712115038212326510433566424650523293261999555565022871454564811453312766524934990529599572227820236569578196841210873189542906771110582428737577172320473113774712560826543606283857910494481715951013601677939588946090257941915294685671582476036525511342773894137847945807902831920328130096765066331366254244760254056538237885678798173308462659097285980035599674879837185559523111215792005945149771714839595770409009983341486144352570200746450022078747332821616059006090021772872988207037534463289442687034943036344354336745002436373485142219064592871177691253579923036133374333408048223917924387929466882231114740060638812996586535143719347485716399431436091507892979143097224033509341961137283167473128691774034159819704359664495382150875212794275998540147497752601895426653284077738548432459176682797681127140157440")); assertPseudoQuotientRemainder(dividend, divider, pseudoDivideAndRemainder(dividend, divider, true)); }
UnivariateDivision { static UnivariatePolynomialZ64[] pseudoDivideAndRemainderAdaptive(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy) { checkZeroDivider(divider); if (dividend.isZero()) return new UnivariatePolynomialZ64[]{UnivariatePolynomialZ64.zero(), UnivariatePolynomialZ64.zero()}; if (dividend.degree < divider.degree) return new UnivariatePolynomialZ64[]{UnivariatePolynomialZ64.zero(), copy ? dividend.clone() : dividend}; if (divider.degree == 0) return new UnivariatePolynomialZ64[]{copy ? dividend.clone() : dividend, UnivariatePolynomialZ64.zero()}; if (divider.degree == 1) return pseudoDivideAndRemainderLinearDividerAdaptive(dividend, divider, copy); return pseudoDivideAndRemainderAdaptive0(dividend, divider, copy); } private UnivariateDivision(); static T remainderMonomial(T dividend, int xDegree, boolean copy); static UnivariatePolynomialZ64[] divideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, boolean copy); static UnivariatePolynomialZ64[] pseudoDivideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZ64 remainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZ64 quotient(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZp64[] divideAndRemainder(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderClassic(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomial<E>[] divideAndRemainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E>[] pseudoDivideAndRemainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderClassic(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static InverseModMonomial<Poly> fastDivisionPreConditioning(Poly divider); static InverseModMonomial<Poly> fastDivisionPreConditioningWithLCCorrection(Poly divider); static Poly[] divideAndRemainderFast0(Poly dividend, Poly divider, InverseModMonomial<Poly> invRevMod, boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderFast(UnivariatePolynomialZp64 dividend, UnivariatePolynomialZp64 divider, boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderFast(UnivariatePolynomialZp64 dividend, UnivariatePolynomialZp64 divider, InverseModMonomial<UnivariatePolynomialZp64> invMod, boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderFast(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider, boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderFast(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider, InverseModMonomial<UnivariatePolynomial<E>> invMod, boolean copy); static UnivariatePolynomialZp64 remainder(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64 remainderFast(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final InverseModMonomial<UnivariatePolynomialZp64> invMod, final boolean copy); static UnivariatePolynomialZp64 quotient(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64 quotientFast(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final InverseModMonomial<UnivariatePolynomialZp64> invMod, final boolean copy); static UnivariatePolynomial<E> remainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E> remainderFast(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final InverseModMonomial<UnivariatePolynomial<E>> invMod, final boolean copy); static UnivariatePolynomial<E> quotient(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E> quotientFast(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final InverseModMonomial<UnivariatePolynomial<E>> invMod, final boolean copy); @SuppressWarnings("unchecked") static Poly[] pseudoDivideAndRemainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly[] divideAndRemainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly[] divideAndRemainderFast(Poly dividend, Poly divider, InverseModMonomial<Poly> invMod, boolean copy); static Poly divideExact(Poly dividend, Poly divider, boolean copy); static Poly divideOrNull(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly remainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly quotient(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly remainderFast(final Poly dividend, final Poly divider, final InverseModMonomial<Poly> invMod, final boolean copy); static E remainderCoefficientBound(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider); }
@Test public void test5_SmallPolynomialsRandom_d() throws Exception { RandomGenerator rnd = getRandom(); RandomDataGenerator rndd = getRandomData(); for (int i = 0; i < its(1000, 10_000); i++) { UnivariatePolynomial<BigInteger> dividend = randomPoly(15, 1000, rnd).toBigPoly(); UnivariatePolynomial<BigInteger> divider = randomPoly(rndd.nextInt(1, 10), 1000, rnd).toBigPoly(); UnivariatePolynomial<BigInteger>[] qr = UnivariateDivision.pseudoDivideAndRemainderAdaptive(dividend, divider, true); assertPseudoQuotientRemainder(dividend, divider, qr); qr = UnivariateDivision.pseudoDivideAndRemainderAdaptive(dividend.clone(), divider, false); assertPseudoQuotientRemainder(dividend, divider, qr); } }
UnivariateDivision { public static <Poly extends IUnivariatePolynomial<Poly>> InverseModMonomial<Poly> fastDivisionPreConditioning(Poly divider) { if (!divider.isMonic()) throw new IllegalArgumentException("Only monic polynomials allowed. Input: " + divider); return new InverseModMonomial<>(divider.clone().reverse()); } private UnivariateDivision(); static T remainderMonomial(T dividend, int xDegree, boolean copy); static UnivariatePolynomialZ64[] divideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, boolean copy); static UnivariatePolynomialZ64[] pseudoDivideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZ64 remainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZ64 quotient(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZp64[] divideAndRemainder(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderClassic(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomial<E>[] divideAndRemainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E>[] pseudoDivideAndRemainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderClassic(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static InverseModMonomial<Poly> fastDivisionPreConditioning(Poly divider); static InverseModMonomial<Poly> fastDivisionPreConditioningWithLCCorrection(Poly divider); static Poly[] divideAndRemainderFast0(Poly dividend, Poly divider, InverseModMonomial<Poly> invRevMod, boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderFast(UnivariatePolynomialZp64 dividend, UnivariatePolynomialZp64 divider, boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderFast(UnivariatePolynomialZp64 dividend, UnivariatePolynomialZp64 divider, InverseModMonomial<UnivariatePolynomialZp64> invMod, boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderFast(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider, boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderFast(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider, InverseModMonomial<UnivariatePolynomial<E>> invMod, boolean copy); static UnivariatePolynomialZp64 remainder(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64 remainderFast(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final InverseModMonomial<UnivariatePolynomialZp64> invMod, final boolean copy); static UnivariatePolynomialZp64 quotient(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64 quotientFast(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final InverseModMonomial<UnivariatePolynomialZp64> invMod, final boolean copy); static UnivariatePolynomial<E> remainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E> remainderFast(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final InverseModMonomial<UnivariatePolynomial<E>> invMod, final boolean copy); static UnivariatePolynomial<E> quotient(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E> quotientFast(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final InverseModMonomial<UnivariatePolynomial<E>> invMod, final boolean copy); @SuppressWarnings("unchecked") static Poly[] pseudoDivideAndRemainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly[] divideAndRemainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly[] divideAndRemainderFast(Poly dividend, Poly divider, InverseModMonomial<Poly> invMod, boolean copy); static Poly divideExact(Poly dividend, Poly divider, boolean copy); static Poly divideOrNull(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly remainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly quotient(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly remainderFast(final Poly dividend, final Poly divider, final InverseModMonomial<Poly> invMod, final boolean copy); static E remainderCoefficientBound(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider); }
@Test public void test11_InverseModStructureRandom() throws Exception { RandomGenerator rnd = getRandom(); for (int i = 0; i < its(100, 1000); i++) { long modulus = getModulusRandom(20); UnivariatePolynomialZp64 p = RandomUnivariatePolynomials.randomMonicPoly(2 + rnd.nextInt(100), modulus, rnd); p.data[0] = 1; UnivariateDivision.InverseModMonomial invMod = UnivariateDivision.fastDivisionPreConditioning(p); for (int j = 0; j < 30; j++) { int xDegree = 1 + rnd.nextInt(1025); assertEquals(invMod.getInverse(xDegree), inverseModMonomial0(p.clone().reverse(), xDegree)); } } }
ArraysUtil { public static int[] quickSortP(int[] target) { int[] permutation = new int[target.length]; for (int i = 1; i < target.length; ++i) permutation[i] = i; quickSort(target, 0, target.length, permutation); return permutation; } private ArraysUtil(); static int[] flatten(int[][] array); static int[] arrayOf(int val, int len); static long[] arrayOf(long val, int len); static char[] arrayOf(char val, int len); static T[] arrayOf(T val, int len); static int[] negate(int[] arr); static long[] negate(long[] arr); static BigInteger[] negate(BigInteger[] arr); static String toString(long[] a, int from, int to); static String toString(T[] a, int from, int to); static String toString(T[] a, int from, int to, Function<T, String> stringer); static void shuffle(int[] array, RandomGenerator rnd); static int[] getSortedDistinct(int[] values); static BigInteger[] getSortedDistinct(BigInteger[] values); static long[] getSortedDistinct(long[] values); static int[] intSetDifference(int[] main, int[] delete); static int[] intSetUnion(int[] a, int[] b); static int[] insert(int[] array, int position, int value); static int[] insert(int[] array, int position, int value, int length); static long[] insert(long[] array, int position, long value); @SuppressWarnings("unchecked") static T[] insert(T[] array, int position, T value); static void reverse(int[] array, int from, int to); static void reverse(long[] array, int from, int to); static void reverse(T[] array, int from, int to); static void reverse(T[] array); static void reverse(int[] array); static void reverse(long[] array); static int[] short2int(final short[] a); static short[] int2short(final int[] a); static int[] byte2int(final byte[] a); static short[] byte2short(final byte[] a); static byte[] int2byte(final int[] a); static int max(int[] array); static long max(long[] array); static int max(int[] array, int from, int to); static int[] max(int[] a, int[] b); static int min(int[] array); static long min(long[] array); static int min(int[] array, int from, int to); static int[] min(int[] a, int[] b); static int firstIndexOf(int element, int[] array); static int firstIndexOf(Object element, Object[] array); static int indexOfMax(int[] array); static int[] sequence(int size); static int[] sequence(int from, int to); static int[][] deepClone(int[][] input); static Object[][] deepClone(Object[][] input); static int sum(final int[] array); static int[] sum(final int[] a, final int[] b); static int[] multiply(final int[] a, final int[] b); static int[] subtract(final int[] a, final int[] b); static int sum(final int[] array, int from); static int sum(final int[] array, int from, int to); static int multiply(final int[] array, int from, int to); static double multiplyToDouble(final int[] array, int from, int to); static double multiplyToDouble(final int[] array); static double sumToDouble(final int[] array, int from, int to); static double sumToDouble(final int[] array); static int or(final long[] array); static int or(final long[] array, int from); static int or(final long[] array, int from, int to); static int[] bijection(T[] from, T[] to, Comparator<? super T> comparator); static int[] bijection(T[] from, T[] to); static int[] addAll(int[] array1, int... array2); static long[] addAll(long[] array1, long... array2); static int[] addAll(int[]... arrays); static int[] remove(int[] array, int i); static long[] remove(long[] array, int i); static T[] remove(T[] array, int i); @SafeVarargs static T[] addAll(T[] array1, T... array2); static T[] remove(T[] array, int[] positions); static int[] remove(int[] array, int[] positions); static long[] remove(long[] array, int[] positions); static T[] select(T[] array, int[] positions); static int[] select(int[] array, int[] positions); static int[] toArray(Set<Integer> set); static int binarySearch1(int[] a, int key); static int binarySearch1(int[] a, int fromIndex, int toIndex, int key); static int commutativeHashCode(final T[] data); static int commutativeHashCode(T[] data, int from, int to); static int commutativeHashCode(final int[] data); static int commutativeHashCode(int[] data, int from, int to); static void insertionSort(int[] target, int[] coSort); static void insertionSort(int[] target, int fromIndex, int toIndex, int[] coSort); static void insertionSort(int[] target, long[] coSort); static void insertionSort(int[] target, int fromIndex, int toIndex, long[] coSort); static void insertionSort(T[] target, Object[] coSort); static void insertionSort(T[] target, int fromIndex, int toIndex, Object[] coSort); static void insertionSort(T[] target, int[] coSort); static void insertionSort(T[] target, int fromIndex, int toIndex, int[] coSort); static void timSort(int target[], int[] coSort); static void stableSort(int target[], int[] cosort); static int[] quickSortP(int[] target); static void quickSort(int[] target, int[] coSort); static void quickSort(int[] target, int fromIndex, int toIndex, int[] coSort); static void quickSort1(int target[], int fromIndex, int length, int[] coSort); static void swap(int x[], int a, int b); static void quickSort(long[] target, long[] coSort); static void quickSort(long[] target, int fromIndex, int toIndex, long[] coSort); static void quickSort1(long target[], int fromIndex, int length, long[] coSort); static void quickSort(int[] target, long[] coSort); static void quickSort(int[] target, int fromIndex, int toIndex, long[] coSort); static void quickSort1(int target[], int fromIndex, int length, long[] coSort); static void swap(long x[], int a, int b); static void quickSort(T[] target, Object[] coSort); static void quickSort(T[] target, int fromIndex, int toIndex, Object[] coSort); static void quickSort1(T[] target, int fromIndex, int length, Object[] coSort); static void quickSort(T[] target, int[] coSort); static void quickSort(T[] target, int fromIndex, int toIndex, int[] coSort); static void quickSort1(T[] target, int fromIndex, int length, int[] coSort); static void swap(Object[] x, int a, int b); static void quickSort(int[] target, Object[] coSort); static void quickSort(int[] target, int fromIndex, int toIndex, Object[] coSort); static void quickSort1(int target[], int fromIndex, int length, Object[] coSort); static int[] quickSortP(short[] target); static void quickSort(short[] target, int fromIndex, int toIndex, int[] coSort); static void quickSort1(short target[], int fromIndex, int length, int[] coSort); static void quickSort(short[] target, int[] coSort); static void quickSort(int[] target, IntComparator comparator); static void quickSort(int[] target, int fromIndex, int toIndex, IntComparator comparator); static void quickSort1(int target[], int fromIndex, int length, IntComparator comparator); static void quickSort(int[] target, int[] cosort, IntComparator comparator); static void quickSort(int[] target, int fromIndex, int toIndex, int[] cosort, IntComparator comparator); static final Comparator<Object> HASH_COMPARATOR; static final Comparator<int[]> COMPARATOR; static final Comparator<long[]> COMPARATOR_LONG; static final Comparator<Comparable[]> COMPARATOR_GENERIC; }
@Test public void testShort1() { short[] target = {2, 1, 0}; assertArrayEquals(new int[]{2, 1, 0}, ArraysUtil.quickSortP(target)); } @Test public void testShort2() { short[] target = {2}; assertArrayEquals(new int[]{0}, ArraysUtil.quickSortP(target)); } @Test public void testShort3() { short[] target = new short[0]; assertArrayEquals(new int[0], ArraysUtil.quickSortP(target)); } @Test public void testSortPermutation1() { RandomGenerator rnd = new Well1024a(); for (int i = 0; i < 100; ++i) { int[] a = randomPermutation(10, rnd); int[] sorted = a.clone(); int[] permutation = ArraysUtil.quickSortP(sorted); assertArrayEquals(permute(a, permutation), sorted); } }
UnivariateDivision { public static UnivariatePolynomialZp64[] divideAndRemainderFast(UnivariatePolynomialZp64 dividend, UnivariatePolynomialZp64 divider, boolean copy) { UnivariatePolynomialZp64[] r = earlyDivideAndRemainderChecks(dividend, divider, copy); if (r != null) return r; return divideAndRemainderFast0(dividend, divider, copy); } private UnivariateDivision(); static T remainderMonomial(T dividend, int xDegree, boolean copy); static UnivariatePolynomialZ64[] divideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, boolean copy); static UnivariatePolynomialZ64[] pseudoDivideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZ64 remainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZ64 quotient(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZp64[] divideAndRemainder(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderClassic(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomial<E>[] divideAndRemainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E>[] pseudoDivideAndRemainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderClassic(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static InverseModMonomial<Poly> fastDivisionPreConditioning(Poly divider); static InverseModMonomial<Poly> fastDivisionPreConditioningWithLCCorrection(Poly divider); static Poly[] divideAndRemainderFast0(Poly dividend, Poly divider, InverseModMonomial<Poly> invRevMod, boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderFast(UnivariatePolynomialZp64 dividend, UnivariatePolynomialZp64 divider, boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderFast(UnivariatePolynomialZp64 dividend, UnivariatePolynomialZp64 divider, InverseModMonomial<UnivariatePolynomialZp64> invMod, boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderFast(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider, boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderFast(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider, InverseModMonomial<UnivariatePolynomial<E>> invMod, boolean copy); static UnivariatePolynomialZp64 remainder(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64 remainderFast(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final InverseModMonomial<UnivariatePolynomialZp64> invMod, final boolean copy); static UnivariatePolynomialZp64 quotient(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64 quotientFast(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final InverseModMonomial<UnivariatePolynomialZp64> invMod, final boolean copy); static UnivariatePolynomial<E> remainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E> remainderFast(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final InverseModMonomial<UnivariatePolynomial<E>> invMod, final boolean copy); static UnivariatePolynomial<E> quotient(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E> quotientFast(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final InverseModMonomial<UnivariatePolynomial<E>> invMod, final boolean copy); @SuppressWarnings("unchecked") static Poly[] pseudoDivideAndRemainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly[] divideAndRemainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly[] divideAndRemainderFast(Poly dividend, Poly divider, InverseModMonomial<Poly> invMod, boolean copy); static Poly divideExact(Poly dividend, Poly divider, boolean copy); static Poly divideOrNull(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly remainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly quotient(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly remainderFast(final Poly dividend, final Poly divider, final InverseModMonomial<Poly> invMod, final boolean copy); static E remainderCoefficientBound(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider); }
@Test public void test22() throws Exception { IntegersZp domain = new IntegersZp(7); UnivariatePolynomial<BigInteger> bDividend = UnivariatePolynomial.create(domain, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1); UnivariatePolynomialZp64 lDividend = asOverZp64(bDividend); UnivariatePolynomial<BigInteger> bDivider = UnivariatePolynomial.create(domain, 1, 2, 3, 3, 2, 1); UnivariatePolynomialZp64 lDivider = asOverZp64(bDivider); UnivariatePolynomial<BigInteger>[] bqd = UnivariateDivision.divideAndRemainderFast(bDividend, bDivider, true); UnivariatePolynomialZp64[] lqd = UnivariateDivision.divideAndRemainderFast(lDividend, lDivider, true); assertArrayEquals(new UnivariatePolynomialZp64[]{asOverZp64(bqd[0]), asOverZp64(bqd[1])}, lqd); }
UnivariateDivision { public static UnivariatePolynomialZ64 remainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy) { checkZeroDivider(divider); if (dividend.degree < divider.degree) return dividend; if (divider.degree == 0) return UnivariatePolynomialZ64.zero(); if (divider.degree == 1) if (divider.cc() % divider.lc() == 0) return UnivariatePolynomialZ64.create(dividend.evaluate(-divider.cc() / divider.lc())); return remainder0(dividend, divider, copy); } private UnivariateDivision(); static T remainderMonomial(T dividend, int xDegree, boolean copy); static UnivariatePolynomialZ64[] divideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, boolean copy); static UnivariatePolynomialZ64[] pseudoDivideAndRemainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZ64 remainder(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZ64 quotient(final UnivariatePolynomialZ64 dividend, final UnivariatePolynomialZ64 divider, final boolean copy); static UnivariatePolynomialZp64[] divideAndRemainder(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderClassic(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomial<E>[] divideAndRemainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E>[] pseudoDivideAndRemainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderClassic(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static InverseModMonomial<Poly> fastDivisionPreConditioning(Poly divider); static InverseModMonomial<Poly> fastDivisionPreConditioningWithLCCorrection(Poly divider); static Poly[] divideAndRemainderFast0(Poly dividend, Poly divider, InverseModMonomial<Poly> invRevMod, boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderFast(UnivariatePolynomialZp64 dividend, UnivariatePolynomialZp64 divider, boolean copy); static UnivariatePolynomialZp64[] divideAndRemainderFast(UnivariatePolynomialZp64 dividend, UnivariatePolynomialZp64 divider, InverseModMonomial<UnivariatePolynomialZp64> invMod, boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderFast(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider, boolean copy); static UnivariatePolynomial<E>[] divideAndRemainderFast(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider, InverseModMonomial<UnivariatePolynomial<E>> invMod, boolean copy); static UnivariatePolynomialZp64 remainder(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64 remainderFast(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final InverseModMonomial<UnivariatePolynomialZp64> invMod, final boolean copy); static UnivariatePolynomialZp64 quotient(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final boolean copy); static UnivariatePolynomialZp64 quotientFast(final UnivariatePolynomialZp64 dividend, final UnivariatePolynomialZp64 divider, final InverseModMonomial<UnivariatePolynomialZp64> invMod, final boolean copy); static UnivariatePolynomial<E> remainder(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E> remainderFast(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final InverseModMonomial<UnivariatePolynomial<E>> invMod, final boolean copy); static UnivariatePolynomial<E> quotient(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final boolean copy); static UnivariatePolynomial<E> quotientFast(final UnivariatePolynomial<E> dividend, final UnivariatePolynomial<E> divider, final InverseModMonomial<UnivariatePolynomial<E>> invMod, final boolean copy); @SuppressWarnings("unchecked") static Poly[] pseudoDivideAndRemainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly[] divideAndRemainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly[] divideAndRemainderFast(Poly dividend, Poly divider, InverseModMonomial<Poly> invMod, boolean copy); static Poly divideExact(Poly dividend, Poly divider, boolean copy); static Poly divideOrNull(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly remainder(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly quotient(Poly dividend, Poly divider, boolean copy); @SuppressWarnings("unchecked") static Poly remainderFast(final Poly dividend, final Poly divider, final InverseModMonomial<Poly> invMod, final boolean copy); static E remainderCoefficientBound(UnivariatePolynomial<E> dividend, UnivariatePolynomial<E> divider); }
@Test public void test25() throws Exception { RandomGenerator rnd = getRandom(); RandomDataGenerator rndd = getRandomData(); int nIterations = 10000; for (int i = 0; i < nIterations; i++) { UnivariatePolynomialZ64 a = randomPoly(rndd.nextInt(1, 5), rnd), b = randomPoly(rndd.nextInt(a.degree + 1, a.degree + 1 + 5), rnd), rem = randomPoly(rndd.nextInt(0, a.degree), rnd); a = a.multiply(b).add(rem); UnivariatePolynomialZ64 r = remainder(a, b, true); assertNotNull(r); assertEquals(rem, r); long modulus = getModulusRandom(10); UnivariatePolynomialZp64 rp = remainder(a.modulus(modulus), b.modulus(modulus), true); assertNotNull(rp); assertEquals(rem.modulus(modulus), rp); UnivariatePolynomial<BigInteger> br = remainder(a.toBigPoly(), b.toBigPoly(), true); assertNotNull(br); assertEquals(rem.toBigPoly(), br); IntegersZp mDomain = new IntegersZp(modulus); UnivariatePolynomial<BigInteger> brp = remainder(a.toBigPoly().setRing(mDomain), b.toBigPoly().setRing(mDomain), true); assertNotNull(brp); assertEquals(rem.toBigPoly().setRing(mDomain), brp); } }
DistinctDegreeFactorization { public static PolynomialFactorDecomposition<UnivariatePolynomialZp64> DistinctDegreeFactorizationPlain(UnivariatePolynomialZp64 poly) { if (poly.isConstant()) return PolynomialFactorDecomposition.unit(poly); long factor = poly.lc(); UnivariatePolynomialZp64 base = poly.clone().monic(); UnivariatePolynomialZp64 polyModulus = base.clone(); if (base.degree <= 1) return PolynomialFactorDecomposition.of(base.createConstant(factor), base); if (base.isMonomial()) return PolynomialFactorDecomposition.of(base.createConstant(factor), base); UnivariateDivision.InverseModMonomial<UnivariatePolynomialZp64> invMod = UnivariateDivision.fastDivisionPreConditioning(polyModulus); UnivariatePolynomialZp64 exponent = poly.createMonomial(1); PolynomialFactorDecomposition<UnivariatePolynomialZp64> result = PolynomialFactorDecomposition.unit(poly.createOne()); int i = 0; while (!base.isConstant()) { ++i; exponent = polyPowMod(exponent, poly.ring.modulus, polyModulus, invMod, false); UnivariatePolynomialZp64 tmpExponent = exponent.clone(); tmpExponent.ensureCapacity(1); tmpExponent.data[1] = base.subtract(tmpExponent.data[1], 1); tmpExponent.fixDegree(); UnivariatePolynomialZp64 gcd = PolynomialGCD(tmpExponent, base); if (!gcd.isConstant()) result.addFactor(gcd.monic(), i); base = UnivariateDivision.quotient(base, gcd, false); if (base.degree < 2 * (i + 1)) { if (!base.isConstant()) result.addFactor(base.monic(), base.degree); break; } } return result.setUnit(poly.createConstant(factor)); } private DistinctDegreeFactorization(); static PolynomialFactorDecomposition<UnivariatePolynomialZp64> DistinctDegreeFactorizationPlain(UnivariatePolynomialZp64 poly); static PolynomialFactorDecomposition<UnivariatePolynomialZp64> DistinctDegreeFactorizationPrecomputedExponents(UnivariatePolynomialZp64 poly); static PolynomialFactorDecomposition<Poly> DistinctDegreeFactorizationShoup(Poly poly); static PolynomialFactorDecomposition<UnivariatePolynomialZp64> DistinctDegreeFactorization(UnivariatePolynomialZp64 poly); @SuppressWarnings("unchecked") static PolynomialFactorDecomposition<Poly> DistinctDegreeFactorization(Poly poly); }
@Test public void test1() throws Exception { UnivariatePolynomialZp64 poly = UnivariatePolynomialZ64.create(0, -1, -1, -1, 0, 1, -1, 1, 1).modulus(3); PolynomialFactorDecomposition<UnivariatePolynomialZp64> f = DistinctDegreeFactorization.DistinctDegreeFactorizationPlain(poly); assertDistinctDegreeFactorization(poly, f); } @Test public void test35a() throws Exception { UnivariatePolynomialZp64 poly = UnivariatePolynomialZ64 .create(19, 20, 13, 10, 26, 19, 6, 29, 13, 20, 10, 12, 20, 3, 21, 16, 25, 10, 26, 22, 25, 2, 23, 29, 21, 14, 8, 26, 16, 7, 7, 1) .modulus(31); PolynomialFactorDecomposition<UnivariatePolynomialZp64> factorization = DistinctDegreeFactorization.DistinctDegreeFactorizationPlain(poly); assertEquals(5, factorization.factors.size()); assertDistinctDegreeFactorization(poly, factorization); } @Test public void test37a() throws Exception { UnivariatePolynomialZp64 poly = UnivariatePolynomialZ64 .create(9, 7, 2, 3, 10, 1, 1) .modulus(11); PolynomialFactorDecomposition<UnivariatePolynomialZp64> factorization = DistinctDegreeFactorization.DistinctDegreeFactorizationPlain(poly); assertDistinctDegreeFactorization(poly, factorization); }
DistinctDegreeFactorization { static PolynomialFactorDecomposition<UnivariatePolynomialZp64> DistinctDegreeFactorizationComplete(UnivariatePolynomialZp64 poly) { PolynomialFactorDecomposition<UnivariatePolynomialZp64> squareFree = UnivariateSquareFreeFactorization.SquareFreeFactorization(poly); long overallFactor = squareFree.unit.lc(); PolynomialFactorDecomposition<UnivariatePolynomialZp64> result = PolynomialFactorDecomposition.unit(poly.createOne()); for (int i = squareFree.size() - 1; i >= 0; --i) { PolynomialFactorDecomposition<UnivariatePolynomialZp64> dd = DistinctDegreeFactorization(squareFree.get(i)); int nFactors = dd.size(); for (int j = nFactors - 1; j >= 0; --j) result.addFactor(dd.get(j), squareFree.getExponent(i)); overallFactor = poly.multiply(overallFactor, dd.unit.lc()); } return result.setUnit(poly.createConstant(overallFactor)); } private DistinctDegreeFactorization(); static PolynomialFactorDecomposition<UnivariatePolynomialZp64> DistinctDegreeFactorizationPlain(UnivariatePolynomialZp64 poly); static PolynomialFactorDecomposition<UnivariatePolynomialZp64> DistinctDegreeFactorizationPrecomputedExponents(UnivariatePolynomialZp64 poly); static PolynomialFactorDecomposition<Poly> DistinctDegreeFactorizationShoup(Poly poly); static PolynomialFactorDecomposition<UnivariatePolynomialZp64> DistinctDegreeFactorization(UnivariatePolynomialZp64 poly); @SuppressWarnings("unchecked") static PolynomialFactorDecomposition<Poly> DistinctDegreeFactorization(Poly poly); }
@Test public void test38() throws Exception { UnivariatePolynomialZp64 poly = UnivariatePolynomialZ64 .create(172, 85, 84, 151, 122, 53, 107, 117, 82, 152, 133, 151, 178, 1) .modulus(181); PolynomialFactorDecomposition<UnivariatePolynomialZp64> fct = DistinctDegreeFactorization.DistinctDegreeFactorizationComplete(poly); assertFactorization(poly, fct); }
DistinctDegreeFactorization { private DistinctDegreeFactorization() {} private DistinctDegreeFactorization(); static PolynomialFactorDecomposition<UnivariatePolynomialZp64> DistinctDegreeFactorizationPlain(UnivariatePolynomialZp64 poly); static PolynomialFactorDecomposition<UnivariatePolynomialZp64> DistinctDegreeFactorizationPrecomputedExponents(UnivariatePolynomialZp64 poly); static PolynomialFactorDecomposition<Poly> DistinctDegreeFactorizationShoup(Poly poly); static PolynomialFactorDecomposition<UnivariatePolynomialZp64> DistinctDegreeFactorization(UnivariatePolynomialZp64 poly); @SuppressWarnings("unchecked") static PolynomialFactorDecomposition<Poly> DistinctDegreeFactorization(Poly poly); }
@Test public void test5() throws Exception { PolynomialFactorDecomposition<UnivariatePolynomialZp64> ddf = DistinctDegreeFactorization.DistinctDegreeFactorization(bigPoly); assertDistinctDegreeFactorization(bigPoly, ddf); assertEquals(2, ddf.factors.size()); } @Test public void test5a() throws Exception { for (int i = 0; i < its(10, 50); i++) { UnivariatePolynomialZp64 bigPoly = this.bigPoly.setModulus(getModulusRandom(20)); long start = System.nanoTime(); PolynomialFactorDecomposition<UnivariatePolynomialZp64> ddf = DistinctDegreeFactorization.DistinctDegreeFactorization(bigPoly); assertDistinctDegreeFactorization(bigPoly, ddf); System.out.println("Time (deg(poly) = " + bigPoly.degree + ", modulus = " + bigPoly.ring.modulus + "): " + TimeUnits.nanosecondsToString(System.nanoTime() - start)); } } @Test public void test5c() throws Exception { long modulus = Integer.MAX_VALUE; for (int i = 0; i < its(10, 50); i++) { UnivariatePolynomialZp64 bigPoly = this.bigPoly.setModulus(modulus); long start = System.nanoTime(); PolynomialFactorDecomposition<UnivariatePolynomialZp64> ddf = DistinctDegreeFactorization.DistinctDegreeFactorization(bigPoly); assertDistinctDegreeFactorization(bigPoly, ddf); System.out.println("Time (deg(poly) = " + bigPoly.degree + ", modulus = " + bigPoly.ring.modulus + "): " + TimeUnits.nanosecondsToString(System.nanoTime() - start)); } } @Test @Benchmark public void test5b() throws Exception { for (int i = 0; i < its(100, 50); i++) { UnivariatePolynomialZp64 bigPoly = this.bigPoly.setModulus(getModulusRandom(20)); long start = System.nanoTime(); PolynomialFactorDecomposition<UnivariatePolynomialZp64> ddf = DistinctDegreeFactorization.DistinctDegreeFactorization(bigPoly); assertDistinctDegreeFactorization(bigPoly, ddf); long time = System.nanoTime() - start; boolean b = UnivariateGCD.EuclidGCD(bigPoly.toBigPoly().square(), bigPoly.toBigPoly().square().derivative()).isConstant(); System.out.println(i + "" + b + " Time (deg(poly) = " + bigPoly.degree + ", modulus = " + bigPoly.ring.modulus + "): " + TimeUnits.nanosecondsToString(time)); } } @Test public void test6() throws Exception { assertTrue(DistinctDegreeFactorization.DistinctDegreeFactorization(UnivariatePolynomialZ64.create(3, 7).modulus(17)).get(0).isMonic()); } @Test public void test7() throws Exception { UnivariatePolynomial<BigInteger> poly = UnivariatePolynomial.create(Long.MAX_VALUE, Long.MAX_VALUE - 1, Long.MAX_VALUE - 2, Long.MAX_VALUE - 3); poly = poly.add(poly.derivative()).square().increment(); poly = poly.multiply(poly.clone().increment()); BigInteger modulus = BigInteger.LONG_MAX_VALUE; modulus = modulus.multiply(modulus).nextProbablePrime(); UnivariatePolynomial<BigInteger> polyMod = poly.setRing(new IntegersZp(modulus)); PolynomialFactorDecomposition<UnivariatePolynomial<BigInteger>> f = DistinctDegreeFactorization(polyMod); assertDistinctDegreeFactorization(polyMod, f); }
UnivariateGCD { public static UnivariatePolynomialZ64 ModularGCD(UnivariatePolynomialZ64 a, UnivariatePolynomialZ64 b) { UnivariatePolynomialZ64 trivialGCD = TrivialGCD(a, b); if (trivialGCD != null) return trivialGCD; if (a.degree < b.degree) return ModularGCD(b, a); long aContent = a.content(), bContent = b.content(); long contentGCD = MachineArithmetic.gcd(aContent, bContent); if (a.isConstant() || b.isConstant()) return UnivariatePolynomialZ64.create(contentGCD); return ModularGCD0(a.clone().divideOrNull(aContent), b.clone().divideOrNull(bContent)).multiply(contentGCD); } private UnivariateGCD(); @SuppressWarnings("unchecked") static T PolynomialGCD(T a, T b); @SuppressWarnings("unchecked") static T[] PolynomialExtendedGCD(T a, T b); static T[] PolynomialFirstBezoutCoefficient(T a, T b); static T PolynomialGCD(T... polynomials); static T PolynomialGCD(Iterable<T> polynomials); static T EuclidGCD(final T a, final T b); @SuppressWarnings("unchecked") static T[] ExtendedEuclidGCD(final T a, final T b); static T[] EuclidFirstBezoutCoefficient(final T a, final T b); static T HalfGCD(T a, T b); static T[] ExtendedHalfGCD(T a, T b); static UnivariatePolynomialZ64 ModularGCD(UnivariatePolynomialZ64 a, UnivariatePolynomialZ64 b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<BigInteger> ModularGCD(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedRationalGCD( UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedResultantGCDInQ(UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<BigInteger>[] ModularExtendedResultantGCDInZ(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> PolynomialGCDInNumberField(UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> a, UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<BigInteger>> PolynomialGCDInRingOfIntegersOfNumberField(UnivariatePolynomial<UnivariatePolynomial<BigInteger>> a, UnivariatePolynomial<UnivariatePolynomial<BigInteger>> b); static boolean updateCRT(ChineseRemaindersMagic<BigInteger> magic, UnivariatePolynomial<BigInteger> accumulated, UnivariatePolynomialZp64 update); }
@Test public void test10() throws Exception { UnivariatePolynomial<BigInteger> a = UnivariatePolynomial.create(1740, 4044, 4371, 6905, 6201, 5209, 4483, 2225, 475); UnivariatePolynomial<BigInteger> b = UnivariatePolynomial.create(1102, 1349, 1847, 1759, 2517, 2607, 2731, 2145, 608); assertEquals(UnivariatePolynomial.create(29, 21, 32, 19), ModularGCD(a, b)); } @Test public void test11() throws Exception { UnivariatePolynomial<BigInteger> a = UnivariatePolynomial.create(0, 1, 1, -6, 17, -18, 14); UnivariatePolynomial<BigInteger> b = UnivariatePolynomial.create(0, 4, -3, 0, 8, 0, 4); assertEquals(UnivariatePolynomial.create(0, 1, -2, 2), ModularGCD(a, b)); } @Test public void test12() throws Exception { UnivariatePolynomial<BigInteger> a = UnivariatePolynomial.create(1, 2, 3, 3, 6, 9); UnivariatePolynomial<BigInteger> b = UnivariatePolynomial.create(1, 3, 6, 5, 3); assertEquals(UnivariatePolynomial.create(1, 2, 3), ModularGCD(a, b)); a = UnivariatePolynomial.create(0, 0, 1, 2); b = UnivariatePolynomial.create(-1, 0, 4); assertEquals(UnivariatePolynomial.create(1, 2), ModularGCD(a, b)); } @Test public void test13() throws Exception { UnivariatePolynomial<BigInteger> a = UnivariatePolynomial.create(-1, 0, 4); UnivariatePolynomial<BigInteger> b = UnivariatePolynomial.create(-1, 0, 0, 0, 16); UnivariatePolynomial<BigInteger> gcd = ModularGCD(a, b); assertEquals(UnivariatePolynomial.create(-1, 0, 4), gcd); } @Test public void test14() throws Exception { UnivariatePolynomial<BigInteger> a = UnivariatePolynomial.create(-1, 0, 4); UnivariatePolynomial<BigInteger> b = UnivariatePolynomial.create(1, -5, 6); UnivariatePolynomial<BigInteger> gcd = ModularGCD(a, b); assertEquals(UnivariatePolynomial.create(-1, 2), gcd); } @Test @Benchmark(runAnyway = true) public void testRandom5() throws Exception { RandomGenerator rnd = getRandom(); int overflow = 0; int larger = 0; DescriptiveStatistics timings = null; for (int k = 0; k < 2; k++) { timings = new DescriptiveStatistics(); for (int i = 0; i < its(5000, 10000); i++) { try { UnivariatePolynomialZ64 a = RandomUnivariatePolynomials.randomPoly(1 + rnd.nextInt(7), 100, rnd); UnivariatePolynomialZ64 b = RandomUnivariatePolynomials.randomPoly(1 + rnd.nextInt(6), 100, rnd); UnivariatePolynomialZ64 gcd = RandomUnivariatePolynomials.randomPoly(2 + rnd.nextInt(5), 30, rnd); a = a.multiply(gcd); b = b.multiply(gcd); long start = System.nanoTime(); UnivariatePolynomialZ64 mgcd = ModularGCD(a, b); timings.addValue(System.nanoTime() - start); assertFalse(mgcd.isConstant()); UnivariatePolynomialZ64[] qr = UnivariateDivision.pseudoDivideAndRemainderAdaptive(mgcd, gcd, true); assertNotNull(qr); assertTrue(qr[1].isZero()); UnivariatePolynomialZ64[] qr1 = UnivariateDivision.pseudoDivideAndRemainderAdaptive(mgcd.clone(), gcd, false); assertArrayEquals(qr, qr1); if (!qr[0].isConstant()) ++larger; assertGCD(a, b, mgcd); } catch (ArithmeticException e) {++overflow;} } } System.out.println("Overflows: " + overflow); System.out.println("Larger gcd: " + larger); System.out.println("\nTiming statistics:\n" + timings); } @Test public void test21() throws Exception { UnivariatePolynomial<BigInteger> a = UnivariatePolynomial.create(8, 2, -1, -2, -7); UnivariatePolynomial<BigInteger> b = UnivariatePolynomial.create(1, -9, -5, -21); assertTrue(ModularGCD(a, b).isOne()); } @Test public void test23() throws Exception { UnivariatePolynomial<BigInteger> a = UnivariatePolynomial.create(0, 14, 50, 11233219232222L, 108, 130, 70); UnivariatePolynomial<BigInteger> b = UnivariatePolynomial.create(63, 92, 143, 1245222, 146, 120, 90); UnivariatePolynomial<BigInteger> gcd1 = UnivariatePolynomial.create(1, 2, 3, 4, 5, 4, 3, 2, 1, -1, -2, -3, -4, -5, -4, -3, -2, -1, 999); UnivariatePolynomial<BigInteger> gcd2 = UnivariatePolynomial.create(999999L, 123L, 123L, 342425L, 312L, -12312432423L, 13212123123123L, -123124342345L); UnivariatePolynomial<BigInteger> gcd3 = UnivariatePolynomial.create(991999L, 123L, 123L, 342425L, 312L, -12312432423L, 13212123123123L, 123124342345L); UnivariatePolynomial<BigInteger> gcd4 = UnivariatePolynomial.create(Long.MAX_VALUE, Long.MAX_VALUE - 1, Long.MAX_VALUE - 2, Long.MAX_VALUE - 3, Long.MAX_VALUE - 4, Long.MAX_VALUE - 5); UnivariatePolynomial<BigInteger> gcd = gcd1.multiply(gcd2).multiply(gcd3).multiply(gcd4); a = a.multiply(gcd); b = b.multiply(gcd); UnivariatePolynomial<BigInteger> gcdActual = PseudoPRS(a, b).gcd(); assertGCD(a, b, gcdActual); APolynomialRemainderSequence<UnivariatePolynomial<BigInteger>> prs = SubresultantPRS(a, b); assertPolynomialRemainders(a, b, prs); UnivariatePolynomial<BigInteger> gcdSubresultant = prs.gcd(); assertEquals(gcdActual.degree, gcdSubresultant.degree); UnivariatePolynomial<BigInteger> gcdModular = ModularGCD(a, b); assertEquals(gcdActual.degree, gcdModular.degree); System.out.println(gcdActual.normMax().bitLength()); } @Test @Benchmark(runAnyway = true) public void testRandom5_bigPoly() throws Exception { RandomGenerator rnd = getRandom(); int overflow = 0; int larger = 0; DescriptiveStatistics timings = null; for (int kk = 0; kk < 2; kk++) { timings = new DescriptiveStatistics(); for (int i = 0; i < its(300, 1000); i++) { try { UnivariatePolynomial<BigInteger> a = RandomUnivariatePolynomials.randomPoly(1 + rnd.nextInt(30), BigInteger.LONG_MAX_VALUE, rnd); UnivariatePolynomial<BigInteger> b = RandomUnivariatePolynomials.randomPoly(1 + rnd.nextInt(30), BigInteger.LONG_MAX_VALUE, rnd); UnivariatePolynomial<BigInteger> gcd = RandomUnivariatePolynomials.randomPoly(2 + rnd.nextInt(30), BigInteger.LONG_MAX_VALUE, rnd); a = a.multiply(gcd); b = b.multiply(gcd); long start = System.nanoTime(); UnivariatePolynomial<BigInteger> mgcd = ModularGCD(a, b); timings.addValue(System.nanoTime() - start); assertFalse(mgcd.isConstant()); UnivariatePolynomial<BigInteger>[] qr = UnivariateDivision.pseudoDivideAndRemainder(mgcd, gcd, true); assertNotNull(qr); assertTrue(qr[1].isZero()); UnivariatePolynomial<BigInteger>[] qr1 = UnivariateDivision.pseudoDivideAndRemainder(mgcd.clone(), gcd, false); assertArrayEquals(qr, qr1); if (!qr[0].isConstant()) ++larger; assertGCD(a, b, mgcd); } catch (ArithmeticException e) {++overflow;} } } System.out.println("Overflows: " + overflow); System.out.println("Larger gcd: " + larger); System.out.println("\nTiming statistics:\n" + timings); }
UnivariateGCD { @SuppressWarnings("unchecked") public static <T extends IUnivariatePolynomial<T>> T PolynomialGCD(T a, T b) { a.assertSameCoefficientRingWith(b); if (Util.isOverMultipleFieldExtension(a)) return (T) PolynomialGCDInMultipleFieldExtension((UnivariatePolynomial) a, (UnivariatePolynomial) b); if (a.isOverFiniteField()) return HalfGCD(a, b); if (a instanceof UnivariatePolynomialZ64) return (T) ModularGCD((UnivariatePolynomialZ64) a, (UnivariatePolynomialZ64) b); if (a.isOverZ()) return (T) ModularGCD((UnivariatePolynomial) a, (UnivariatePolynomial) b); if (Util.isOverRationals(a)) return (T) PolynomialGCDInQ((UnivariatePolynomial) a, (UnivariatePolynomial) b); if (Util.isOverRingOfIntegersOfSimpleNumberField(a)) return (T) PolynomialGCDInRingOfIntegersOfNumberField((UnivariatePolynomial) a, (UnivariatePolynomial) b); if (Util.isOverSimpleNumberField(a)) return (T) PolynomialGCDInNumberField((UnivariatePolynomial) a, (UnivariatePolynomial) b); if (a.isOverField()) return HalfGCD(a, b); T r = tryNested(a, b); if (r != null) return r; T t = trivialGCD(a, b); if (t != null) return t; return (T) UnivariateResultants.SubresultantPRS((UnivariatePolynomial) a, (UnivariatePolynomial) b).gcd(); } private UnivariateGCD(); @SuppressWarnings("unchecked") static T PolynomialGCD(T a, T b); @SuppressWarnings("unchecked") static T[] PolynomialExtendedGCD(T a, T b); static T[] PolynomialFirstBezoutCoefficient(T a, T b); static T PolynomialGCD(T... polynomials); static T PolynomialGCD(Iterable<T> polynomials); static T EuclidGCD(final T a, final T b); @SuppressWarnings("unchecked") static T[] ExtendedEuclidGCD(final T a, final T b); static T[] EuclidFirstBezoutCoefficient(final T a, final T b); static T HalfGCD(T a, T b); static T[] ExtendedHalfGCD(T a, T b); static UnivariatePolynomialZ64 ModularGCD(UnivariatePolynomialZ64 a, UnivariatePolynomialZ64 b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<BigInteger> ModularGCD(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedRationalGCD( UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedResultantGCDInQ(UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<BigInteger>[] ModularExtendedResultantGCDInZ(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> PolynomialGCDInNumberField(UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> a, UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<BigInteger>> PolynomialGCDInRingOfIntegersOfNumberField(UnivariatePolynomial<UnivariatePolynomial<BigInteger>> a, UnivariatePolynomial<UnivariatePolynomial<BigInteger>> b); static boolean updateCRT(ChineseRemaindersMagic<BigInteger> magic, UnivariatePolynomial<BigInteger> accumulated, UnivariatePolynomialZp64 update); }
@Test public void test20() throws Exception { UnivariatePolynomial<BigInteger> a = UnivariatePolynomial.create(32); UnivariatePolynomial<BigInteger> b = UnivariatePolynomial.create(24); UnivariatePolynomial<BigInteger> gcd = UnivariatePolynomial.create(8); assertEquals(gcd, PolynomialGCD(a, b)); assertEquals(gcd, SubresultantPRS(a, b).gcd()); assertEquals(gcd, PrimitivePRS(a, b).gcd()); assertEquals(gcd, PseudoPRS(a, b).gcd()); } @Test public void test25() throws Exception { UnivariatePolynomial<Rational<BigInteger>> a = UnivariatePolynomial.create(Rings.Q, Rings.Q.parse("2/3"), Rings.Q.parse("4/5"), Rings.Q.parse("1/2"), Rings.Q.parse("-31/2")); UnivariatePolynomial<Rational<BigInteger>> b = UnivariatePolynomial.create(Rings.Q, Rings.Q.parse("7/3"), Rings.Q.parse("4/7"), Rings.Q.parse("3/2"), Rings.Q.parse("-31/12")); UnivariatePolynomial<Rational<BigInteger>> gcd = UnivariatePolynomial.create(Rings.Q, Rings.Q.parse("4/3"), Rings.Q.parse("-4/7"), Rings.Q.parse("-1/2"), Rings.Q.parse("-1/12")); a = a.clone().multiply(gcd); b = b.clone().multiply(gcd); assertGCD(a, b, PolynomialGCD(a, b)); }
UnivariateGCD { @SuppressWarnings("unchecked") public static <T extends IUnivariatePolynomial<T>> T[] ExtendedEuclidGCD(final T a, final T b) { a.assertSameCoefficientRingWith(b); if (canConvertToZp64(a)) return Conversions64bit.convert(a, ExtendedEuclidGCD(asOverZp64(a), asOverZp64(b))); T s = a.createZero(), old_s = a.createOne(); T t = a.createOne(), old_t = a.createZero(); T r = b.clone(), old_r = a.clone(); T q; T tmp; while (!r.isZero()) { q = UnivariateDivision.quotient(old_r, r, true); if (q == null) throw new ArithmeticException("Not divisible with remainder: (" + old_r + ") / (" + r + ")"); tmp = old_r; old_r = r; r = tmp.clone().subtract(q.clone().multiply(r)); tmp = old_s; old_s = s; s = tmp.clone().subtract(q.clone().multiply(s)); tmp = old_t; old_t = t; t = tmp.clone().subtract(q.clone().multiply(t)); } assert old_r.equals(a.clone().multiply(old_s).add(b.clone().multiply(old_t))) : a.clone().multiply(old_s).add (b.clone().multiply(old_t)); T[] result = a.createArray(3); result[0] = old_r; result[1] = old_s; result[2] = old_t; return normalizeExtendedGCD(result); } private UnivariateGCD(); @SuppressWarnings("unchecked") static T PolynomialGCD(T a, T b); @SuppressWarnings("unchecked") static T[] PolynomialExtendedGCD(T a, T b); static T[] PolynomialFirstBezoutCoefficient(T a, T b); static T PolynomialGCD(T... polynomials); static T PolynomialGCD(Iterable<T> polynomials); static T EuclidGCD(final T a, final T b); @SuppressWarnings("unchecked") static T[] ExtendedEuclidGCD(final T a, final T b); static T[] EuclidFirstBezoutCoefficient(final T a, final T b); static T HalfGCD(T a, T b); static T[] ExtendedHalfGCD(T a, T b); static UnivariatePolynomialZ64 ModularGCD(UnivariatePolynomialZ64 a, UnivariatePolynomialZ64 b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<BigInteger> ModularGCD(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedRationalGCD( UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedResultantGCDInQ(UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<BigInteger>[] ModularExtendedResultantGCDInZ(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> PolynomialGCDInNumberField(UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> a, UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<BigInteger>> PolynomialGCDInRingOfIntegersOfNumberField(UnivariatePolynomial<UnivariatePolynomial<BigInteger>> a, UnivariatePolynomial<UnivariatePolynomial<BigInteger>> b); static boolean updateCRT(ChineseRemaindersMagic<BigInteger> magic, UnivariatePolynomial<BigInteger> accumulated, UnivariatePolynomialZp64 update); }
@Test public void test24() throws Exception { long modulus = 419566991; UnivariatePolynomial<BigInteger> poly = UnivariatePolynomial.create(Rings.Z, new BigInteger("-4914"), new BigInteger("6213"), new BigInteger("3791"), new BigInteger("996"), new BigInteger("-13304"), new BigInteger("-1567"), new BigInteger("2627"), new BigInteger("15845"), new BigInteger("-12626"), new BigInteger("-6383"), new BigInteger("294"), new BigInteger("26501"), new BigInteger("-17063"), new BigInteger("-14635"), new BigInteger("9387"), new BigInteger("-7141"), new BigInteger("-8185"), new BigInteger("17856"), new BigInteger("4431"), new BigInteger("-13075"), new BigInteger("-7050"), new BigInteger("14672"), new BigInteger("3690"), new BigInteger("-3990")); UnivariatePolynomial<BigInteger> a = UnivariatePolynomial.create(Rings.Z, new BigInteger("419563715"), new BigInteger("419566193"), new BigInteger("3612"), new BigInteger("3444"), new BigInteger("419563127"), new BigInteger("419564681"), new BigInteger("419565017"), new BigInteger("419564387"), new BigInteger("419563463"), new BigInteger("3192"), new BigInteger("419563841"), new BigInteger("419563001")); UnivariatePolynomial<BigInteger> b = UnivariatePolynomial.create(Rings.Z, new BigInteger("209783497"), new BigInteger("9989688"), new BigInteger("379608231"), new BigInteger("399587609"), new BigInteger("59938143"), new BigInteger("29969072"), new BigInteger("99896901"), new BigInteger("359628849"), new BigInteger("329659781"), new BigInteger("239752567"), new BigInteger("19979379"), new BigInteger("179814423"), new BigInteger("1")); IntegersZp domain = new IntegersZp(modulus); UnivariatePolynomial<BigInteger> aMod = a.setRing(domain).monic(poly.lc()); UnivariatePolynomial<BigInteger> bMod = b.setRing(domain).monic(); UnivariatePolynomial<BigInteger>[] xgcd = UnivariateGCD.ExtendedEuclidGCD(aMod, bMod); UnivariatePolynomialZp64[] lxgcd = UnivariateGCD.ExtendedEuclidGCD(UnivariatePolynomial.asOverZp64(aMod), UnivariatePolynomial.asOverZp64(bMod)); assertEquals(UnivariatePolynomial.asOverZp64(xgcd[0]), lxgcd[0]); assertEquals(UnivariatePolynomial.asOverZp64(xgcd[1]), lxgcd[1]); assertEquals(UnivariatePolynomial.asOverZp64(xgcd[2]), lxgcd[2]); } @Test public void test27() throws Exception { UnivariatePolynomialZp64 a = RandomUnivariatePolynomials.randomMonicPoly(15_000, 19, getRandom()); UnivariatePolynomialZp64 b = RandomUnivariatePolynomials.randomMonicPoly(15_000, 19, getRandom()); assertExtendedGCD(ExtendedEuclidGCD(a, b), a, b); }
UnivariateGCD { @SuppressWarnings({"ConstantConditions", "unchecked"}) public static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedRationalGCD( UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b) { if (a == b || a.equals(b)) return new UnivariatePolynomial[]{a.clone(), a.createZero(), a.createOne()}; if (a.degree() < b.degree()) { UnivariatePolynomial<Rational<BigInteger>>[] r = ModularExtendedRationalGCD(b, a); ArraysUtil.swap(r, 1, 2); return r; } if (b.isZero()) { UnivariatePolynomial<Rational<BigInteger>>[] result = a.createArray(3); result[0] = a.clone(); result[1] = a.createOne(); result[2] = a.createZero(); return normalizeExtendedGCD(result); } Tuple2<UnivariatePolynomial<BigInteger>, BigInteger> ac = toCommonDenominator(a), bc = toCommonDenominator(b); UnivariatePolynomial<BigInteger> az = ac._1, bz = bc._1; BigInteger aContent = az.content(), bContent = bz.content(); UnivariatePolynomial<Rational<BigInteger>>[] xgcd = ModularExtendedRationalGCD0( az.clone().divideOrNull(aContent), bz.clone().divideOrNull(bContent)); xgcd[1].multiply(new Rational<>(Z, ac._2, aContent)); xgcd[2].multiply(new Rational<>(Z, bc._2, bContent)); return xgcd; } private UnivariateGCD(); @SuppressWarnings("unchecked") static T PolynomialGCD(T a, T b); @SuppressWarnings("unchecked") static T[] PolynomialExtendedGCD(T a, T b); static T[] PolynomialFirstBezoutCoefficient(T a, T b); static T PolynomialGCD(T... polynomials); static T PolynomialGCD(Iterable<T> polynomials); static T EuclidGCD(final T a, final T b); @SuppressWarnings("unchecked") static T[] ExtendedEuclidGCD(final T a, final T b); static T[] EuclidFirstBezoutCoefficient(final T a, final T b); static T HalfGCD(T a, T b); static T[] ExtendedHalfGCD(T a, T b); static UnivariatePolynomialZ64 ModularGCD(UnivariatePolynomialZ64 a, UnivariatePolynomialZ64 b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<BigInteger> ModularGCD(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedRationalGCD( UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedResultantGCDInQ(UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<BigInteger>[] ModularExtendedResultantGCDInZ(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> PolynomialGCDInNumberField(UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> a, UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<BigInteger>> PolynomialGCDInRingOfIntegersOfNumberField(UnivariatePolynomial<UnivariatePolynomial<BigInteger>> a, UnivariatePolynomial<UnivariatePolynomial<BigInteger>> b); static boolean updateCRT(ChineseRemaindersMagic<BigInteger> magic, UnivariatePolynomial<BigInteger> accumulated, UnivariatePolynomialZp64 update); }
@Test public void test33() throws Exception { UnivariatePolynomial<Rational<BigInteger>> a = UnivariatePolynomial.parse("1 + 23123*x^7 + 2344*x^15", Rings.Q); UnivariatePolynomial<Rational<BigInteger>> b = UnivariatePolynomial.parse("1 + 23*x - 23454*x^4", Rings.Q); UnivariatePolynomial<Rational<BigInteger>>[] xgcd = ModularExtendedRationalGCD(a, b); assertExtendedGCD(xgcd, a, b); } @Test public void test33a() throws Exception { UnivariatePolynomial<Rational<BigInteger>> a = UnivariatePolynomial.parse("1 + 23123*x^7 + 2344*x^15", Rings.Q); UnivariatePolynomial<Rational<BigInteger>> b = UnivariatePolynomial.parse("1 + 23*x - 23454*x^4", Rings.Q); a.multiply(new Rational<>(Rings.Z, BigInteger.valueOf(123), BigInteger.valueOf(32))); b.multiply(new Rational<>(Rings.Z, BigInteger.valueOf(123), BigInteger.valueOf(12332))); assertExtendedGCD(ModularExtendedRationalGCD(a, b), a, b); assertExtendedGCD(ModularExtendedRationalGCD(b, a), b, a); } @Test public void test34() throws Exception { UnivariatePolynomial<Rational<BigInteger>> a = UnivariatePolynomial.parse("1 + 23123*x^7 + 2344*x^15", Rings.Q); UnivariatePolynomial<Rational<BigInteger>> b = UnivariatePolynomial.parse("1 + 23*x - 23454*x^4", Rings.Q); UnivariatePolynomial<Rational<BigInteger>> g = UnivariatePolynomial.parse("1 + (23/2)*x - 23454*x^3", Rings.Q); a.multiply(new Rational<>(Rings.Z, BigInteger.valueOf(123), BigInteger.valueOf(32))); b.multiply(new Rational<>(Rings.Z, BigInteger.valueOf(123), BigInteger.valueOf(12332))); a.multiply(g); b.multiply(g); assertExtendedGCD(ModularExtendedRationalGCD(a, b), a, b); assertExtendedGCD(ModularExtendedRationalGCD(b, a), b, a); } @Test @Benchmark public void test35_performance() throws Exception { UnivariatePolynomial<Rational<BigInteger>> a = UnivariatePolynomial.parse("1 + 23123*x^7 + 2344*x^15", Rings.Q); UnivariatePolynomial<Rational<BigInteger>> b = UnivariatePolynomial.parse("1 + 23*x + 23454*x^4", Rings.Q); UnivariatePolynomial<Rational<BigInteger>> g = UnivariatePolynomial.parse("1 + (23/2)*x + 23454*x^3", Rings.Q); a.multiply(new Rational<>(Rings.Z, BigInteger.valueOf(123), BigInteger.valueOf(32))); b.multiply(new Rational<>(Rings.Z, BigInteger.valueOf(123), BigInteger.valueOf(12332))); a.multiply(g); b.multiply(g); System.out.println(a); System.out.println(b); for (int i = 0; i < 1000; i++) { long start = System.nanoTime(); assertExtendedGCD(ModularExtendedRationalGCD(a, b), a, b); assertExtendedGCD(ModularExtendedRationalGCD(b, a), b, a); System.out.println(nanosecondsToString(System.nanoTime() - start)); } } @Test @Benchmark public void test36_performance() throws Exception { UnivariatePolynomial<Rational<BigInteger>> a = UnivariatePolynomial.parse("(296/15) + (874/9)*x + (2083/20)*x^2 + ((-11819)/90)*x^3 + ((-147)/8)* x^4 + (152461/360)*x^5 + (223567/1440)*x^6 + (22223/432)* x^7 + ((-583021)/2880)*x^8 + (45407/240)*x^9 + (235373/1260)* x^10 + ((-58349)/378)*x^11 + (269417/2520)*x^12 + (2402/45)* x^13 + (206113/420)*x^14 + ((-218167)/1890)*x^15 + ((-62221)/5040)* x^16 + ((-59279)/2520)*x^17 + (164803/630)*x^18 + (1027/54)* x^19 + ((-539)/30)*x^20 + ((-97)/3)*x^21 + (64/3)*x^22", Rings.Q); UnivariatePolynomial<Rational<BigInteger>> b = UnivariatePolynomial.parse("(388/15) + 221*x + (76253/120)*x^2 + (73661/120)*x^3 + ((-21007)/240)* x^4 + (58939/720)*x^5 + (3215/8)*x^6 + (2599/6)*x^7 + (29683/105)* x^8 + ((-7141)/105)*x^9 + (16021/84)*x^10 + (8807/240)* x^11 + (20747/168)*x^12 + ((-1597627)/10080)*x^13 + (1846219/3360)* x^14 + (334471/6720)*x^15 + ((-644489)/6720)*x^16 + ((-551)/20)* x^17 + (17611/120)*x^18 + (3127/30)*x^19 + ((-4591)/120)* x^20 + (229/30)*x^21 + ((-34)/3)*x^22 + (26/3)*x^23", Rings.Q); for (int i = 0; i < 1000; i++) { long start = System.nanoTime(); UnivariatePolynomial<Rational<BigInteger>>[] r = ModularExtendedRationalGCD(a, b); System.out.println(nanosecondsToString(System.nanoTime() - start)); assertExtendedGCD(r, a, b); } }
UnivariateGCD { @SuppressWarnings("unchecked") public static <T extends IUnivariatePolynomial<T>> T[] PolynomialExtendedGCD(T a, T b) { if (Util.isOverQ(a)) return (T[]) ModularExtendedResultantGCDInQ((UnivariatePolynomial) a, (UnivariatePolynomial) b); if (a.isOverZ()) return (T[]) ModularExtendedResultantGCDInZ((UnivariatePolynomial) a, (UnivariatePolynomial) b); if (a.isOverField()) return ExtendedHalfGCD(a, b); else throw new IllegalArgumentException("Polynomial over field is expected"); } private UnivariateGCD(); @SuppressWarnings("unchecked") static T PolynomialGCD(T a, T b); @SuppressWarnings("unchecked") static T[] PolynomialExtendedGCD(T a, T b); static T[] PolynomialFirstBezoutCoefficient(T a, T b); static T PolynomialGCD(T... polynomials); static T PolynomialGCD(Iterable<T> polynomials); static T EuclidGCD(final T a, final T b); @SuppressWarnings("unchecked") static T[] ExtendedEuclidGCD(final T a, final T b); static T[] EuclidFirstBezoutCoefficient(final T a, final T b); static T HalfGCD(T a, T b); static T[] ExtendedHalfGCD(T a, T b); static UnivariatePolynomialZ64 ModularGCD(UnivariatePolynomialZ64 a, UnivariatePolynomialZ64 b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<BigInteger> ModularGCD(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedRationalGCD( UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedResultantGCDInQ(UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<BigInteger>[] ModularExtendedResultantGCDInZ(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> PolynomialGCDInNumberField(UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> a, UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<BigInteger>> PolynomialGCDInRingOfIntegersOfNumberField(UnivariatePolynomial<UnivariatePolynomial<BigInteger>> a, UnivariatePolynomial<UnivariatePolynomial<BigInteger>> b); static boolean updateCRT(ChineseRemaindersMagic<BigInteger> magic, UnivariatePolynomial<BigInteger> accumulated, UnivariatePolynomialZp64 update); }
@Test public void test37() { UnivariatePolynomial<Rational<BigInteger>> a = UnivariatePolynomial.parse("(x - 1)^2*(x - 2)^2", Q), b = UnivariatePolynomial.parse("(x - 1)*(x^2 - 3)", Q); UnivariatePolynomial<Rational<BigInteger>>[] xgcd = PolynomialExtendedGCD(a, b); assertExtendedGCD(xgcd, a, b); System.out.println(Arrays.toString(xgcd)); } @Test public void test38() { UnivariatePolynomial<BigInteger> a = UnivariatePolynomial.parse("3+3*x^3", Z), b = UnivariatePolynomial.parse("3+3*x^3", Z); UnivariatePolynomial<BigInteger>[] xgcd = PolynomialExtendedGCD(a, b); assertExtendedGCD(xgcd, a, b); System.out.println(Arrays.toString(xgcd)); }
UnivariateGCD { public static <T extends IUnivariatePolynomial<T>> T HalfGCD(T a, T b) { a.assertSameCoefficientRingWith(b); T trivialGCD = TrivialGCD(a, b); if (trivialGCD != null) return trivialGCD; if (canConvertToZp64(a)) return Conversions64bit.convert(HalfGCD(asOverZp64(a), asOverZp64(b))); if (a.degree() < b.degree()) return HalfGCD(b, a); if (a.degree() == b.degree()) b = UnivariateDivision.remainder(b, a, true); while (a.degree() > SWITCH_TO_HALF_GCD_ALGORITHM_DEGREE && !b.isZero()) { T[] col = reduceHalfGCD(a, b); a = col[0]; b = col[1]; if (!b.isZero()) { T remainder = UnivariateDivision.remainder(a, b, true); if (remainder == null) throw new ArithmeticException("Not divisible with remainder: (" + a + ") / (" + b + ")"); a = b; b = remainder; } } return UnivariateGCD.EuclidGCD(a, b); } private UnivariateGCD(); @SuppressWarnings("unchecked") static T PolynomialGCD(T a, T b); @SuppressWarnings("unchecked") static T[] PolynomialExtendedGCD(T a, T b); static T[] PolynomialFirstBezoutCoefficient(T a, T b); static T PolynomialGCD(T... polynomials); static T PolynomialGCD(Iterable<T> polynomials); static T EuclidGCD(final T a, final T b); @SuppressWarnings("unchecked") static T[] ExtendedEuclidGCD(final T a, final T b); static T[] EuclidFirstBezoutCoefficient(final T a, final T b); static T HalfGCD(T a, T b); static T[] ExtendedHalfGCD(T a, T b); static UnivariatePolynomialZ64 ModularGCD(UnivariatePolynomialZ64 a, UnivariatePolynomialZ64 b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<BigInteger> ModularGCD(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedRationalGCD( UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedResultantGCDInQ(UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<BigInteger>[] ModularExtendedResultantGCDInZ(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> PolynomialGCDInNumberField(UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> a, UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<BigInteger>> PolynomialGCDInRingOfIntegersOfNumberField(UnivariatePolynomial<UnivariatePolynomial<BigInteger>> a, UnivariatePolynomial<UnivariatePolynomial<BigInteger>> b); static boolean updateCRT(ChineseRemaindersMagic<BigInteger> magic, UnivariatePolynomial<BigInteger> accumulated, UnivariatePolynomialZp64 update); }
@Test public void test37_algext() { AlgebraicNumberField<UnivariatePolynomial<Rational<BigInteger>>> field = AlgebraicNumberField(UnivariatePolynomial.create(Q, Q.valueOf(-2), Q.valueOf(0), Q.valueOf(1))); Coder<UnivariatePolynomial<Rational<BigInteger>>, ?, ?> cfCoder = Coder.mkUnivariateCoder(field, "s"); UnivariateRing<UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>>> uRing = UnivariateRing(field); Coder<UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>>, ?, ?> coder = Coder.mkUnivariateCoder(uRing, cfCoder, "x"); UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> a = coder.parse("(1 - s + s*x^5) * ( 1 + s*x^2 + 12*x^5)"); UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> b = coder.parse("(1 - s + s*x^5) * ( 14 - s*x + 2*x^17)"); assertEquals(coder.parse("-1+1/2*s+x^5"), UnivariateGCD.HalfGCD(a, b)); }
UnivariateGCD { @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<BigInteger>> gcdAssociateInNumberField0( UnivariatePolynomial<UnivariatePolynomial<BigInteger>> a, UnivariatePolynomial<UnivariatePolynomial<BigInteger>> b) { assert a.lc().isConstant(); assert b.lc().isConstant(); AlgebraicNumberField<UnivariatePolynomial<BigInteger>> numberField = (AlgebraicNumberField<UnivariatePolynomial<BigInteger>>) a.ring; UnivariateRing<UnivariatePolynomial<BigInteger>> auxRing = Rings.UnivariateRing(Z); UnivariatePolynomial<BigInteger> minimalPoly = numberField.getMinimalPolynomial(); BigInteger lcGCD = Z.gcd(a.lc().cc(), b.lc().cc()), disc = UnivariateResultants.Discriminant(minimalPoly), correctionFactor = disc.multiply(lcGCD); BigInteger crtPrime = null; UnivariatePolynomial<UnivariatePolynomial<BigInteger>> gcd = null, prevCandidate = null; PrimesIterator primes = new PrimesIterator(1 << 20); while (true) { long prime = primes.take(); IntegersZp64 zpRing = new IntegersZp64(prime); UnivariatePolynomialZp64 minimalPolyMod = asOverZp64(minimalPoly, zpRing); if (minimalPolyMod.nNonZeroTerms() != minimalPoly.nNonZeroTerms()) continue; FiniteField<UnivariatePolynomialZp64> modRing = new FiniteField<>(minimalPolyMod); UnivariatePolynomial<UnivariatePolynomialZp64> aMod = a.mapCoefficients(modRing, cf -> asOverZp64(cf, zpRing)), bMod = b.mapCoefficients(modRing, cf -> asOverZp64(cf, zpRing)); UnivariatePolynomial<UnivariatePolynomialZp64> gcdMod; try { gcdMod = PolynomialGCD(aMod, bMod); } catch (Throwable e) { continue; } if (gcdMod.isConstant()) return a.createOne(); gcdMod.multiply(correctionFactor.mod(prime).longValue()); BigInteger bPrime = BigInteger.valueOf(prime); if (crtPrime == null || gcdMod.degree < gcd.degree) { crtPrime = bPrime; gcd = gcdMod.mapCoefficients(auxRing, cf -> cf.toBigPoly().setRing(Z)); continue; } if (gcdMod.degree > gcd.degree) continue; ChineseRemaindersMagic<BigInteger> magic = createMagic(Z, crtPrime, bPrime); boolean updated = false; for (int i = gcd.degree; i >= 0; --i) { boolean u = updateCRT(magic, gcd.data[i], gcdMod.data[i]); if (u) updated = true; } crtPrime = crtPrime.multiply(bPrime); IntegersZp crtRing = new IntegersZp(crtPrime); UnivariatePolynomial<UnivariatePolynomial<BigInteger>> candidate = gcd.mapCoefficients(numberField, cf -> numberField.valueOf(UnivariatePolynomial.asPolyZSymmetric(cf.setRingUnsafe(crtRing)))) .primitivePart(); if (prevCandidate == null) { prevCandidate = candidate; continue; } if (!updated || prevCandidate.equals(candidate)) { UnivariatePolynomial<UnivariatePolynomial<BigInteger>> rem; rem = UnivariateDivision.pseudoRemainderAdaptive(b, candidate, true); if (rem == null || !rem.isZero()) continue; rem = UnivariateDivision.pseudoRemainderAdaptive(a, candidate, true); if (rem == null || !rem.isZero()) continue; return candidate; } prevCandidate = candidate; } } private UnivariateGCD(); @SuppressWarnings("unchecked") static T PolynomialGCD(T a, T b); @SuppressWarnings("unchecked") static T[] PolynomialExtendedGCD(T a, T b); static T[] PolynomialFirstBezoutCoefficient(T a, T b); static T PolynomialGCD(T... polynomials); static T PolynomialGCD(Iterable<T> polynomials); static T EuclidGCD(final T a, final T b); @SuppressWarnings("unchecked") static T[] ExtendedEuclidGCD(final T a, final T b); static T[] EuclidFirstBezoutCoefficient(final T a, final T b); static T HalfGCD(T a, T b); static T[] ExtendedHalfGCD(T a, T b); static UnivariatePolynomialZ64 ModularGCD(UnivariatePolynomialZ64 a, UnivariatePolynomialZ64 b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<BigInteger> ModularGCD(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedRationalGCD( UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedResultantGCDInQ(UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<BigInteger>[] ModularExtendedResultantGCDInZ(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> PolynomialGCDInNumberField(UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> a, UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<BigInteger>> PolynomialGCDInRingOfIntegersOfNumberField(UnivariatePolynomial<UnivariatePolynomial<BigInteger>> a, UnivariatePolynomial<UnivariatePolynomial<BigInteger>> b); static boolean updateCRT(ChineseRemaindersMagic<BigInteger> magic, UnivariatePolynomial<BigInteger> accumulated, UnivariatePolynomialZp64 update); }
@Test public void test38_algext() { AlgebraicNumberField<UnivariatePolynomial<BigInteger>> field = AlgebraicNumberField(UnivariatePolynomial.create(Z, Z.valueOf(-2), Z.valueOf(0), Z.valueOf(1))); Coder<UnivariatePolynomial<BigInteger>, ?, ?> cfCoder = Coder.mkUnivariateCoder(field, "s"); UnivariateRing<UnivariatePolynomial<UnivariatePolynomial<BigInteger>>> uRing = UnivariateRing(field); Coder<UnivariatePolynomial<UnivariatePolynomial<BigInteger>>, ?, ?> coder = Coder.mkUnivariateCoder(uRing, cfCoder, "x"); UnivariatePolynomial<UnivariatePolynomial<BigInteger>> a = coder.parse("(1 - s + x^5) * ( 1 + s*x^2 + 12*x^5)"); UnivariatePolynomial<UnivariatePolynomial<BigInteger>> b = coder.parse("(1 - s + x^5) * ( 14 - s*x + 2*x^17)"); assertEquals(coder.parse("1 - s + x^5"), UnivariateGCD.gcdAssociateInNumberField0(a, b)); }
UnivariateGCD { @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<BigInteger>> gcdAssociateInNumberField( UnivariatePolynomial<UnivariatePolynomial<BigInteger>> a, UnivariatePolynomial<UnivariatePolynomial<BigInteger>> b) { AlgebraicNumberField<UnivariatePolynomial<BigInteger>> numberField = (AlgebraicNumberField<UnivariatePolynomial<BigInteger>>) a.ring; integerPrimitivePart(a); integerPrimitivePart(b); if (!a.lc().isConstant()) a.multiply(numberField.normalizer(a.lc())); if (!b.lc().isConstant()) b.multiply(numberField.normalizer(b.lc())); integerPrimitivePart(a); integerPrimitivePart(b); UnivariatePolynomial<UnivariatePolynomial<BigInteger>> simpleGCD = TrivialGCDInNumberField(a, b); if (simpleGCD != null) return simpleGCD; return gcdAssociateInNumberField0(a, b); } private UnivariateGCD(); @SuppressWarnings("unchecked") static T PolynomialGCD(T a, T b); @SuppressWarnings("unchecked") static T[] PolynomialExtendedGCD(T a, T b); static T[] PolynomialFirstBezoutCoefficient(T a, T b); static T PolynomialGCD(T... polynomials); static T PolynomialGCD(Iterable<T> polynomials); static T EuclidGCD(final T a, final T b); @SuppressWarnings("unchecked") static T[] ExtendedEuclidGCD(final T a, final T b); static T[] EuclidFirstBezoutCoefficient(final T a, final T b); static T HalfGCD(T a, T b); static T[] ExtendedHalfGCD(T a, T b); static UnivariatePolynomialZ64 ModularGCD(UnivariatePolynomialZ64 a, UnivariatePolynomialZ64 b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<BigInteger> ModularGCD(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedRationalGCD( UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<Rational<BigInteger>>[] ModularExtendedResultantGCDInQ(UnivariatePolynomial<Rational<BigInteger>> a, UnivariatePolynomial<Rational<BigInteger>> b); @SuppressWarnings({"ConstantConditions", "unchecked"}) static UnivariatePolynomial<BigInteger>[] ModularExtendedResultantGCDInZ(UnivariatePolynomial<BigInteger> a, UnivariatePolynomial<BigInteger> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> PolynomialGCDInNumberField(UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> a, UnivariatePolynomial<UnivariatePolynomial<Rational<BigInteger>>> b); @SuppressWarnings("ConstantConditions") static UnivariatePolynomial<UnivariatePolynomial<BigInteger>> PolynomialGCDInRingOfIntegersOfNumberField(UnivariatePolynomial<UnivariatePolynomial<BigInteger>> a, UnivariatePolynomial<UnivariatePolynomial<BigInteger>> b); static boolean updateCRT(ChineseRemaindersMagic<BigInteger> magic, UnivariatePolynomial<BigInteger> accumulated, UnivariatePolynomialZp64 update); }
@Test public void test39_algext() { UnivariatePolynomial<BigInteger> minimalPoly = UnivariatePolynomial.create(-2, 0, 0, 0, 0, 0, 1); AlgebraicNumberField<UnivariatePolynomial<BigInteger>> field = AlgebraicNumberField(minimalPoly); Coder<UnivariatePolynomial<BigInteger>, ?, ?> cfCoder = Coder.mkUnivariateCoder(field, "s"); UnivariateRing<UnivariatePolynomial<UnivariatePolynomial<BigInteger>>> uRing = UnivariateRing(field); Coder<UnivariatePolynomial<UnivariatePolynomial<BigInteger>>, ?, ?> coder = Coder.mkUnivariateCoder(uRing, cfCoder, "x"); UnivariatePolynomial<UnivariatePolynomial<BigInteger>> a = coder.parse("(1 - s + (12 - 3*s^5) * x^5) * ( 1 + s*x^2 + 12*x^5)"); UnivariatePolynomial<UnivariatePolynomial<BigInteger>> b = coder.parse("(1 - s + (12 - 3*s^5) * x^5) * ( 14 - s*x + 2*s*x^17)"); UnivariatePolynomial<UnivariatePolynomial<BigInteger>> gcd = UnivariateGCD.gcdAssociateInNumberField(a, b); assertTrue(pseudoDivideAndRemainder(a, gcd, true)[1].isZero()); assertTrue(pseudoDivideAndRemainder(b, gcd, true)[1].isZero()); }
Spectrums { public static <T extends Peak, S extends MutableSpectrum<T>> void sortSpectrumByMass(S spectrum) { if (spectrum instanceof OrderedSpectrum) return; __sortSpectrum__(spectrum, new PeakComparator<T, S>() { @Override public int compare(S left, S right, int i, int j) { return Double.compare(left.getMzAt(i), right.getMzAt(j)); } }); } static Spectrum<Peak> wrap(double[] mz, double[] intensities); static Spectrum<Peak> wrap(float[] mz, float[] intensities); static Spectrum<P> wrap(final List<P> peaks); static SimpleSpectrum neutralMassSpectrum(final S spectrum, final Ionization ionization); static SimpleSpectrum neutralMassSpectrum(final S spectrum, final PrecursorIonType ionization); static SimpleSpectrum mergeSpectra(@SuppressWarnings("unchecked") final S... spectra); static SimpleSpectrum mergeSpectra(@SuppressWarnings("unchecked") final List<S> spectra); static SimpleSpectrum mergeSpectra(Deviation massWindow, boolean sumIntenstities, boolean mergeMasses, @SuppressWarnings("unchecked") final S... spectra); static int getFirstPeakGreaterOrEqualThan(S spec, double mass); static double cosineProduct(S left, S2 right, Deviation deviation); static double cosineProductWithLosses(S left, S2 right, Deviation deviation, double precursorLeft, double precursorRight); static SimpleSpectrum getInversedSpectrum(S spec, double precursor); static double dotProductPeaks(S left, S2 right, Deviation deviation); static SimpleSpectrum mergeSpectra(Deviation massWindow, boolean sumIntenstities, boolean mergeMasses, final List<S> spectra); static Comparator<T> getPeakIntensityComparatorReversed(); static Comparator<T> getPeakMassComparator(); static Spectrum<P> getIntensityOrderedSpectrum(S spectrum); static void addOffset(S s, double mzOffset, double intensityOffset); static void scale(S s, double mzScale, double intensityScale); static boolean haveEqualPeaks(S a, S2 b); static S subtractAdductsFromSpectrum(S spectrum, Ionization ionization); static SimpleSpectrum map(S spectrum, Transformation<P1, Peak> t); static S transform(S spectrum, Transformation<P, P> t); static S filter(S spectrum, Predicate<P> predicate); static S filter(S spectrum, PeakPredicate predicate); static SimpleSpectrum mergePeaksWithinSpectrum(S msms, Deviation mergeWindow, boolean sumIntensities, boolean mergeMasses); static void cutByMassThreshold(S msms, double maximalMass); static void applyBaseline(S msms, double intensityThreshold); static SimpleSpectrum getBaselined(S msms, double intensityThreshold); static void filterIsotpePeaks(S spec, Deviation deviation); static void filterIsotpePeaks(S spec, Deviation deviation, double maxIntensityRatioAt0, double maxIntensityRatioAt1000, int maxNumberOfIsotopePeaks, ChemicalAlphabet alphabet); static void filterIsotopePeaks(S spec, Deviation deviation, double maxIntensityRatioAt0, double maxIntensityRatioAt1000, int maxNumberOfIsotopePeaks, ChemicalAlphabet alphabet, boolean checkForConsistentIsotopeAssignment); static SimpleSpectrum extractIsotopePattern(S ms1Spec, MassDeviation deviation, double targetMz); static SimpleSpectrum extractIsotopePattern(S ms1Spec, MassDeviation deviation, double targetMz, int absCharge); static SimpleSpectrum extractIsotopePattern(S ms1Spec, MassDeviation deviation, double targetMz, int absCharge, boolean mergePeaks); static SimpleSpectrum extractIsotopePatternFromMultipleSpectra(List<S> ms1Spectra, MS1MassDeviation deviation, double targetMz, int absCharge, boolean mergePeaks, double minIsoPeakFreq); static SimpleSpectrum extendPattern(Spectrum<Peak> mainPattern, Spectrum<Peak> longerPattern, double minIntensityCutoff); static PrecursorIonType[] guessIonization(Spectrum<Peak> ms1, double ionMass, Deviation deviation, PrecursorIonType[] ionTypes); static SimpleSpectrum empty(); static double calculateTIC(S spec); static double calculateTIC(S spec, Range<Double> massRange, double intensityBaseline); static double calculateTIC(S spec, double intensityBaseLine); static SimpleSpectrum extractMostIntensivePeaks(S spectrum, int numberOfPeaksPerMassWindow, double slidingWindowWidth); static SimpleSpectrum from(Collection<? extends Peak> peaks); static SimpleSpectrum from(List<Number> mzsL, List<Number> intensitiesL); static SimpleSpectrum from(TDoubleArrayList mzsL, TDoubleArrayList intensitiesL); static SimpleSpectrum subspectrum(S spectrum, int from, int length); static List<P> extractPeakList(S spectrum); static double getMinimalIntensity(S spectrum); static double getMaximalIntensity(S spectrum); static int getIndexOfPeakWithMinimalIntensity(S spectrum); static int getIndexOfPeakWithMaximalIntensity(S spectrum); static int getIndexOfPeakWithMinimalMass(S spectrum); static int getIndexOfPeakWithMaximalMass(S spectrum); static List<Peak> copyPeakList(S spectrum); @SuppressWarnings("rawtypes") static double[] copyIntensities(S spectrum, double[] buffer, int offset); static double[] copyIntensities(S spectrum, double[] buffer); static double[] copyIntensities(S spectrum); @SuppressWarnings("rawtypes") static double[] copyMasses(S spectrum, double[] buffer, int offset); static double[] copyMasses(S spectrum, double[] buffer); static double[] copyMasses(S spectrum); static void normalize(S spectrum, Normalization norm); static void normalizeByPeak(S spectrum, int peakIdx, double base); static SimpleSpectrum getNormalizedSpectrum(S spectrum, Normalization norm); static void normalizeToMax(S spectrum, double norm); static void normalizeToSum(S spectrum, double norm); static int indexOfPeak(S spectrum, P peak); static int search(S spectrum, double mz, Deviation d); static int mostIntensivePeakWithin(S spectrum, double mz, Deviation dev); static int indexOfFirstPeakWithin(S spectrum, double mz, Deviation dev); static int indexOfFirstPeakWithin(S spectrum, double begin, double end); static int binarySearch(S spectrum, double mz, Deviation d); static int binarySearch(S spectrum, double mz); static int binarySearch(S spectrum, double mz, double intensity); static double getMedianIntensity(Spectrum<? extends Peak> spec); static Spectrum<Peak> getMassOrderedSpectrum(Spectrum<? extends Peak> spectrum); static boolean isMassOrderedSpectrum(Spectrum<? extends Peak> spectrum); static void sortSpectrumByMass(S spectrum); static void sortSpectrumByDescendingMass(S spectrum); static void sortSpectrumByIntensity(S spectrum); static void sortSpectrumByDescendingIntensity(S spectrum); static S selectSpectrumWithMostIntensePrecursor(List<S> spectra, double precursorMass, Deviation dev); static AlreadyOrderedSpectrum<T> getAlreadyOrderedSpectrum(S spec); static void writePeaks(BufferedWriter writer, Spectrum spec); final static double DELTA; }
@Test public void testSort() { SimpleMutableSpectrum spectrum = new SimpleMutableSpectrum(); spectrum.addPeak(new SimplePeak(5,3)); spectrum.addPeak(new SimplePeak(3,2)); spectrum.addPeak(new SimplePeak(1,4)); Spectrums.sortSpectrumByMass(spectrum); Peak last = null; for (Peak p : spectrum) { if (last != null) { assertTrue(p.getMass()>last.getMass()); } } { SimpleSpectrum sp = new SimpleSpectrum(new double[]{5, 3, 1, 2, 8, 4, 11, 2, 10, 1}, new double[]{2, 3, 4, 5, 2, 1, 1, 2, 1, 3}); assertTrue(sp instanceof OrderedSpectrum); last = null; for (Peak p : sp) { if (last != null) { assertTrue(p.getMass() > last.getMass()); } } } { final SimpleMutableSpectrum spec = new SimpleMutableSpectrum(); final Random r = new Random(seed); for (int i=0; i < 5000; ++i) { spec.addPeak(Math.abs(r.nextDouble()), Math.abs(r.nextDouble())); } Spectrums.sortSpectrumByMass(spec); boolean isSorted = true; for (int i=1; i < spec.size(); ++i) { if (spec.getMzAt(i) < spec.getMzAt(i-1)) isSorted = false; } assertTrue("spectrum should be sorted", isSorted); } { final SimpleMutableSpectrum spec = new SimpleMutableSpectrum(); final Random r = new Random(seed); for (int i=0; i < 5000; ++i) { spec.addPeak(0, Math.abs(r.nextDouble())); } for (int i=0; i <= 50; ++i) { spec.setMzAt(r.nextInt(spec.size()), Math.abs(r.nextDouble())); } Spectrums.sortSpectrumByMass(spec); boolean isSorted = true; for (int i=1; i < spec.size(); ++i) { if (spec.getMzAt(i) < spec.getMzAt(i-1)) isSorted = false; } assertTrue("spectrum should be sorted", isSorted); } }
IntFloatHashMap implements IntFloatMap { public IntFloatIterator entries() { return (values == null) ? IntFloatIterator.Empty : new KeyValueIterator(); } IntFloatHashMap(int size); int size(); int capacity(); float averageOpsPerAccess(); int collisionKeys(); int reallocations(); boolean isHash(); int collisions(); boolean isEmpty(); float get(int A); void put(int key, float value); void putIfGreater(int key, float value); IntFloatIterator entries(); }
@Test(expected = NoSuchElementException.class) public void TestEmptyIterator() { final IntFloatHashMap map = new IntFloatHashMap(10); final IntFloatIterator iter = map.entries(); assertEquals(iter.hasNext(), false); iter.getKey(); }
MassDecomposer { public List<int[]> decompose(double mass, Deviation deviation, Map<T, Interval> boundaries){ final double abs = deviation.absoluteFor(mass); return decompose(Math.max(0,mass-abs), Math.max(0,mass+abs), boundaries); } MassDecomposer(Alphabet<T> alphabet); List<int[]> decompose(double mass, Deviation deviation, Map<T, Interval> boundaries); DecompIterator<T> decomposeIterator(double mass, Deviation deviation, Map<T, Interval> boundaries); DecompIterator<T> decomposeIterator(double from, double to); DecompIterator<T> decomposeIterator(double from, double to, Map<T, Interval> boundaries); Alphabet<T> getAlphabet(); boolean maybeDecomposable(double startMass, double endMass); List<int[]> decompose(double from, double to); List<int[]> decompose(final double from, final double to, Map<T, Interval> boundaries); void init(); }
@Test public void singleElementTest(){ final PeriodicTable table = PeriodicTable.getInstance(); final TableSelection tableSelection = TableSelection.fromString(table, "CHNOPS"); final MolecularFormula mf = MolecularFormula.parseOrThrow("C16"); final double mass = mf.getMass(); final Deviation dev = new Deviation(100, 0.001); ChemicalAlphabet alphabet = new ChemicalAlphabet(tableSelection, table.getAllByName("C")); MassDecomposer<Element> decomposer = new RangeMassDecomposer<>(new ChemicalAlphabetWrapper(alphabet)); Map<Element, Interval> boundary = new HashMap<Element, Interval>(); boundary.put(table.getByName("C"), new Interval(0, Integer.MAX_VALUE)); List<int[]> compomers = decomposer.decompose(mass, dev, boundary); List<MolecularFormula> formulas = new ArrayList<MolecularFormula>(compomers.size()); for (int[] c : compomers) { formulas.add(alphabet.decompositionToFormula(c)); } assertEquals(mf, formulas.get(0)); }
PatternGenerator { public ChargedSpectrum generatePattern(MolecularFormula formula) { return generatePattern(addAtomsToFormula(formula), Integer.MAX_VALUE); } PatternGenerator(IsotopicDistribution dist, Ionization ion, Normalization mode); PatternGenerator(Ionization ion); PatternGenerator(Ionization ion, Normalization mode); PatternGenerator(Normalization mode); PatternGenerator(); ChargedSpectrum generatePattern(MolecularFormula formula); ChargedSpectrum generatePattern(MolecularFormula formula, int numberOfPeaks); ChargedSpectrum generatePatternWithTreshold(MolecularFormula formula, double treshold); }
@Test public void testNonChargedPatternGeneration() { try { PeriodicTable.getInstance().setDistribution(new IsotopicDistributionJSONFile().fromClassPath("/chemcalc_distribution.json")); } catch (IOException e) { throw new RuntimeException(e); } final PatternGenerator generator = new PatternGenerator(new Charge(1), Normalization.Max(100)); final MolecularFormula mol = MolecularFormula.parseOrThrow("C6H12O6"); final Spectrum<? extends Peak> spectrum = generator.generatePattern(mol, 6); assertEquals(6, spectrum.size()); assertEquals(180.06, spectrum.getMzAt(0), 0.01); assertEquals(181.07, spectrum.getMzAt(1), 0.01); assertEquals(182.07, spectrum.getMzAt(2), 0.01); assertEquals(183.07, spectrum.getMzAt(3), 0.01); assertEquals(184.07, spectrum.getMzAt(4), 0.01); assertEquals(100, spectrum.getIntensityAt(0), 0.01); assertEquals(6.856, spectrum.getIntensityAt(1), 0.001); assertEquals(1.432, spectrum.getIntensityAt(2), 0.001); assertEquals(0.0866, spectrum.getIntensityAt(3), 0.001); assertEquals(0.009, spectrum.getIntensityAt(4), 0.001); } @Test public void testChargedPatternGeneration() { final PatternGenerator generator = new PatternGenerator(PeriodicTable.getInstance().ionByNameOrThrow("[M+Na]+").getIonization(), Normalization.Max(100)); final PatternGenerator generatorRaw = new PatternGenerator(new Charge(1), Normalization.Max(100)); final MolecularFormula glucose = MolecularFormula.parseOrThrow("C6H12O6"); final MolecularFormula glucoseIonized = MolecularFormula.parseOrThrow("C6H12O6Na"); final Spectrum<? extends Peak> spectrum = generator.generatePattern(glucose, 5); final Spectrum<? extends Peak> spectrum2 = generatorRaw.generatePattern(glucoseIonized, 5); assertTrue(Spectrums.haveEqualPeaks(spectrum, spectrum2)); }
HierarchicalClustering { public void cluster(T[] elements, double[][] pairwiseDistances) { cluster(elements, pairwiseDistances, Double.POSITIVE_INFINITY); } HierarchicalClustering(DistanceMeasureStrategy distanceMeasureStrategy); void cluster(T[] elements, double[][] pairwiseDistances); void cluster(T[] elements, double[][] pairwiseDistances, double threshold); List<List<T>> getClusters(); ClusteringTree<T> getClusteringTree(); }
@Test public void cluster() { String[] elements = new String[]{"A", "B", "C", "D", "E", "F", "G"}; double[][] distances = new double[][]{ new double[]{0, 1, 4, 2, 5, 6, 7}, new double[]{1, 0, 5, 3, 8, 9, 9}, new double[]{4, 5, 0, 5, 3, 2, 2}, new double[]{2, 3, 5, 0, 4, 5, 3}, new double[]{5, 8, 3, 4, 0, 6, 7}, new double[]{6, 9, 2, 5, 6, 0, 2}, new double[]{7, 9, 2, 3, 7, 2, 0} }; double threshold = 3.0; List<List<String>> clusters = clusterAndSort(elements, distances, threshold); assertEquals(3, clusters.size()); assertArrayEquals(new String[]{"A","B","D"}, clusters.get(0).toArray(new String[0])); assertArrayEquals(new String[]{"C","F","G"}, clusters.get(1).toArray(new String[0])); assertArrayEquals(new String[]{"E"}, clusters.get(2).toArray(new String[0])); threshold = 2.0; clusters = clusterAndSort(elements, distances, threshold); assertEquals(4, clusters.size()); assertArrayEquals(new String[]{"A","B"}, clusters.get(0).toArray(new String[0])); assertArrayEquals(new String[]{"C","F","G"}, clusters.get(1).toArray(new String[0])); assertArrayEquals(new String[]{"D"}, clusters.get(2).toArray(new String[0])); assertArrayEquals(new String[]{"E"}, clusters.get(3).toArray(new String[0])); }
Spectrums { public static <S extends Spectrum<P>, P extends Peak> int search(S spectrum, double mz, Deviation d) { return (spectrum instanceof OrderedSpectrum) ? binarySearch(spectrum, mz, d) : linearSearch(spectrum, mz, d); } static Spectrum<Peak> wrap(double[] mz, double[] intensities); static Spectrum<Peak> wrap(float[] mz, float[] intensities); static Spectrum<P> wrap(final List<P> peaks); static SimpleSpectrum neutralMassSpectrum(final S spectrum, final Ionization ionization); static SimpleSpectrum neutralMassSpectrum(final S spectrum, final PrecursorIonType ionization); static SimpleSpectrum mergeSpectra(@SuppressWarnings("unchecked") final S... spectra); static SimpleSpectrum mergeSpectra(@SuppressWarnings("unchecked") final List<S> spectra); static SimpleSpectrum mergeSpectra(Deviation massWindow, boolean sumIntenstities, boolean mergeMasses, @SuppressWarnings("unchecked") final S... spectra); static int getFirstPeakGreaterOrEqualThan(S spec, double mass); static double cosineProduct(S left, S2 right, Deviation deviation); static double cosineProductWithLosses(S left, S2 right, Deviation deviation, double precursorLeft, double precursorRight); static SimpleSpectrum getInversedSpectrum(S spec, double precursor); static double dotProductPeaks(S left, S2 right, Deviation deviation); static SimpleSpectrum mergeSpectra(Deviation massWindow, boolean sumIntenstities, boolean mergeMasses, final List<S> spectra); static Comparator<T> getPeakIntensityComparatorReversed(); static Comparator<T> getPeakMassComparator(); static Spectrum<P> getIntensityOrderedSpectrum(S spectrum); static void addOffset(S s, double mzOffset, double intensityOffset); static void scale(S s, double mzScale, double intensityScale); static boolean haveEqualPeaks(S a, S2 b); static S subtractAdductsFromSpectrum(S spectrum, Ionization ionization); static SimpleSpectrum map(S spectrum, Transformation<P1, Peak> t); static S transform(S spectrum, Transformation<P, P> t); static S filter(S spectrum, Predicate<P> predicate); static S filter(S spectrum, PeakPredicate predicate); static SimpleSpectrum mergePeaksWithinSpectrum(S msms, Deviation mergeWindow, boolean sumIntensities, boolean mergeMasses); static void cutByMassThreshold(S msms, double maximalMass); static void applyBaseline(S msms, double intensityThreshold); static SimpleSpectrum getBaselined(S msms, double intensityThreshold); static void filterIsotpePeaks(S spec, Deviation deviation); static void filterIsotpePeaks(S spec, Deviation deviation, double maxIntensityRatioAt0, double maxIntensityRatioAt1000, int maxNumberOfIsotopePeaks, ChemicalAlphabet alphabet); static void filterIsotopePeaks(S spec, Deviation deviation, double maxIntensityRatioAt0, double maxIntensityRatioAt1000, int maxNumberOfIsotopePeaks, ChemicalAlphabet alphabet, boolean checkForConsistentIsotopeAssignment); static SimpleSpectrum extractIsotopePattern(S ms1Spec, MassDeviation deviation, double targetMz); static SimpleSpectrum extractIsotopePattern(S ms1Spec, MassDeviation deviation, double targetMz, int absCharge); static SimpleSpectrum extractIsotopePattern(S ms1Spec, MassDeviation deviation, double targetMz, int absCharge, boolean mergePeaks); static SimpleSpectrum extractIsotopePatternFromMultipleSpectra(List<S> ms1Spectra, MS1MassDeviation deviation, double targetMz, int absCharge, boolean mergePeaks, double minIsoPeakFreq); static SimpleSpectrum extendPattern(Spectrum<Peak> mainPattern, Spectrum<Peak> longerPattern, double minIntensityCutoff); static PrecursorIonType[] guessIonization(Spectrum<Peak> ms1, double ionMass, Deviation deviation, PrecursorIonType[] ionTypes); static SimpleSpectrum empty(); static double calculateTIC(S spec); static double calculateTIC(S spec, Range<Double> massRange, double intensityBaseline); static double calculateTIC(S spec, double intensityBaseLine); static SimpleSpectrum extractMostIntensivePeaks(S spectrum, int numberOfPeaksPerMassWindow, double slidingWindowWidth); static SimpleSpectrum from(Collection<? extends Peak> peaks); static SimpleSpectrum from(List<Number> mzsL, List<Number> intensitiesL); static SimpleSpectrum from(TDoubleArrayList mzsL, TDoubleArrayList intensitiesL); static SimpleSpectrum subspectrum(S spectrum, int from, int length); static List<P> extractPeakList(S spectrum); static double getMinimalIntensity(S spectrum); static double getMaximalIntensity(S spectrum); static int getIndexOfPeakWithMinimalIntensity(S spectrum); static int getIndexOfPeakWithMaximalIntensity(S spectrum); static int getIndexOfPeakWithMinimalMass(S spectrum); static int getIndexOfPeakWithMaximalMass(S spectrum); static List<Peak> copyPeakList(S spectrum); @SuppressWarnings("rawtypes") static double[] copyIntensities(S spectrum, double[] buffer, int offset); static double[] copyIntensities(S spectrum, double[] buffer); static double[] copyIntensities(S spectrum); @SuppressWarnings("rawtypes") static double[] copyMasses(S spectrum, double[] buffer, int offset); static double[] copyMasses(S spectrum, double[] buffer); static double[] copyMasses(S spectrum); static void normalize(S spectrum, Normalization norm); static void normalizeByPeak(S spectrum, int peakIdx, double base); static SimpleSpectrum getNormalizedSpectrum(S spectrum, Normalization norm); static void normalizeToMax(S spectrum, double norm); static void normalizeToSum(S spectrum, double norm); static int indexOfPeak(S spectrum, P peak); static int search(S spectrum, double mz, Deviation d); static int mostIntensivePeakWithin(S spectrum, double mz, Deviation dev); static int indexOfFirstPeakWithin(S spectrum, double mz, Deviation dev); static int indexOfFirstPeakWithin(S spectrum, double begin, double end); static int binarySearch(S spectrum, double mz, Deviation d); static int binarySearch(S spectrum, double mz); static int binarySearch(S spectrum, double mz, double intensity); static double getMedianIntensity(Spectrum<? extends Peak> spec); static Spectrum<Peak> getMassOrderedSpectrum(Spectrum<? extends Peak> spectrum); static boolean isMassOrderedSpectrum(Spectrum<? extends Peak> spectrum); static void sortSpectrumByMass(S spectrum); static void sortSpectrumByDescendingMass(S spectrum); static void sortSpectrumByIntensity(S spectrum); static void sortSpectrumByDescendingIntensity(S spectrum); static S selectSpectrumWithMostIntensePrecursor(List<S> spectra, double precursorMass, Deviation dev); static AlreadyOrderedSpectrum<T> getAlreadyOrderedSpectrum(S spec); static void writePeaks(BufferedWriter writer, Spectrum spec); final static double DELTA; }
@Test public void testSearch() { SimpleMutableSpectrum spectrum = new SimpleMutableSpectrum(); spectrum.addPeak(new SimplePeak(5,3)); spectrum.addPeak(new SimplePeak(3,2)); spectrum.addPeak(new SimplePeak(1,4)); Spectrums.sortSpectrumByMass(spectrum); assertTrue(Spectrums.binarySearch(spectrum, 18)<0); assertEquals(2, Spectrums.binarySearch(spectrum, 5)); assertEquals(1, Spectrums.binarySearch(spectrum, 3)); assertEquals(0, Spectrums.binarySearch(spectrum,1)); SimpleSpectrum sp = new SimpleSpectrum(new double[]{1,2,3,5}, new double[]{2,3,4,5}); assertTrue(Spectrums.binarySearch(sp, 18)<0); assertEquals(3, Spectrums.binarySearch(sp, 5)); assertEquals(2, Spectrums.binarySearch(sp, 3)); assertEquals(1, Spectrums.binarySearch(sp, 2)); assertEquals(0, Spectrums.binarySearch(sp, 1)); }
Spectrums { public static <P extends Peak, S extends MutableSpectrum<P>> void filterIsotpePeaks(S spec, Deviation deviation) { filterIsotpePeaks(spec, deviation, 0.2, 0.55, 3, new ChemicalAlphabet()); } static Spectrum<Peak> wrap(double[] mz, double[] intensities); static Spectrum<Peak> wrap(float[] mz, float[] intensities); static Spectrum<P> wrap(final List<P> peaks); static SimpleSpectrum neutralMassSpectrum(final S spectrum, final Ionization ionization); static SimpleSpectrum neutralMassSpectrum(final S spectrum, final PrecursorIonType ionization); static SimpleSpectrum mergeSpectra(@SuppressWarnings("unchecked") final S... spectra); static SimpleSpectrum mergeSpectra(@SuppressWarnings("unchecked") final List<S> spectra); static SimpleSpectrum mergeSpectra(Deviation massWindow, boolean sumIntenstities, boolean mergeMasses, @SuppressWarnings("unchecked") final S... spectra); static int getFirstPeakGreaterOrEqualThan(S spec, double mass); static double cosineProduct(S left, S2 right, Deviation deviation); static double cosineProductWithLosses(S left, S2 right, Deviation deviation, double precursorLeft, double precursorRight); static SimpleSpectrum getInversedSpectrum(S spec, double precursor); static double dotProductPeaks(S left, S2 right, Deviation deviation); static SimpleSpectrum mergeSpectra(Deviation massWindow, boolean sumIntenstities, boolean mergeMasses, final List<S> spectra); static Comparator<T> getPeakIntensityComparatorReversed(); static Comparator<T> getPeakMassComparator(); static Spectrum<P> getIntensityOrderedSpectrum(S spectrum); static void addOffset(S s, double mzOffset, double intensityOffset); static void scale(S s, double mzScale, double intensityScale); static boolean haveEqualPeaks(S a, S2 b); static S subtractAdductsFromSpectrum(S spectrum, Ionization ionization); static SimpleSpectrum map(S spectrum, Transformation<P1, Peak> t); static S transform(S spectrum, Transformation<P, P> t); static S filter(S spectrum, Predicate<P> predicate); static S filter(S spectrum, PeakPredicate predicate); static SimpleSpectrum mergePeaksWithinSpectrum(S msms, Deviation mergeWindow, boolean sumIntensities, boolean mergeMasses); static void cutByMassThreshold(S msms, double maximalMass); static void applyBaseline(S msms, double intensityThreshold); static SimpleSpectrum getBaselined(S msms, double intensityThreshold); static void filterIsotpePeaks(S spec, Deviation deviation); static void filterIsotpePeaks(S spec, Deviation deviation, double maxIntensityRatioAt0, double maxIntensityRatioAt1000, int maxNumberOfIsotopePeaks, ChemicalAlphabet alphabet); static void filterIsotopePeaks(S spec, Deviation deviation, double maxIntensityRatioAt0, double maxIntensityRatioAt1000, int maxNumberOfIsotopePeaks, ChemicalAlphabet alphabet, boolean checkForConsistentIsotopeAssignment); static SimpleSpectrum extractIsotopePattern(S ms1Spec, MassDeviation deviation, double targetMz); static SimpleSpectrum extractIsotopePattern(S ms1Spec, MassDeviation deviation, double targetMz, int absCharge); static SimpleSpectrum extractIsotopePattern(S ms1Spec, MassDeviation deviation, double targetMz, int absCharge, boolean mergePeaks); static SimpleSpectrum extractIsotopePatternFromMultipleSpectra(List<S> ms1Spectra, MS1MassDeviation deviation, double targetMz, int absCharge, boolean mergePeaks, double minIsoPeakFreq); static SimpleSpectrum extendPattern(Spectrum<Peak> mainPattern, Spectrum<Peak> longerPattern, double minIntensityCutoff); static PrecursorIonType[] guessIonization(Spectrum<Peak> ms1, double ionMass, Deviation deviation, PrecursorIonType[] ionTypes); static SimpleSpectrum empty(); static double calculateTIC(S spec); static double calculateTIC(S spec, Range<Double> massRange, double intensityBaseline); static double calculateTIC(S spec, double intensityBaseLine); static SimpleSpectrum extractMostIntensivePeaks(S spectrum, int numberOfPeaksPerMassWindow, double slidingWindowWidth); static SimpleSpectrum from(Collection<? extends Peak> peaks); static SimpleSpectrum from(List<Number> mzsL, List<Number> intensitiesL); static SimpleSpectrum from(TDoubleArrayList mzsL, TDoubleArrayList intensitiesL); static SimpleSpectrum subspectrum(S spectrum, int from, int length); static List<P> extractPeakList(S spectrum); static double getMinimalIntensity(S spectrum); static double getMaximalIntensity(S spectrum); static int getIndexOfPeakWithMinimalIntensity(S spectrum); static int getIndexOfPeakWithMaximalIntensity(S spectrum); static int getIndexOfPeakWithMinimalMass(S spectrum); static int getIndexOfPeakWithMaximalMass(S spectrum); static List<Peak> copyPeakList(S spectrum); @SuppressWarnings("rawtypes") static double[] copyIntensities(S spectrum, double[] buffer, int offset); static double[] copyIntensities(S spectrum, double[] buffer); static double[] copyIntensities(S spectrum); @SuppressWarnings("rawtypes") static double[] copyMasses(S spectrum, double[] buffer, int offset); static double[] copyMasses(S spectrum, double[] buffer); static double[] copyMasses(S spectrum); static void normalize(S spectrum, Normalization norm); static void normalizeByPeak(S spectrum, int peakIdx, double base); static SimpleSpectrum getNormalizedSpectrum(S spectrum, Normalization norm); static void normalizeToMax(S spectrum, double norm); static void normalizeToSum(S spectrum, double norm); static int indexOfPeak(S spectrum, P peak); static int search(S spectrum, double mz, Deviation d); static int mostIntensivePeakWithin(S spectrum, double mz, Deviation dev); static int indexOfFirstPeakWithin(S spectrum, double mz, Deviation dev); static int indexOfFirstPeakWithin(S spectrum, double begin, double end); static int binarySearch(S spectrum, double mz, Deviation d); static int binarySearch(S spectrum, double mz); static int binarySearch(S spectrum, double mz, double intensity); static double getMedianIntensity(Spectrum<? extends Peak> spec); static Spectrum<Peak> getMassOrderedSpectrum(Spectrum<? extends Peak> spectrum); static boolean isMassOrderedSpectrum(Spectrum<? extends Peak> spectrum); static void sortSpectrumByMass(S spectrum); static void sortSpectrumByDescendingMass(S spectrum); static void sortSpectrumByIntensity(S spectrum); static void sortSpectrumByDescendingIntensity(S spectrum); static S selectSpectrumWithMostIntensePrecursor(List<S> spectra, double precursorMass, Deviation dev); static AlreadyOrderedSpectrum<T> getAlreadyOrderedSpectrum(S spec); static void writePeaks(BufferedWriter writer, Spectrum spec); final static double DELTA; }
@Test public void testFilterIsotpes(){ SimpleMutableSpectrum spectrum = new SimpleMutableSpectrum(); spectrum.addPeak(new SimplePeak(540.3121726360905, 0.6640867687951271)); spectrum.addPeak(new SimplePeak(541.3152753047328, 0.2737396761795133)); spectrum.addPeak(new SimplePeak(542.318370128813, 0.05499724422532549)); spectrum.addPeak(new SimplePeak(543.3214567823122, 0.007176310800034031)); spectrum.addPeak(new SimplePeak(540.3054645080905, 0.7104014905351598)); spectrum.addPeak(new SimplePeak(541.307970285248, 0.2443438820957737)); spectrum.addPeak(new SimplePeak(542.3104462599396, 0.0408362176639628)); spectrum.addPeak(new SimplePeak(543.3128911877274, 0.004418409705103798)); spectrum.addPeak(new SimplePeak(541.3199976680905, 0.6640109468088424)); spectrum.addPeak(new SimplePeak(542.323101222116, 0.27378479204311157)); spectrum.addPeak(new SimplePeak(543.3261969812916, 0.05502244501368937)); spectrum.addPeak(new SimplePeak(544.3292846236769, 0.007181816134356579)); ChemicalAlphabet alphabet = new ChemicalAlphabet(); Deviation deviation = new Deviation(10); Spectrums.filterIsotpePeaks(spectrum, deviation, 0.2, 0.55, 4, alphabet); assertEquals(3, spectrum.size()); assertEquals(new SimplePeak(540.3054645080905, 0.7104014905351598), spectrum.getPeakAt(0)); assertEquals(new SimplePeak(540.3121726360905, 0.6640867687951271), spectrum.getPeakAt(1)); assertEquals(new SimplePeak(541.3199976680905, 0.6640109468088424), spectrum.getPeakAt(2)); }
ParameterConfig { public Object createInstanceWithDefaults(String key) { Class<?> clazz = getClassFromKeyAndThrow(key); return createInstanceWithDefaults(clazz); } ParameterConfig(CombinedConfiguration config, CombinedConfiguration classesConfig, String layoutConfigName, String localConfigName, String configRoot, String classRoot); ParameterConfig(CombinedConfiguration config, CombinedConfiguration classesConfig, PropertiesConfigurationLayout layout, String localConfigName, String configRoot, String classRoot); void write(Writer writer); void writeModified(Writer writer); ParameterConfig newIndependentInstance(@NotNull final String name); ParameterConfig newIndependentInstance(@NotNull final String name, boolean overrideExisting); ParameterConfig newIndependentInstance(@NotNull final ParameterConfig modificationLayer, boolean overrideExisting); ParameterConfig newIndependentInstance(@NotNull final InputStream streamToLoad, @NotNull final String name, boolean overrideExisting); String getLocalConfigName(); boolean containsConfiguration(@NotNull String name); String shortKey(@NotNull String key); Iterator<String> getConfigKeys(); Iterator<String> getModifiedConfigKeys(); Iterator<String> getClassConfigKeys(); ImmutableConfiguration getModifiedConfigs(); ImmutableConfiguration getConfigs(); ImmutableConfiguration getClassConfigs(); boolean isModifiable(); Optional<String[]> getConfigDescription(String key); String getConfigValue(@NotNull String key); boolean isInstantiatableWithDefaults(Class<C> klass); Class<?> changeConfig(@NotNull String key, @NotNull String value); boolean containsConfigKey(@NotNull String key); Class<?> getClassFromKeyAndThrow(@NotNull String key); Class<?> getClassFromKey(@NotNull String key); Object createInstanceWithDefaults(String key); C createInstanceWithDefaults(Class<C> klass); C createInstanceWithDefaults(Class<C> klass, @NotNull final String sourceParent); Map<Class<A>, A> createInstancesWithDefaults(Class<A> annotationType, boolean skipIllegalKeys); Map<Class<A>, A> createInstancesWithModifiedDefaults(Class<A> annotationType, boolean skipIllegalKeys); static T convertStringToType(@NotNull Class<T> fType, Type generic, @NotNull String stringValue); static T createCollectionInstance(final @NotNull Class<T> fType, final @NotNull Class<E> emementType); static T convertToDefaultType(@NotNull Class<T> targetType, @NotNull String stringValue); static T[] convertToCollection(@NotNull Class<T> targetElementType, @NotNull String values); static Constructor<T> getConstructor(Class<T> klass); final String configRoot; final String classRoot; }
@Test public void testCreateInstanceWithDefault() { Object r = PropertyManager.DEFAULTS.createInstanceWithDefaults(classToCreate); resultValidator.accept(classToCreate.cast(r)); }
IntFloatHashMap implements IntFloatMap { public int size() { return size; } IntFloatHashMap(int size); int size(); int capacity(); float averageOpsPerAccess(); int collisionKeys(); int reallocations(); boolean isHash(); int collisions(); boolean isEmpty(); float get(int A); void put(int key, float value); void putIfGreater(int key, float value); IntFloatIterator entries(); }
@Test public void testSize() { final IntFloatHashMap map = new IntFloatHashMap(10); assertEquals(0, map.size()); assertTrue(map.isEmpty()); map.put(1, 1.0f); map.put(2, 1.0f); map.put(3, 1.0f); assertEquals(3, map.size()); }
IntFloatHashMap implements IntFloatMap { public void put(int key, float value) { if (key <= 0){ throw new IllegalArgumentException("Non positive keys like " + key + " may not be entered into this map"); } if (Float.isNaN(value)){ throw new IllegalArgumentException("NaN may not be entered into this map"); } allocate(); int index = indexFor(hash(key, 0), keys.length); int k = keys[index]; for (int tries = 1; k != 0 && k != key && tries < keys.length; ++tries){ index = indexFor(hash(key, tries), keys.length); k = keys[index]; } if (k != 0 && k!= key){ throw new RuntimeException("Map is full"); } values[index] = value; if (k == 0) { keys[index] = key; ++size; if (size >= threshold){ resize(2 * keys.length); } } } IntFloatHashMap(int size); int size(); int capacity(); float averageOpsPerAccess(); int collisionKeys(); int reallocations(); boolean isHash(); int collisions(); boolean isEmpty(); float get(int A); void put(int key, float value); void putIfGreater(int key, float value); IntFloatIterator entries(); }
@Test(expected = IllegalArgumentException.class) public void dontAllowNullKeys() { final IntFloatHashMap map = new IntFloatHashMap(10); map.put(0, 1f); } @Test(expected = IllegalArgumentException.class) public void dontAllowNegativeKeys() { final IntFloatHashMap map = new IntFloatHashMap(10); map.put(-4, 1f); } @Test(expected = IllegalArgumentException.class) public void dontAllowNaNValues() { final IntFloatHashMap map = new IntFloatHashMap(10); map.put(1, Float.NaN); }
IntFloatHashMap implements IntFloatMap { public boolean isHash() { return true; } IntFloatHashMap(int size); int size(); int capacity(); float averageOpsPerAccess(); int collisionKeys(); int reallocations(); boolean isHash(); int collisions(); boolean isEmpty(); float get(int A); void put(int key, float value); void putIfGreater(int key, float value); IntFloatIterator entries(); }
@Test public void testIsAHash() { assertTrue(new IntFloatHashMap(10).isHash()); }
IntFloatHashMap implements IntFloatMap { public void putIfGreater(int key, float value) { if (key == 0){ throw new IllegalArgumentException("0 may not be entered into this map"); } if (Float.isNaN(value)){ throw new IllegalArgumentException("NaN may not be entered into this map"); } if (value < DEFAULT_VALUE) return; allocate(); int index = indexFor(hash(key, 0), keys.length); int k = keys[index]; for (int tries = 1; k != 0 && k != key && tries < keys.length; ++tries){ index = indexFor(hash(key, tries), keys.length); k = keys[index]; } if (k != 0 && k!= key){ throw new RuntimeException("Map is full"); } final float oldValue = values[index]; if (k == 0) { keys[index] = key; values[index] = value; ++size; if (size >= threshold){ resize(2 * keys.length); } } else if (oldValue < value) { values[index] = value; } } IntFloatHashMap(int size); int size(); int capacity(); float averageOpsPerAccess(); int collisionKeys(); int reallocations(); boolean isHash(); int collisions(); boolean isEmpty(); float get(int A); void put(int key, float value); void putIfGreater(int key, float value); IntFloatIterator entries(); }
@Test public void testPutIfGreater() { final IntFloatHashMap map = new IntFloatHashMap(10); map.put(1, 12f); map.put(13, 27f); map.put(126, 39f); map.putIfGreater(13, 15); assertEquals(3, map.size()); assertEquals(27f, map.get(13), DELTA); map.putIfGreater(13, 27f); assertEquals(3, map.size()); map.putIfGreater(13, 30f); assertEquals(3, map.size()); assertEquals(30f, map.get(13), DELTA); map.putIfGreater(13, -33f); assertEquals(30f, map.get(13), DELTA); }
Despesa { public void validarValor() { if(valor == null || valor.compareTo(BigDecimal.ZERO) == 0) { throw new BusinessException("Valor da despesa deve ser maior que zero"); } } void validarValor(); void pagar(); @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy") LocalDate getDataFormatada(); String getDescricaCategoria(); }
@Test public void validarValorMaiorQueZero() { final Despesa despesaValorDez = Despesa.builder() .valor(BigDecimal.TEN) .build(); despesaValorDez.validarValor(); final Despesa despesaValorUm = Despesa.builder() .valor(BigDecimal.ONE) .build(); despesaValorUm.validarValor(); final Despesa despesaValorZeroPontoUm = Despesa.builder() .valor(BigDecimal.valueOf(0.1)) .build(); despesaValorZeroPontoUm.validarValor(); } @Test(expected = BusinessException.class) public void validarValorZero() { final Despesa despesaValorZero = Despesa.builder() .valor(BigDecimal.ZERO) .build(); despesaValorZero.validarValor(); }
DespesaRestController { @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") public ResponseEntity delete(@PathVariable("id") Long id) { despesaService.delete(id); return ResponseEntity.ok().build(); } @RequestMapping(method = RequestMethod.POST, value = "/search") ResponseEntity findAll(@RequestBody DespesaBuscaTO despesaBuscaTO); @RequestMapping(method = RequestMethod.GET, value = "/{id}") ResponseEntity findById(@PathVariable("id") Long id); @RequestMapping(method = RequestMethod.POST) ResponseEntity save(@RequestBody Despesa despesa); @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") ResponseEntity delete(@PathVariable("id") Long id); @RequestMapping(method = RequestMethod.PUT, value = "/pagar/{id}") ResponseEntity<Despesa> pagar(@PathVariable("id") Long id); }
@Test public void excluir() throws Exception { mockMvc.perform(delete("/despesas/" + 1L) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); }
DespesaRestController { @RequestMapping(method = RequestMethod.PUT, value = "/pagar/{id}") public ResponseEntity<Despesa> pagar(@PathVariable("id") Long id) { final Despesa despesa = despesaService.findById(id); final Despesa despesaPaga = despesaService.pagar(despesa); return ResponseEntity.ok(despesaPaga); } @RequestMapping(method = RequestMethod.POST, value = "/search") ResponseEntity findAll(@RequestBody DespesaBuscaTO despesaBuscaTO); @RequestMapping(method = RequestMethod.GET, value = "/{id}") ResponseEntity findById(@PathVariable("id") Long id); @RequestMapping(method = RequestMethod.POST) ResponseEntity save(@RequestBody Despesa despesa); @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") ResponseEntity delete(@PathVariable("id") Long id); @RequestMapping(method = RequestMethod.PUT, value = "/pagar/{id}") ResponseEntity<Despesa> pagar(@PathVariable("id") Long id); }
@Test public void pagar() throws Exception { final Despesa despesa = Despesa.builder() .data(LocalDate.now()) .valor(BigDecimal.valueOf(70)) .descricao("Conta de Luz") .categoria(Categoria.MORARIA) .build(); given(despesaService.findById(1L)) .willReturn(despesa); given(despesaService.pagar(despesa)) .willReturn(despesa); mockMvc.perform(put("/despesas/pagar/" + 1L) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(objectMapper.writeValueAsString(despesa))); }
DespesaService { public BigDecimal findTotalPagoMesAtual() { return findTotalAPagarMesAtual(true); } List<Despesa> findAll(); Page<Despesa> findAll(DespesaBuscaTO despesaBuscaTO); @Transactional Despesa save(Despesa despesa); @Transactional void delete(Long idDespesa); Despesa findById(Long id); Map<Categoria, BigDecimal> findTotalMesAtualByCategoria(); @Transactional Despesa pagar(Despesa despesa); BigDecimal findTotalAPagarMesAtual(); BigDecimal findTotalPagoMesAtual(); List<Despesa> findProximasCincoDespesasAVencer(); List<Despesa> findDespesasAtrasadas(); Map<Boolean, BigDecimal> findTotalByPago(); }
@Test public void findTotalPagoMesAtual() { despesaService.save(Despesa.builder() .data(LocalDate.now()) .valor(BigDecimal.valueOf(70)) .descricao("Conta de Luz") .categoria(Categoria.MORARIA) .paga(false) .build()); despesaService.save(Despesa.builder() .data(LocalDate.now()) .valor(BigDecimal.TEN) .descricao("Conta de Agua") .categoria(Categoria.MORARIA) .paga(true) .build()); despesaService.save(Despesa.builder() .data(LocalDate.now()) .valor(BigDecimal.valueOf(100)) .descricao("Mercado") .categoria(Categoria.ALIMENTACAO) .paga(false) .build()); despesaService.save(Despesa.builder() .data(LocalDate.now()) .valor(BigDecimal.valueOf(135)) .descricao("Dentista") .categoria(Categoria.SAUDE) .paga(true) .build()); final BigDecimal totalPago = despesaService.findTotalPagoMesAtual(); assertEquals(BigDecimal.valueOf(145).setScale(2), totalPago); }
DespesaService { public BigDecimal findTotalAPagarMesAtual() { return findTotalAPagarMesAtual(false); } List<Despesa> findAll(); Page<Despesa> findAll(DespesaBuscaTO despesaBuscaTO); @Transactional Despesa save(Despesa despesa); @Transactional void delete(Long idDespesa); Despesa findById(Long id); Map<Categoria, BigDecimal> findTotalMesAtualByCategoria(); @Transactional Despesa pagar(Despesa despesa); BigDecimal findTotalAPagarMesAtual(); BigDecimal findTotalPagoMesAtual(); List<Despesa> findProximasCincoDespesasAVencer(); List<Despesa> findDespesasAtrasadas(); Map<Boolean, BigDecimal> findTotalByPago(); }
@Test public void findTotalAPagarMesAtual() { despesaService.save(Despesa.builder() .data(LocalDate.now()) .valor(BigDecimal.valueOf(70)) .descricao("Conta de Luz") .categoria(Categoria.MORARIA) .paga(false) .build()); despesaService.save(Despesa.builder() .data(LocalDate.now()) .valor(BigDecimal.TEN) .descricao("Conta de Agua") .categoria(Categoria.MORARIA) .paga(true) .build()); despesaService.save(Despesa.builder() .data(LocalDate.now()) .valor(BigDecimal.valueOf(100)) .descricao("Mercado") .categoria(Categoria.ALIMENTACAO) .paga(false) .build()); final BigDecimal totalAPagarMesAtual = despesaService.findTotalAPagarMesAtual(); assertEquals(BigDecimal.valueOf(170).setScale(2), totalAPagarMesAtual); }
DespesaService { @Transactional public Despesa pagar(Despesa despesa) { despesa.pagar(); return save(despesa); } List<Despesa> findAll(); Page<Despesa> findAll(DespesaBuscaTO despesaBuscaTO); @Transactional Despesa save(Despesa despesa); @Transactional void delete(Long idDespesa); Despesa findById(Long id); Map<Categoria, BigDecimal> findTotalMesAtualByCategoria(); @Transactional Despesa pagar(Despesa despesa); BigDecimal findTotalAPagarMesAtual(); BigDecimal findTotalPagoMesAtual(); List<Despesa> findProximasCincoDespesasAVencer(); List<Despesa> findDespesasAtrasadas(); Map<Boolean, BigDecimal> findTotalByPago(); }
@Test public void pagar() { Despesa despesa = Despesa.builder() .data(LocalDate.now()) .valor(BigDecimal.TEN) .descricao("Conta de Luz") .categoria(Categoria.MORARIA) .paga(false) .build(); despesaService.save(despesa); final List<Despesa> despesasAntesDePagar = despesaService.findAll(); assertEquals(1, despesasAntesDePagar.size()); assertThat(despesasAntesDePagar, contains(allOf( hasProperty("id", is(despesa.getId())), hasProperty("descricao", is("Conta de Luz")), hasProperty("paga", is(false))))); despesaService.pagar(despesa); final List<Despesa> despesasPaga = despesaService.findAll(); assertEquals(1, despesasPaga.size()); assertThat(despesasPaga, contains(allOf( hasProperty("id", is(despesa.getId())), hasProperty("descricao", is("Conta de Luz")), hasProperty("paga", is(true))))); }
CategoriaRestController { @RequestMapping(method = RequestMethod.GET) public ResponseEntity findAll() { return ResponseEntity.ok(Categoria.getCategoriasTOSortedByDescricao()); } @RequestMapping(method = RequestMethod.GET) ResponseEntity findAll(); }
@Test public void findAll() throws Exception { final List<CategoriaTO> categorias = Categoria.getCategoriasTOSortedByDescricao(); mockMvc.perform(get("/categorias") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(objectMapper.writeValueAsString(categorias))); }
StatusDespesaRestController { @RequestMapping(method = RequestMethod.GET) public ResponseEntity findAll() { return ResponseEntity.ok(StatusDespesa.getStatusTOSortedByOrdem()); } @RequestMapping(method = RequestMethod.GET) ResponseEntity findAll(); }
@Test public void findAll() throws Exception { final List<StatusDespesaTO> status = StatusDespesa.getStatusTOSortedByOrdem(); mockMvc.perform(get("/despesa/status") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(objectMapper.writeValueAsString(status))); }
DespesaRestController { @RequestMapping(method = RequestMethod.POST, value = "/search") public ResponseEntity findAll(@RequestBody DespesaBuscaTO despesaBuscaTO) { final Page<Despesa> despesas = despesaService.findAll(despesaBuscaTO); return ResponseEntity.ok(despesas); } @RequestMapping(method = RequestMethod.POST, value = "/search") ResponseEntity findAll(@RequestBody DespesaBuscaTO despesaBuscaTO); @RequestMapping(method = RequestMethod.GET, value = "/{id}") ResponseEntity findById(@PathVariable("id") Long id); @RequestMapping(method = RequestMethod.POST) ResponseEntity save(@RequestBody Despesa despesa); @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") ResponseEntity delete(@PathVariable("id") Long id); @RequestMapping(method = RequestMethod.PUT, value = "/pagar/{id}") ResponseEntity<Despesa> pagar(@PathVariable("id") Long id); }
@Test public void buscarTodos() throws Exception { final Despesa contaDeLuz = Despesa.builder() .data(LocalDate.now()) .valor(BigDecimal.valueOf(70)) .descricao("Conta de Luz") .categoria(Categoria.MORARIA) .build(); final Despesa contaDeAgua = Despesa.builder() .data(LocalDate.now()) .valor(BigDecimal.TEN) .descricao("Conta de Agua") .categoria(Categoria.MORARIA) .build(); final DespesaBuscaTO buscaTO = DespesaBuscaTO.builder() .quantidade(10) .build(); final List<Despesa> despesas = Arrays.asList(contaDeLuz, contaDeAgua); final Page<Despesa> pageDespesa = new PageImpl<>(despesas, new PageRequest(buscaTO.getPagina(), buscaTO.getQuantidade()), 2L); given(despesaService.findAll(any(DespesaBuscaTO.class))) .willReturn(pageDespesa); mockMvc.perform(post("/despesas/search") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsBytes(buscaTO)) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(objectMapper.writeValueAsString(pageDespesa))); }
DespesaRestController { @RequestMapping(method = RequestMethod.GET, value = "/{id}") public ResponseEntity findById(@PathVariable("id") Long id) { final Despesa despesa = despesaService.findById(id); return ResponseEntity.ok(despesa); } @RequestMapping(method = RequestMethod.POST, value = "/search") ResponseEntity findAll(@RequestBody DespesaBuscaTO despesaBuscaTO); @RequestMapping(method = RequestMethod.GET, value = "/{id}") ResponseEntity findById(@PathVariable("id") Long id); @RequestMapping(method = RequestMethod.POST) ResponseEntity save(@RequestBody Despesa despesa); @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") ResponseEntity delete(@PathVariable("id") Long id); @RequestMapping(method = RequestMethod.PUT, value = "/pagar/{id}") ResponseEntity<Despesa> pagar(@PathVariable("id") Long id); }
@Test public void buscarPorId() throws Exception { final Despesa despesa = Despesa.builder() .data(LocalDate.now()) .valor(BigDecimal.valueOf(70)) .descricao("Conta de Luz") .categoria(Categoria.MORARIA) .build(); given(despesaService.findById(1L)) .willReturn(despesa); mockMvc.perform(get("/despesas/" + 1L) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(objectMapper.writeValueAsString(despesa))); }
DespesaRestController { @RequestMapping(method = RequestMethod.POST) public ResponseEntity save(@RequestBody Despesa despesa) { despesaService.save(despesa); return ResponseEntity.ok().build(); } @RequestMapping(method = RequestMethod.POST, value = "/search") ResponseEntity findAll(@RequestBody DespesaBuscaTO despesaBuscaTO); @RequestMapping(method = RequestMethod.GET, value = "/{id}") ResponseEntity findById(@PathVariable("id") Long id); @RequestMapping(method = RequestMethod.POST) ResponseEntity save(@RequestBody Despesa despesa); @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") ResponseEntity delete(@PathVariable("id") Long id); @RequestMapping(method = RequestMethod.PUT, value = "/pagar/{id}") ResponseEntity<Despesa> pagar(@PathVariable("id") Long id); }
@Test public void salvar() throws Exception { final Despesa despesa = Despesa.builder() .data(LocalDate.now()) .valor(BigDecimal.valueOf(70)) .descricao("Conta de Luz") .categoria(Categoria.MORARIA) .build(); given(despesaService.save(despesa)) .willReturn(despesa); mockMvc.perform(post("/despesas") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsBytes(despesa)) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); }
HealthRecorder { public boolean isHealthy() { return healthy.get(); } boolean logStatus(Object key, boolean currentStatus); boolean isHealthy(); }
@Test public void shouldReturnHealthyWhenNoStatusIsRecorded() { HealthRecorder healthRecorder = new HealthRecorder(); assertThat(healthRecorder.isHealthy()).isTrue(); }
RxUtils { public static <T> Observable<T> singleOrEmpty(Observable<? extends Collection<T>> collectionObservable) { return collectionObservable.toList().concatMap(lists -> { if (lists.size() > 1) { return Observable.error(new IllegalArgumentException("Observable contains more than one collection.")); } else if (lists.size() == 1 && lists.get(0).size() > 1) { return Observable.error(new IllegalArgumentException( "Observable collection contains more than one item.")); } else if (lists.size() == 1 && lists.get(0).size() == 1) { return Observable.just(lists.get(0).iterator().next()); } else { return Observable.empty(); } }); } static FirstThen first(Observable<?> doFirst); static IfThenElse<T> ifTrue(Observable<Boolean> ifValue); static Observable<T1> consolidate(Observable<T1> observableLeft, Observable<T2> observableRight, Action2<T1, T2> action); static Observable<T> async(List<T> list); static Observable<T> async(Observable<T> observable); static Observable<Double> sum(Observable<Double> observable); static Observable<T> doIfEmpty(Observable<T> output, Action0 action); static Observable<T> exception(Supplier<Exception> supplier); static Observable<T> singleOrEmpty(Observable<? extends Collection<T>> collectionObservable); }
@Test(expected = NoSuchElementException.class) public void shouldAggregateExceptions() { Observable<List<Foo>> error = Observable.error(new NoSuchElementException()); RxUtils.singleOrEmpty(error).toBlocking().subscribe(); } @Test public void emptyShouldReturnEmpty() { Observable<Foo> fooObservable = RxUtils.singleOrEmpty(Observable.empty()); assertThat(fooObservable.toList().toBlocking().single()).isEmpty(); } @Test public void noItemsShouldReturnEmpty() { Observable<Foo> fooObservable = RxUtils.singleOrEmpty(just(new ArrayList<>())); assertThat(fooObservable.toList().toBlocking().single()).isEmpty(); } @Test public void oneItemShouldReturnOneItem() { List<Foo> expected = Collections.singletonList(new Foo()); Foo actual = RxUtils.singleOrEmpty(just(expected)).toBlocking().single(); assertThat(actual).isEqualTo(expected.get(0)); } @Test(expected = IllegalArgumentException.class) public void severalItemsShouldNotifyException() { List<Foo> foos = Arrays.asList(new Foo(), new Foo()); RxUtils.singleOrEmpty(just(foos)).toBlocking().subscribe(); } @Test(expected = IllegalArgumentException.class) public void severalCollectionsShouldNotifyException() { List<Foo> foos =Arrays.asList(new Foo(), new Foo()); List<Foo> fi =Arrays.asList(new Foo(), new Foo()); RxUtils.singleOrEmpty(just(foos, fi)).toBlocking().subscribe(); }
DebugUtil { static boolean isIdePresent(ClassLoader classLoader) { return classLoader.getResource("com/intellij") != null; } static final boolean IS_DEBUG; }
@Test public void testIsIdePresent() throws MalformedURLException { ClassLoader classLoaderWithIdeaDebugger = Mockito.mock(ClassLoader.class); when(classLoaderWithIdeaDebugger.getResource(eq("com/intellij"))) .thenReturn(new URL("jar:file:/path/to/debugger-agent-storage.jar!/com/intellij")); assertThat(DebugUtil.isIdePresent(classLoaderWithIdeaDebugger)).isTrue(); }
DebugUtil { static boolean isMavenDebug() { return Boolean.getBoolean("maven.surefire.debug"); } static final boolean IS_DEBUG; }
@Test public void testIsMavenDebug() { String debugPropName = "maven.surefire.debug"; boolean originalSurefireDebugProp = Boolean.getBoolean(debugPropName); System.setProperty(debugPropName, "true"); assertThat(DebugUtil.isMavenDebug()).isTrue(); System.setProperty(debugPropName, String.valueOf(originalSurefireDebugProp)); }
FieldSetter implements Setter<I,T> { @Override public void invoke(I instance, T value) throws IllegalAccessException { field.set(instance, value); } private FieldSetter(Field field, Class<T> parameterType, Type genericParameterType); static Setter<I,T> create(Class<I> cls, Field field); @Override void invoke(I instance, T value); @Override Class<?> getParameterType(); @Override Type getGenericParameterType(); @Override BiConsumer<I,T> setterFunction(); }
@Test public void shouldSetFinalField() throws Exception { GenericFieldSubclass foo = new GenericFieldSubclass(1); value.invoke(foo, 9); assertThat(foo.value).isEqualTo(9); genericSuperKey.invoke(foo, "9"); assertThat(foo.superKey).isEqualTo("9"); genericSuperValue.invoke(foo, 9); assertThat(foo.superValue).isEqualTo(9); FieldSubclass bar = new FieldSubclass(1); superKey.invoke(bar, "9"); assertThat(bar.superKey).isEqualTo("9"); superValue.invoke(bar, 9); assertThat(bar.superValue).isEqualTo(9); }
FieldSetter implements Setter<I,T> { @Override public BiConsumer<I,T> setterFunction() { return setter; } private FieldSetter(Field field, Class<T> parameterType, Type genericParameterType); static Setter<I,T> create(Class<I> cls, Field field); @Override void invoke(I instance, T value); @Override Class<?> getParameterType(); @Override Type getGenericParameterType(); @Override BiConsumer<I,T> setterFunction(); }
@Test public void shouldSupportSetterLambda() { GenericFieldSubclass foo = new GenericFieldSubclass(1); BiConsumer<GenericFieldSubclass, Integer> setter = value.setterFunction(); setter.accept(foo, 9); assertThat(foo.value).isEqualTo(9); }
FieldSetter implements Setter<I,T> { @Override public Class<?> getParameterType() { return parameterType; } private FieldSetter(Field field, Class<T> parameterType, Type genericParameterType); static Setter<I,T> create(Class<I> cls, Field field); @Override void invoke(I instance, T value); @Override Class<?> getParameterType(); @Override Type getGenericParameterType(); @Override BiConsumer<I,T> setterFunction(); }
@Test public void shouldGetParameterType() { assertThat(value.getParameterType()).isEqualTo(Integer.class); assertThat(genericSuperKey.getParameterType()).isEqualTo(String.class); assertThat(genericSuperValue.getParameterType()).isEqualTo(Integer.class); assertThat(superKey.getParameterType()).isEqualTo(String.class); assertThat(superValue.getParameterType()).isEqualTo(Integer.class); }
FieldSetter implements Setter<I,T> { @Override public Type getGenericParameterType() { return genericParameterType; } private FieldSetter(Field field, Class<T> parameterType, Type genericParameterType); static Setter<I,T> create(Class<I> cls, Field field); @Override void invoke(I instance, T value); @Override Class<?> getParameterType(); @Override Type getGenericParameterType(); @Override BiConsumer<I,T> setterFunction(); }
@Test public void shouldGetGenericParameterType() { assertThat(longObservable.getGenericParameterType().toString()).isEqualTo("rx.Observable<java.lang.Long>"); assertThat(genericSuperKey.getGenericParameterType().toString()).isEqualTo("class java.lang.String"); assertThat(genericSuperValue.getGenericParameterType().toString()).isEqualTo("class java.lang.Integer"); assertThat(superKey.getGenericParameterType().toString()).isEqualTo("class java.lang.String"); assertThat(superValue.getGenericParameterType().toString()).isEqualTo("class java.lang.Integer"); }
PropertyResolver { @Override public String toString() { return Arrays.toString(properties); } private PropertyResolver(Class<?> type, Type genericType, Property[] properties); static Optional<PropertyResolver> from(Type type, String[] propertyNames); Class<?> getPropertyType(); Type getPropertyGenericType(); Optional<PropertyResolver> subPath(String[] subPath); @Override String toString(); Function<I,T> getter(); BiConsumer<I,T> setter(); }
@Test public void testToString() { PropertyResolver.from(Mutable.class, new String[]{"anInt"}).get().toString(); }
MethodGetter implements Getter<I,T> { @Override public T invoke(I instance) { return getterLambda.apply(instance); } private MethodGetter(Method method, Class<T> returnType, Type genericReturnType); static Getter create(Class<?> cls, Method method); @Override T invoke(I instance); @Override Class<?> getReturnType(); @Override Type getGenericReturnType(); @Override Function<I, T> getterFunction(); }
@Test public void shouldGetValue() throws Exception { assertThat(value.invoke(new GenericMethodSubclass(5))).isEqualTo(5); assertThat(genericSuperKey.invoke(new GenericMethodSubclass(5))).isEqualTo("5"); assertThat(genericSuperValue.invoke(new GenericMethodSubclass(5))).isEqualTo(5); assertThat(superKey.invoke(new MethodSubclass("1", 2))).isEqualTo("1"); assertThat(superValue.invoke(new MethodSubclass("1", 2))).isEqualTo(2); }
MethodGetter implements Getter<I,T> { @Override public Class<?> getReturnType() { return returnType; } private MethodGetter(Method method, Class<T> returnType, Type genericReturnType); static Getter create(Class<?> cls, Method method); @Override T invoke(I instance); @Override Class<?> getReturnType(); @Override Type getGenericReturnType(); @Override Function<I, T> getterFunction(); }
@Test public void shouldGetReturnType() { assertThat(value.getReturnType()).isEqualTo(Integer.class); assertThat(genericSuperKey.getReturnType()).isEqualTo(String.class); assertThat(genericSuperValue.getReturnType()).isEqualTo(Integer.class); assertThat(superKey.getReturnType()).isEqualTo(String.class); assertThat(superValue.getReturnType()).isEqualTo(Integer.class); }
JsonDeserializerFactory { public <T> Function<String, T> createDeserializer(TypeReference<T> typeReference) { return createDeserializer(mapper.readerFor(typeReference)); } @Inject JsonDeserializerFactory(ObjectMapper mapper); JsonDeserializerFactory(); Function<String, T> createDeserializer(TypeReference<T> typeReference); Function<String, T> createDeserializer(Type type); Function<String, T> createDeserializer(Class<T> paramType); Function<byte[], T> createByteDeserializer(TypeReference<T> typeReference); Function<byte[], T> createByteDeserializer(Class<T> paramType); }
@Test public void shouldSerializeAndDeserializeImmutableObjectsByTypeReferenceToAndFromByteArrays() { Function<ImmutableEntity, String> serializer = serializerFactory.createStringSerializer(immutableEntityTypeReference); String json = serializer.apply(immutableEntity); Function<String, ImmutableEntity> deserializer = deserializerFactory.createDeserializer(immutableEntityTypeReference); ImmutableEntity result = deserializer.apply(json); assertThat(result).isEqualTo(immutableEntity); } @Test public void shouldSerializeAndDeserializeImmutableObjects() { Function<ImmutableEntity, String> serializer = serializerFactory.createStringSerializer(ImmutableEntity.class); String json = serializer.apply(immutableEntity); Function<String, ImmutableEntity> deserializer = deserializerFactory.createDeserializer(ImmutableEntity.class); ImmutableEntity result = deserializer.apply(json); assertThat(result).isEqualTo(immutableEntity); } @Test public void shouldSerializeAndDeserializeMutableObjects() { Function<MutableEntity, String> serializer = serializerFactory.createStringSerializer(MutableEntity.class); String json = serializer.apply(mutableEntity); Function<String, MutableEntity> deserializer = deserializerFactory.createDeserializer(MutableEntity.class); MutableEntity result = deserializer.apply(json); assertThat(result).isEqualTo(mutableEntity); } @Test public void shouldSerializeAndDeserializeJdk8Types() { Function<Jdk8Types, String> serializer = serializerFactory.createStringSerializer(Jdk8Types.class); String json = serializer.apply(jdk8Types); Function<String, Jdk8Types> deserializer = deserializerFactory.createDeserializer(Jdk8Types.class); Jdk8Types result = deserializer.apply(json); assertThat(result).isEqualTo(jdk8Types); } @Test public void shouldDeserializeFromType() throws NoSuchMethodException { Method method = this.getClass().getDeclaredMethod("methodReturningListOfString"); Type type = method.getGenericReturnType(); Function<String, List<String>> serializeList = deserializerFactory.createDeserializer(type); List<String> result = serializeList.apply("[\"a\",\"b\"]"); assertThat(result).hasSize(2); assertThat(result.get(0)).isEqualTo("a"); assertThat(result.get(1)).isEqualTo("b"); } @Test public void shouldThrowInvalidJsonException() { Function<String, ImmutableEntity> deserializer = deserializerFactory.createDeserializer(ImmutableEntity.class); try { deserializer.apply("not real json"); fail("Expected exception, but none was thrown"); } catch(Exception actualException) { assertThat(actualException).isInstanceOf(InvalidJsonException.class); assertThat(actualException.getMessage()).contains("Unrecognized token"); } } @Test public void shouldDeserializeNullToNull() { Function<String, ImmutableEntity> deserializer = deserializerFactory.createDeserializer(ImmutableEntity.class); ImmutableEntity result = deserializer.apply(null); assertThat(result).isNull(); }
MethodGetter implements Getter<I,T> { @Override public Type getGenericReturnType() { return genericReturnType; } private MethodGetter(Method method, Class<T> returnType, Type genericReturnType); static Getter create(Class<?> cls, Method method); @Override T invoke(I instance); @Override Class<?> getReturnType(); @Override Type getGenericReturnType(); @Override Function<I, T> getterFunction(); }
@Test public void shouldGetGenericReturnType() { assertThat(longObservable.getGenericReturnType().toString()).isEqualTo("rx.Observable<java.lang.Long>"); assertThat(genericSuperKey.getGenericReturnType().toString()).isEqualTo("class java.lang.String"); assertThat(genericSuperValue.getGenericReturnType().toString()).isEqualTo("class java.lang.Integer"); assertThat(superKey.getGenericReturnType().toString()).isEqualTo("class java.lang.String"); assertThat(superValue.getGenericReturnType().toString()).isEqualTo("class java.lang.Integer"); }
CompoundKey { @Override public int hashCode() { final int prime = 31; int result = 1; for (Object k : keys) { result = result * prime + (k == null ? 0 : k.hashCode()); } return result; } CompoundKey(Object... keys); @Override int hashCode(); @Override boolean equals(Object obj); }
@Test public void shouldBeComparableWhenSame() { CompoundKey key1 = new CompoundKey("one", "two", "three"); CompoundKey key2 = new CompoundKey("one", "two", "three"); assertThat(key1).isEqualTo(key2); assertThat(key1.hashCode()).isEqualTo(key2.hashCode()); } @Test public void shouldBeComparableWhenDifferent() { CompoundKey key1 = new CompoundKey("one", "two", "three"); CompoundKey key2 = new CompoundKey("one", "two", "four"); assertThat(key1).isNotEqualTo(key2); assertThat(key1.hashCode()).isNotEqualTo(key2.hashCode()); } @Test public void shouldCompareKeysWithDifferentLength() { CompoundKey key1 = new CompoundKey("one", "two", "three"); CompoundKey key2 = new CompoundKey("one", "two"); assertThat(key1).isNotEqualTo(key2); assertThat(key1.hashCode()).isNotEqualTo(key2.hashCode()); } @Test public void shouldCompareNullValues() { CompoundKey key1 = new CompoundKey(null, null); CompoundKey key2 = new CompoundKey(null, null, null); assertThat(key1).isNotEqualTo(key2); assertThat(key1.hashCode()).isNotEqualTo(key2.hashCode()); }
CamelSnakeConverter { public static String snakeToCamel(String snakeString) { String lowerCaseSnakeString = snakeString.toLowerCase(); StringBuilder camel = new StringBuilder(); boolean nextUpper = false; for (char c : lowerCaseSnakeString.toCharArray()) { if (c == '_') { nextUpper = true; } else if (nextUpper) { camel.append(Character.toUpperCase(c)); nextUpper = false; } else { camel.append(c); } } return camel.toString(); } static String camelToSnake(String camelString); static String snakeToCamel(String snakeString); }
@Test public void shouldConvertToCamelCase() { assertThat(CamelSnakeConverter.snakeToCamel("AAA")).isEqualTo("aaa"); assertThat(CamelSnakeConverter.snakeToCamel("AAA_AAA_AAA")).isEqualTo("aaaAaaAaa"); assertThat(CamelSnakeConverter.snakeToCamel("a_a")).isEqualTo("aA"); assertThat(CamelSnakeConverter.snakeToCamel("aa")).isEqualTo("aa"); assertThat(CamelSnakeConverter.snakeToCamel("A")).isEqualTo("a"); assertThat(CamelSnakeConverter.snakeToCamel("a")).isEqualTo("a"); assertThat(CamelSnakeConverter.snakeToCamel("a_Ab_aA_a")).isEqualTo("aAbAaA"); assertThat(CamelSnakeConverter.snakeToCamel("")).isEqualTo(""); }
CamelSnakeConverter { public static String camelToSnake(String camelString) { return camelRegex.matcher(camelString).replaceAll(snakeReplacement).toLowerCase(); } static String camelToSnake(String camelString); static String snakeToCamel(String snakeString); }
@Test public void shouldConvertToSnake() { assertThat(CamelSnakeConverter.camelToSnake("AAA")).isEqualTo("aaa"); assertThat(CamelSnakeConverter.camelToSnake("aaaAaaAaa")).isEqualTo("aaa_aaa_aaa"); assertThat(CamelSnakeConverter.camelToSnake("aA")).isEqualTo("a_a"); assertThat(CamelSnakeConverter.camelToSnake("aa")).isEqualTo("aa"); assertThat(CamelSnakeConverter.camelToSnake("A")).isEqualTo("a"); assertThat(CamelSnakeConverter.camelToSnake("a")).isEqualTo("a"); assertThat(CamelSnakeConverter.camelToSnake("aAbAaA")).isEqualTo("a_ab_aa_a"); assertThat(CamelSnakeConverter.camelToSnake("")).isEqualTo(""); }
ObservableStatementFactory { public Observable<Object> create(Object[] args, ConnectionProvider connectionProvider) { AtomicReference<TransactionStatement> transactionHolder = new AtomicReference<>(); Observable<Object> result = Observable.unsafeCreate(subscription -> { try { Statement dbStatement = statementFactory.create(args, subscription); TransactionStatement transactionStatement = transactionHolder.get(); if (transactionStatement != null) { Transaction transaction = transactionStatement.getTransaction(); transaction.setConnectionProvider(connectionProvider); transactionStatement.markStatementSubscribed(dbStatement); if (transaction.isAllSubscribed()) { scheduleWorker(subscription, transaction::execute); } } else { scheduleWorker(subscription, () -> executeStatement(dbStatement, connectionProvider)); } } catch (Exception e) { if (!subscription.isUnsubscribed()) { subscription.onError(e); } } }); if (DebugUtil.IS_DEBUG || LOG.isDebugEnabled()) { Exception queryFailure = new RuntimeException("Query failed"); result = result.onErrorResumeNext(thrown -> { queryFailure.initCause(thrown); return error(queryFailure); }); } result = pagingOutput.apply(result, args); result = metrics.measure(result, time -> logSlowQuery(transactionHolder.get(), time, args)); result = result.onBackpressureBuffer(RECORD_BUFFER_SIZE); return new DaoObservable<>(result, transactionHolder); } ObservableStatementFactory( DbStatementFactory statementFactory, PagingOutput pagingOutput, Scheduler scheduler, Function<Object[], String> paramSerializer, Metrics metrics, DatabaseConfig config ); Observable<Object> create(Object[] args, ConnectionProvider connectionProvider); }
@Test public void shouldReleaseSchedulerWorkers() { Observable<Object> stmt = statementFactory.create(new Object[0], mockDb.getConnectionProvider()); stmt.toBlocking().single(); verify(scheduler, times(1)).createWorker(); verify(worker).unsubscribe(); }
ParamQueryPart implements DynamicQueryPart { @Override public DynamicQueryPart subPath(String[] subPath) throws SQLException { Optional<PropertyResolver> propertyResolver = argResolver.subPath(subPath); if (!propertyResolver.isPresent()) { throw new RuntimeException(String.format("Properties %s cannot be found in %s", Arrays.toString(subPath), argResolver.getPropertyType())); } return new ParamQueryPart(argIndex, propertyResolver.get()); } ParamQueryPart(int argIndex, Type cls); protected ParamQueryPart(ParamQueryPart paramQueryPart); protected ParamQueryPart(int argIndex, PropertyResolver argResolver); @Override void visit(StringBuilder sql, Object[] args); @Override void addParams(PreparedStatementParameters parameters, Object[] args); @Override DynamicQueryPart subPath(String[] subPath); }
@Test public void shouldIncludePropertiesAndTypeOnSubPathError() throws SQLException { ParamQueryPart paramQueryPart = new ParamQueryPart(0, ReflectionUtil.getPropertyResolver(Foo.class).orElseThrow(IllegalArgumentException::new)); try { paramQueryPart.subPath(new String[] { "bar", "zap" }); fail(); } catch (RuntimeException e) { assertThat(e.getMessage()).isEqualTo(String.format("Properties [bar, zap] cannot be found in class %s", Foo.class.getName())); } }
MutabilityDetector { static boolean isImmutable(Class<?> cls) { return !hasSetterMethod(cls) && !hasNoArgConstructor(cls) && !hasNonFinalField(cls); } }
@Test public void testIsImmutable() { assertThat(MutabilityDetector.isImmutable(Immutable.class)).isTrue(); assertThat(MutabilityDetector.isImmutable(Mutable.class)).isFalse(); } @Test public void shouldIgnoreSyntheticMembers() throws Exception { Class<?> withSynthetic = createClassWithSyntheticMembers(); assertThat(MutabilityDetector.isImmutable(withSynthetic)).isTrue(); }
JsonDeserializerFactory { public <T> Function<byte[], T> createByteDeserializer(TypeReference<T> typeReference) { return createByteDeserializer(mapper.readerFor(typeReference)); } @Inject JsonDeserializerFactory(ObjectMapper mapper); JsonDeserializerFactory(); Function<String, T> createDeserializer(TypeReference<T> typeReference); Function<String, T> createDeserializer(Type type); Function<String, T> createDeserializer(Class<T> paramType); Function<byte[], T> createByteDeserializer(TypeReference<T> typeReference); Function<byte[], T> createByteDeserializer(Class<T> paramType); }
@Test public void shouldSerializeAndDeserializeToAndFromByteArrays() { Function<ImmutableEntity, byte[]> serializer = serializerFactory.createByteSerializer(ImmutableEntity.class); byte[] json = serializer.apply(immutableEntity); Function<byte[], ImmutableEntity> deserializer = deserializerFactory.createByteDeserializer(ImmutableEntity.class); ImmutableEntity result = deserializer.apply(json); assertThat(result).isEqualTo(immutableEntity); } @Test public void shouldThrowInvalidJsonExceptionUsingByteArayDeserializer() { Function<byte[], ImmutableEntity> deserializer = deserializerFactory.createByteDeserializer(ImmutableEntity.class); try { deserializer.apply("not real json".getBytes()); fail("Expected exception, but none was thrown"); } catch(Exception actualException) { assertThat(actualException).isInstanceOf(InvalidJsonException.class); assertThat(actualException.getMessage()).contains("Unrecognized token"); } } @Test public void shouldDeserializeByteArrayNullToNull() { Function<byte[], ImmutableEntity> deserializer = deserializerFactory.createByteDeserializer(ImmutableEntity.class); ImmutableEntity result = deserializer.apply(null); assertThat(result).isNull(); } @Test public void shouldSerializeAndDeserializeImmutableObjectsByTypeReference() { Function<ImmutableEntity, byte[]> serializer = serializerFactory.createByteSerializer(immutableEntityTypeReference); byte[] json = serializer.apply(immutableEntity); Function<byte[], ImmutableEntity> deserializer = deserializerFactory.createByteDeserializer(immutableEntityTypeReference); ImmutableEntity result = deserializer.apply(json); assertThat(result).isEqualTo(immutableEntity); }
DeserializerUtil { static <I,T> Map<String[], T> createPropertyDeserializers(Class<I> cls, ResultSetMetaData metaData, BiFunction<PropertyResolver<I,?>, Deserializer, T> deserializerFactory ) throws SQLException { Map<String[], T> propertyDeserializers = new LinkedHashMap<>(); String[] columns = extractColumnLabels(metaData); for (int i = 0; i < columns.length; i++) { String column = columns[i]; String propertyName = CamelSnakeConverter.snakeToCamel(column); String[] propertyPath = propertyName.split("\\."); Optional<PropertyResolver> propertyResolver = ReflectionUtil.getPropertyResolver(cls, propertyPath); if (propertyResolver.isPresent()) { T propertyDeserializer = createPropertyDeserializer((PropertyResolver<I, ?>) propertyResolver.get(), metaData, i + 1, deserializerFactory); propertyDeserializers.put(propertyPath, propertyDeserializer); } else { LOG.warn("Tried to deserialize column " + column + ", but found no matching property named " + propertyName + " in " + cls.getSimpleName()); } } return Collections.unmodifiableMap(propertyDeserializers); } }
@Test public void shouldLogWarnIfNoPropertyDeserializerWasFound() throws SQLException, NoSuchFieldException, IllegalAccessException { SimpleResultSet resultSet = new SimpleResultSet(); resultSet.addColumn("test_a", Types.VARCHAR, 255, 0); Appender mockAppender = createMockedLogAppender(DeserializerUtil.class); DeserializerUtil.createPropertyDeserializers(ClassWithoutPropertyA.class, resultSet, (propertyResolver, deserializer) -> deserializer); verify(mockAppender).doAppend(matches(log -> { assertThat(log.getLevel().toString()).isEqualTo("WARN"); assertThat(log.getMessage().toString()) .matches("Tried to deserialize column test_a, but found no matching property named testA in ClassWithoutPropertyA"); })); destroyMockedAppender(mockAppender, DeserializerUtil.class); } @Test public void shouldNotWarnForFoundProperties() throws SQLException, NoSuchFieldException, IllegalAccessException { SimpleResultSet resultSet = new SimpleResultSet(); resultSet.addColumn("test_b", Types.VARCHAR, 255, 0); Appender mockAppender = createMockedLogAppender(DeserializerUtil.class); DeserializerUtil.createPropertyDeserializers(ClassWithoutPropertyA.class, resultSet, (propertyResolver, deserializer) -> deserializer); verify(mockAppender, never()).doAppend(any()); destroyMockedAppender(mockAppender, DeserializerUtil.class); }
DaoClassScanner extends AbstractClassScanner { @Override public void visit(ClassScanner classScanner) { classScanner.findClassesWithMethodAnnotation(Query.class).forEach(this::addIfInterface); classScanner.findClassesWithMethodAnnotation(Update.class).forEach(this::addIfInterface); } @Override void visit(ClassScanner classScanner); }
@Test public void testDaoClassScanner() { ClassGraph classGraph = new ClassGraph() .whitelistPackages("se.fortnox.reactivewizard.binding.scanners") .enableAnnotationInfo() .enableMethodInfo() .enableAllInfo(); DaoClassScanner daoClassScanner = new DaoClassScanner(); try (ScanResult scanResult = classGraph.scan()) { daoClassScanner.visit(new ClassScannerImpl(scanResult)); } Set<Class<?>> classes = daoClassScanner.getClasses(); assertThat(classes).hasSize(2); classes.forEach(cls -> assertThat(cls.isInterface()).isTrue()); Set<Class<?>> otherClasses = classes.stream() .filter(cls -> { String name = cls.getName(); return !name.contains("QueryDao") && !name.contains("UpdateDao"); }) .collect(Collectors.toSet()); assertThat(otherClasses).isEmpty(); }
LiquibaseMigrateProvider { LiquibaseMigrate get() { if (liquibaseMigrate == null) { try { liquibaseMigrate = new LiquibaseMigrate(liquibaseConfig); } catch (LiquibaseException | IOException e) { throw new IllegalStateException(e); } } return liquibaseMigrate; } @Inject LiquibaseMigrateProvider(ConfigFactory configFactory); }
@Test public void shouldGetLiquibaseMigrateInstance() { LiquibaseConfig liquibaseConfig = mock(LiquibaseConfig.class); when(liquibaseConfig.getUrl()).thenReturn("jdbc:h2:mem:test"); when(liquibaseConfig.getMigrationsFile()).thenReturn("migrations.xml"); ConfigFactory configFactory = mock(ConfigFactory.class); when(configFactory.get(LiquibaseConfig.class)).thenReturn(liquibaseConfig); LiquibaseMigrateProvider liquibaseMigrateProvider = new LiquibaseMigrateProvider(configFactory); verify(liquibaseConfig, never()).getUrl(); LiquibaseMigrate liquibaseMigrate = liquibaseMigrateProvider.get(); verify(liquibaseConfig, atLeastOnce()).getUrl(); }
WebException extends RuntimeException { public String getId() { return id; } WebException(HttpResponseStatus httpStatus, Throwable throwable, boolean stacktrace); WebException(HttpResponseStatus httpStatus, String errorCode, Throwable throwable); WebException(HttpResponseStatus httpStatus); WebException(HttpResponseStatus httpStatus, Throwable throwable); WebException(HttpResponseStatus httpStatus, FieldError... fieldErrors); WebException(FieldError... fieldErrors); WebException(HttpResponseStatus httpStatus, String errorCode, String userMessage); WebException(HttpResponseStatus httpStatus, String errorCode); @JsonIgnore HttpResponseStatus getStatus(); WebException withErrorParams(Object... params); String getId(); String getError(); @JsonInclude(Include.NON_NULL) FieldError[] getFields(); @Override @JsonInclude(Include.NON_NULL) String getMessage(); @JsonInclude(Include.NON_NULL) Object[] getErrorParams(); void setErrorParams(Object[] errorParams); Level getLogLevel(); void setLogLevel(Level logLevel); WebException withLogLevel(Level logLevel); }
@Test public void shouldGetIdWhenIntializedWithStatus() { WebException webException = new WebException(BAD_GATEWAY); assertUuid(webException.getId()); } @Test public void shouldGetIdWhenInitializedWithFieldError() { WebException webException = new WebException(new FieldError[0]); assertUuid(webException.getId()); }
WebException extends RuntimeException { public Level getLogLevel() { return logLevel; } WebException(HttpResponseStatus httpStatus, Throwable throwable, boolean stacktrace); WebException(HttpResponseStatus httpStatus, String errorCode, Throwable throwable); WebException(HttpResponseStatus httpStatus); WebException(HttpResponseStatus httpStatus, Throwable throwable); WebException(HttpResponseStatus httpStatus, FieldError... fieldErrors); WebException(FieldError... fieldErrors); WebException(HttpResponseStatus httpStatus, String errorCode, String userMessage); WebException(HttpResponseStatus httpStatus, String errorCode); @JsonIgnore HttpResponseStatus getStatus(); WebException withErrorParams(Object... params); String getId(); String getError(); @JsonInclude(Include.NON_NULL) FieldError[] getFields(); @Override @JsonInclude(Include.NON_NULL) String getMessage(); @JsonInclude(Include.NON_NULL) Object[] getErrorParams(); void setErrorParams(Object[] errorParams); Level getLogLevel(); void setLogLevel(Level logLevel); WebException withLogLevel(Level logLevel); }
@Test public void shouldSetDebugLoggingFor404() { WebException webException = new WebException(NOT_FOUND); assertThat(webException.getLogLevel()).isEqualTo(DEBUG); } @Test public void shouldSetWarnLoggingForAnythingElse() { WebException webException = new WebException(CONTINUE); assertThat(webException.getLogLevel()).isEqualTo(WARN); }
WebException extends RuntimeException { public String getError() { return error; } WebException(HttpResponseStatus httpStatus, Throwable throwable, boolean stacktrace); WebException(HttpResponseStatus httpStatus, String errorCode, Throwable throwable); WebException(HttpResponseStatus httpStatus); WebException(HttpResponseStatus httpStatus, Throwable throwable); WebException(HttpResponseStatus httpStatus, FieldError... fieldErrors); WebException(FieldError... fieldErrors); WebException(HttpResponseStatus httpStatus, String errorCode, String userMessage); WebException(HttpResponseStatus httpStatus, String errorCode); @JsonIgnore HttpResponseStatus getStatus(); WebException withErrorParams(Object... params); String getId(); String getError(); @JsonInclude(Include.NON_NULL) FieldError[] getFields(); @Override @JsonInclude(Include.NON_NULL) String getMessage(); @JsonInclude(Include.NON_NULL) Object[] getErrorParams(); void setErrorParams(Object[] errorParams); Level getLogLevel(); void setLogLevel(Level logLevel); WebException withLogLevel(Level logLevel); }
@Test public void shouldSetErrorCode() { WebException webException = new WebException(NOT_FOUND, "entry.not.found"); assertThat(webException.getError()).isEqualTo("entry.not.found"); } @Test public void shouldSetErrorCodeToInternalWhenStatusIs500() { WebException webException = new WebException(INTERNAL_SERVER_ERROR); assertThat(webException.getError()).isEqualTo("internal"); } @Test public void shouldNotSetErrorCodeToInternalWhenStatusIs500IfErrorCodeWasPassed() { WebException webException = new WebException(INTERNAL_SERVER_ERROR, "anything"); assertThat(webException.getError()).isEqualTo("anything"); } @Test public void shouldSetErrorFromStatusWhenFieldErrorsAreEmpty() { WebException webException = new WebException(BAD_REQUEST, new FieldError[0]); assertThat(webException.getError()).isEqualTo("badrequest"); } @Test public void shouldSetErrorToGivenValueWhenErrorCodeAndThrowableIsGiven() { WebException webException = new WebException(BAD_REQUEST, "error_code",new IllegalArgumentException("cause")); assertThat(webException.getError()).isEqualTo("error_code"); assertThat(webException.getCause()).isInstanceOf(IllegalArgumentException.class); }
WebException extends RuntimeException { @JsonIgnore public HttpResponseStatus getStatus() { return status; } WebException(HttpResponseStatus httpStatus, Throwable throwable, boolean stacktrace); WebException(HttpResponseStatus httpStatus, String errorCode, Throwable throwable); WebException(HttpResponseStatus httpStatus); WebException(HttpResponseStatus httpStatus, Throwable throwable); WebException(HttpResponseStatus httpStatus, FieldError... fieldErrors); WebException(FieldError... fieldErrors); WebException(HttpResponseStatus httpStatus, String errorCode, String userMessage); WebException(HttpResponseStatus httpStatus, String errorCode); @JsonIgnore HttpResponseStatus getStatus(); WebException withErrorParams(Object... params); String getId(); String getError(); @JsonInclude(Include.NON_NULL) FieldError[] getFields(); @Override @JsonInclude(Include.NON_NULL) String getMessage(); @JsonInclude(Include.NON_NULL) Object[] getErrorParams(); void setErrorParams(Object[] errorParams); Level getLogLevel(); void setLogLevel(Level logLevel); WebException withLogLevel(Level logLevel); }
@Test public void shouldSetBadRequestWhenInitializedWithFieldErrors() { WebException webException = new WebException(FieldError.notNull("dummy")); assertThat(webException.getStatus()).isEqualTo(BAD_REQUEST); } @Test public void shouldUsePassedStatusWhenInitializedWithFieldErrorsAndStatus() { WebException webException = new WebException(METHOD_NOT_ALLOWED, FieldError.notNull("dummy")); assertThat(webException.getStatus()).isEqualTo(METHOD_NOT_ALLOWED); }
HttpClientProvider { public HttpClient createClient(HttpClientConfig httpClientConfig) { return instantiateClient(httpClientConfig, getRxClientProvider(httpClientConfig)); } @Inject HttpClientProvider(ObjectMapper objectMapper, RequestParameterSerializers requestParameterSerializers, Set<PreRequestHook> preRequestHooks, HealthRecorder healthRecorder ); HttpClient createClient(HttpClientConfig httpClientConfig); }
@Test public void shouldCreateInstanceOfHttpClient() throws URISyntaxException { Injector injector = TestInjector.create(binder -> { binder.bind(ServerConfig.class).toInstance(new ServerConfig(){{ setEnabled(false); }}); }); HttpClientProvider provider = injector.getInstance(HttpClientProvider.class); HttpClientConfig httpClientConfig = new HttpClientConfig("localhost:8080"); HttpClient client = provider.createClient(httpClientConfig); assertThat(client).isNotNull(); assertThat(client).isInstanceOf(HttpClient.class); }
RequestParameterSerializers { public RequestParameterSerializer<?> getSerializer(Class<?> type) { return serializers.get(type); } @Inject RequestParameterSerializers(Set<RequestParameterSerializer> requestParameterSerializers); RequestParameterSerializers(); RequestParameterSerializer<?> getSerializer(Class<?> type); }
@Test public void shouldProvideSerializerByClass() { assertThat(serializers.getSerializer(Foo.class)).isInstanceOf(Foo.class); assertThat(serializers.getSerializer(Bar.class)).isInstanceOf(Bar.class); }
HttpClient implements InvocationHandler { @SuppressWarnings("unchecked") public <T> T create(Class<T> jaxRsInterface) { return (T)Proxy.newProxyInstance(jaxRsInterface.getClassLoader(), new Class[]{jaxRsInterface}, this); } @Inject HttpClient(HttpClientConfig config, ReactorRxClientProvider clientProvider, ObjectMapper objectMapper, RequestParameterSerializers requestParameterSerializers, Set<PreRequestHook> preRequestHooks ); HttpClient(HttpClientConfig config); static void setTimeout(Object proxy, int timeout, ChronoUnit timeoutUnit); void setTimeout(int timeout, ChronoUnit timeoutUnit); @SuppressWarnings("unchecked") T create(Class<T> jaxRsInterface); @Override Object invoke(Object proxy, Method method, Object[] arguments); static Observable<Response<T>> getFullResponse(Observable<T> source); static Single<Response<T>> getFullResponse(Single<T> source); static final String COOKIE; }
@Test public void shouldReportUnhealthyWhenConnectionCannotBeAquiredBeforeTimeout() throws URISyntaxException { DisposableServer server = HttpServer.create().port(0) .handle((request, response) -> Flux.defer(() -> { response.status(HttpResponseStatus.OK); return Flux.<Void>empty(); }).delaySubscription(Duration.ofMillis(1000))) .bindNow(); HttpClientConfig httpClientConfig = new HttpClientConfig(); httpClientConfig.setUrl("http: httpClientConfig.setPoolAcquireTimeoutMs(100); httpClientConfig.setMaxConnections(1); ReactorRxClientProvider reactorRxClientProvider = new ReactorRxClientProvider(httpClientConfig, healthRecorder); HttpClient reactorHttpClient = new HttpClient(httpClientConfig, reactorRxClientProvider, new ObjectMapper(), new RequestParameterSerializers(), Collections.EMPTY_SET); TestResource testResource = reactorHttpClient.create(TestResource.class); Observable<String> hello = testResource.getHello(); Observable<String> hello2 = testResource.getHello(); Observable .merge(hello, hello2).test().awaitTerminalEvent(); assertThat(healthRecorder.isHealthy()).isFalse(); } @Test public void shouldHandleMultipleChunks() { DisposableServer server = HttpServer.create().port(0).handle((request, response) -> { response.status(HttpResponseStatus.OK); return response.sendString(just("\"he") .concatWith(defer(() -> just("llo\""))) .concatWith(defer(Flux::empty))); }).bindNow(); TestResource resource = getHttpProxy(server.port()); String result = resource.getHello().toBlocking().single(); assertThat(result).isEqualTo("hello"); server.disposeNow(); } @Test public void shouldSendFormParamsAsBodyWithCorrectContentType() { AtomicReference<HttpServerRequest> recordedRequest = new AtomicReference<>(); AtomicReference<String> recordedRequestBody = new AtomicReference<>(); DisposableServer server = HttpServer.create().port(0).handle((request, response) -> { recordedRequest.set(request); response.status(HttpResponseStatus.CREATED); return request.receive().flatMap(buf -> { recordedRequestBody.set(buf.toString(Charset.defaultCharset())); return Flux.empty(); }); }).bindNow(); TestResource resource = getHttpProxy(server.port()); resource.postForm("A", "b!\"#¤%/=&", null, null).toBlocking().singleOrDefault(null); assertThat(recordedRequest.get().requestHeaders().get("Content-Type")).isEqualTo(MediaType.APPLICATION_FORM_URLENCODED); assertThat(recordedRequestBody.get()).isEqualTo("paramA=A&paramB=b%21%22%23%C2%A4%25%2F%3D%26"); server.disposeNow(); } @Test public void shouldNotSendHeaderParamsAsPostBody() { AtomicReference<HttpServerRequest> recordedRequest = new AtomicReference<>(); AtomicReference<String> recordedRequestBody = new AtomicReference<>(); DisposableServer server = HttpServer.create().port(0).handle((request, response) -> { recordedRequest.set(request); response.status(HttpResponseStatus.CREATED); return request.receive().flatMap(buf -> { recordedRequestBody.set(buf.toString(Charset.defaultCharset())); return Flux.empty(); }); }).bindNow(); TestResource resource = getHttpProxy(server.port()); resource.postForm("A", "b!\"#¤%/=&", "123", "cookie_val").toBlocking().singleOrDefault(null); assertThat(recordedRequest.get().requestHeaders().get("Content-Type")).isEqualTo(MediaType.APPLICATION_FORM_URLENCODED); assertThat(recordedRequest.get().requestHeaders().get("myheader")).isEqualTo("123"); assertThat(recordedRequest.get().requestHeaders().get("Cookie")).isEqualTo("cookie_key=cookie_val"); assertThat(recordedRequestBody.get()).isEqualTo("paramA=A&paramB=b%21%22%23%C2%A4%25%2F%3D%26"); server.disposeNow(); } @Test public void shouldAllowBodyInPostPutDeletePatchCalls() { AtomicReference<HttpServerRequest> recordedRequest = new AtomicReference<>(); AtomicReference<String> recordedRequestBody = new AtomicReference<>(); DisposableServer server = HttpServer.create().port(0).handle((request, response) -> { recordedRequest.set(request); response.status(HttpResponseStatus.NO_CONTENT); return request.receive().flatMap(buf -> { recordedRequestBody.set(buf.toString(Charset.defaultCharset())); return Flux.empty(); }); }).bindNow(); TestResource resource = getHttpProxy(server.port()); resource.patch("test").toBlocking().lastOrDefault(null); assertThat(recordedRequestBody.get()).isEqualTo("\"test\""); assertThat(recordedRequest.get().method()).isEqualTo(HttpMethod.PATCH); resource.delete("test").toBlocking().lastOrDefault(null); assertThat(recordedRequestBody.get()).isEqualTo("\"test\""); assertThat(recordedRequest.get().method()).isEqualTo(HttpMethod.DELETE); resource.put("test").toBlocking().lastOrDefault(null); assertThat(recordedRequestBody.get()).isEqualTo("\"test\""); assertThat(recordedRequest.get().method()).isEqualTo(HttpMethod.PUT); resource.post("test").toBlocking().lastOrDefault(null); assertThat(recordedRequestBody.get()).isEqualTo("\"test\""); assertThat(recordedRequest.get().method()).isEqualTo(HttpMethod.POST); server.disposeNow(); } @Test public void shouldExecutePreRequestHooks() throws URISyntaxException { DisposableServer server = HttpServer.create().port(0).handle((request, response) -> { response.status(HttpResponseStatus.OK); return response.sendString(Mono.just("\"hi\"")); }).bindNow(); String url = "localhost:" + server.port(); HttpClientConfig config = new HttpClientConfig(url); ReactorRxClientProvider clientProvider = new ReactorRxClientProvider(config, healthRecorder); PreRequestHook preRequestHook = mock(PreRequestHook.class); HashSet<PreRequestHook> preRequestHooks = Sets.newHashSet(preRequestHook); HttpClient client = new HttpClient(config, clientProvider, new ObjectMapper(), new RequestParameterSerializers(), preRequestHooks); TestResource resource = client.create(TestResource.class); resource.getHello().toBlocking().single(); verify(preRequestHook, times(1)).apply((TestUtil.matches(requestBuilder -> { assertThat(requestBuilder.getFullUrl()).isEqualToIgnoringCase(url + "/hello"); }))); server.disposeNow(); } @Test public void shouldErrorOnUntrustedHost() throws URISyntaxException, CertificateException { SelfSignedCertificate cert = new SelfSignedCertificate(); SslContextBuilder serverOptions = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()); DisposableServer server = reactor.netty.http.server.HttpServer.create() .secure(sslContextSpec -> sslContextSpec.sslContext(serverOptions)) .handle((req, res) -> res.sendString(Mono.just("Hello"))) .bindNow(); HttpClientConfig httpClientConfig = new HttpClientConfig("https: Injector injector = injectorWithProgrammaticHttpClientConfig(httpClientConfig); ReactorRxClientProvider rxClientProvider = injector.getInstance(ReactorRxClientProvider.class); try { rxClientProvider .clientFor(new InetSocketAddress("localhost", server.port())) .get() .uri("/") .responseContent() .aggregate() .asString() .block(); fail("expected error"); } catch (RuntimeException runtimeException) { assertThat(runtimeException.getCause()).isInstanceOf(SSLHandshakeException.class); } server.disposeNow(); } @Test public void shouldHandleUnsafeSecureOnUntrustedHost() throws URISyntaxException, CertificateException { SelfSignedCertificate cert =new SelfSignedCertificate(); SslContextBuilder serverOptions = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()); DisposableServer server = reactor.netty.http.server.HttpServer.create() .secure(sslContextSpec -> sslContextSpec.sslContext(serverOptions)) .handle((req, res) -> res.sendString(Mono.just("Hello"))) .bindNow(); HttpClientConfig httpClientConfig = new HttpClientConfig("https: httpClientConfig.setValidateCertificates(false); Injector injector = injectorWithProgrammaticHttpClientConfig(httpClientConfig); ReactorRxClientProvider rxClientProvider = injector.getInstance(ReactorRxClientProvider.class); try { String response = rxClientProvider .clientFor(new InetSocketAddress("localhost", server.port())) .get() .uri("/") .responseContent() .aggregate() .asString() .block(); assertThat(response).isEqualTo("Hello"); } catch (RuntimeException runtimeException) { Assert.fail("Should not give an error"); } server.disposeNow(); } @Test public void shouldSupportSendingXml() { AtomicReference<HttpServerRequest> recordedRequest = new AtomicReference<>(); AtomicReference<String> recordedRequestBody = new AtomicReference<>(); DisposableServer server = HttpServer.create().port(0).handle((request, response) -> { recordedRequest.set(request); response.status(HttpResponseStatus.NO_CONTENT); return request.receive().flatMap(buf -> { recordedRequestBody.set(buf.toString(Charset.defaultCharset())); return Flux.empty(); }); }).bindNow(); TestResource resource = getHttpProxy(server.port()); resource.sendXml("<xml></xml>").toBlocking().lastOrDefault(null); assertThat(recordedRequestBody.get()).isEqualTo("<xml></xml>"); assertThat(recordedRequest.get().method()).isEqualTo(HttpMethod.POST); assertThat(recordedRequest.get().requestHeaders().get("Content-Type")).isEqualTo("application/xml"); server.disposeNow(); } @Test public void shouldSupportSendingXmlAsBytes() { AtomicReference<HttpServerRequest> recordedRequest = new AtomicReference<>(); AtomicReference<String> recordedRequestBody = new AtomicReference<>(); DisposableServer server = HttpServer.create().port(0).handle((request, response) -> { recordedRequest.set(request); response.status(HttpResponseStatus.NO_CONTENT); return request.receive().flatMap(buf -> { recordedRequestBody.set(buf.toString(Charset.defaultCharset())); return Flux.empty(); }); }).bindNow(); TestResource resource = getHttpProxy(server.port()); resource.sendXml("<xml></xml>".getBytes(Charset.defaultCharset())).toBlocking().lastOrDefault(null); assertThat(recordedRequestBody.get()).isEqualTo("<xml></xml>"); assertThat(recordedRequest.get().method()).isEqualTo(HttpMethod.POST); assertThat(recordedRequest.get().requestHeaders().get("Content-Type")).isEqualTo("application/xml"); server.disposeNow(); } @Test public void shouldFailIfBodyIsNotStringOrBytes() { AtomicReference<HttpServerRequest> recordedRequest = new AtomicReference<>(); AtomicReference<String> recordedRequestBody = new AtomicReference<>(); DisposableServer server = HttpServer.create().port(0).handle((request, response) -> { recordedRequest.set(request); response.status(HttpResponseStatus.NO_CONTENT); return request.receive().flatMap(buf -> { recordedRequestBody.set(buf.toString(Charset.defaultCharset())); return Flux.empty(); }); }).bindNow(); TestResource resource = getHttpProxy(server.port()); try { resource.sendXml(new Pojo()).toBlocking().lastOrDefault(null); fail("expected exception"); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("When content type is not application/json the body param must be String or byte[], but was class se.fortnox.reactivewizard.client.HttpClientTest$Pojo"); } server.disposeNow(); }
HttpClient implements InvocationHandler { protected String serialize(Object value) { if (value instanceof Date) { return String.valueOf(((Date)value).getTime()); } if (value.getClass().isArray()) { value = asList((Object[])value); } if (value instanceof List) { StringBuilder stringBuilder = new StringBuilder(); List list = (List)value; for (int i = 0; i < list.size(); i++) { Object entryValue = list.get(i); stringBuilder.append(entryValue); if (i < list.size() - 1) { stringBuilder.append(","); } } return stringBuilder.toString(); } return value.toString(); } @Inject HttpClient(HttpClientConfig config, ReactorRxClientProvider clientProvider, ObjectMapper objectMapper, RequestParameterSerializers requestParameterSerializers, Set<PreRequestHook> preRequestHooks ); HttpClient(HttpClientConfig config); static void setTimeout(Object proxy, int timeout, ChronoUnit timeoutUnit); void setTimeout(int timeout, ChronoUnit timeoutUnit); @SuppressWarnings("unchecked") T create(Class<T> jaxRsInterface); @Override Object invoke(Object proxy, Method method, Object[] arguments); static Observable<Response<T>> getFullResponse(Observable<T> source); static Single<Response<T>> getFullResponse(Single<T> source); static final String COOKIE; }
@Test public void shouldSerializeDate() throws Exception { HttpClient client = new HttpClient(new HttpClientConfig("localhost")); assertThat(client.serialize(new Date(1474889891615L))).isEqualTo("1474889891615"); } @Test public void shouldSerializeList() throws Exception { HttpClient client = new HttpClient(new HttpClientConfig("localhost")); assertThat(client.serialize(new Long[]{})).isEqualTo(""); assertThat(client.serialize(new Long[]{5L, 78L, 1005L})).isEqualTo("5,78,1005"); assertThat(client.serialize(new ArrayList<>())).isEqualTo(""); assertThat(client.serialize(Arrays.asList(5L, 78L, 1005L))).isEqualTo("5,78,1005"); }
HttpClient implements InvocationHandler { protected String getPath(Method method, Object[] arguments, JaxRsMeta meta) { String path = meta.getFullPath(); StringBuilder query = null; Class<?>[] types = method.getParameterTypes(); List<Object> args = new ArrayList<>(asList(arguments)); List<Annotation[]> argumentAnnotations = new ArrayList<>(asList(method.getParameterAnnotations())); for (int i = 0; i < args.size(); i++) { Object value = args.get(i); for (Annotation annotation : argumentAnnotations.get(i)) { if (annotation instanceof QueryParam) { if (value == null) { continue; } if (query == null) { query = new StringBuilder(path.contains("?") ? "&" : "?"); } else { query.append('&'); } query.append(((QueryParam)annotation).value()); query.append('='); query.append(urlEncode(serialize(value))); } else if (annotation instanceof PathParam) { if (path.contains("{" + ((PathParam)annotation).value() + ":.*}")) { path = path.replaceAll("\\{" + ((PathParam)annotation).value() + ":.*\\}", this.encode(this.serialize(value))); } else { path = path.replaceAll("\\{" + ((PathParam)annotation).value() + "\\}", this.urlEncode(this.serialize(value))); } } else if (annotation instanceof BeanParam) { if (value == null) { continue; } beanParamCache .computeIfAbsent(types[i], this::getBeanParamGetters) .forEach(beanParamProperty -> { args.add(beanParamProperty.getter.apply(value)); argumentAnnotations.add(beanParamProperty.annotations); }); } } } if (query != null) { return path + query; } return path; } @Inject HttpClient(HttpClientConfig config, ReactorRxClientProvider clientProvider, ObjectMapper objectMapper, RequestParameterSerializers requestParameterSerializers, Set<PreRequestHook> preRequestHooks ); HttpClient(HttpClientConfig config); static void setTimeout(Object proxy, int timeout, ChronoUnit timeoutUnit); void setTimeout(int timeout, ChronoUnit timeoutUnit); @SuppressWarnings("unchecked") T create(Class<T> jaxRsInterface); @Override Object invoke(Object proxy, Method method, Object[] arguments); static Observable<Response<T>> getFullResponse(Observable<T> source); static Single<Response<T>> getFullResponse(Single<T> source); static final String COOKIE; }
@Test public void shouldEncodePath() throws Exception { HttpClient client = new HttpClient(new HttpClientConfig("localhost")); Method method = TestResource.class.getMethod("withPathAndQueryParam", String.class, String.class); String path = client.getPath(method, new Object[]{"key_with_ä", "value_with_+"}, new JaxRsMeta(method, null)); assertThat(path).isEqualTo("/hello/{fid}/key_with_%C3%A4?value=value_with_%2B"); } @Test public void shouldEncodeWithMultipleQueryParams() throws Exception { HttpClient client = new HttpClient(new HttpClientConfig("localhost")); Method method = TestResource.class.getMethod("withMultipleQueryParam", String.class, String.class); String path = client.getPath(method, new Object[]{"first", "second"}, new JaxRsMeta(method, null)); assertThat(path).isEqualTo("/hello/multipleQueryParams?valueA=first&valueB=second"); } @Test public void shouldEncodePathWithoutNullValues() throws Exception { HttpClient client = new HttpClient(new HttpClientConfig("localhost")); Method method = TestResource.class.getMethod("withPathAndQueryParam", String.class, String.class); String path = client.getPath(method, new Object[]{"path", null}, new JaxRsMeta(method, null)); assertThat(path).isEqualTo("/hello/{fid}/path"); } @Test public void shouldNotEncodePathWithSlash() throws Exception { HttpClient client = new HttpClient(new HttpClientConfig("localhost")); Method method = TestResource.class.getMethod("withRegExpPathAndQueryParam", String.class, String.class); String path = client.getPath(method, new Object[]{"key/with/Slash", "value/with/slash"}, new JaxRsMeta(method, null)); assertThat(path).isEqualTo("/hello/{fid}/key/with/Slash?value=value%2Fwith%2Fslash"); } @Test public void shouldEncodePathWithSlash() throws Exception { HttpClient client = new HttpClient(new HttpClientConfig("localhost")); Method method = TestResource.class.getMethod("withPathAndQueryParam", String.class, String.class); String path = client.getPath(method, new Object[]{"key/with/Slash", "value/with/slash"}, new JaxRsMeta(method, null)); assertThat(path).isEqualTo("/hello/{fid}/key%2Fwith%2FSlash?value=value%2Fwith%2Fslash"); } @Test public void shouldEncodePathAndQueryWithColon() throws Exception { HttpClient client = new HttpClient(new HttpClientConfig("localhost")); Method method = TestResource.class.getMethod("withPathAndQueryParam", String.class, String.class); String path = client.getPath(method, new Object[]{"path:param", "query-param-with:colon"}, new JaxRsMeta(method, null)); assertThat(path).isEqualTo("/hello/{fid}/path%3Aparam?value=query-param-with%3Acolon"); } @Test public void shouldSupportBeanParam() throws Exception { HttpClient client = new HttpClient(new HttpClientConfig("localhost")); Method method = TestResource.class.getMethod("withBeanParam", TestResource.Filters.class); TestResource.Filters filters = new TestResource.Filters(); filters.setFilter1("a"); filters.setFilter2("b"); String path = client.getPath(method, new Object[]{filters}, new JaxRsMeta(method, null)); assertThat(path).isEqualTo("/hello/beanParam?filter1=a&filter2=b"); }
HttpClient implements InvocationHandler { public static <T> Observable<Response<T>> getFullResponse(Observable<T> source) { if (!(source instanceof ObservableWithResponse)) { throw new IllegalArgumentException("Must be used with observable returned from api call"); } return source.map(data -> new Response<>(((ObservableWithResponse<T>)source).getResponse(), data)) .switchIfEmpty(fromCallable(() -> new Response<>(((ObservableWithResponse<T>)source).getResponse(), null))); } @Inject HttpClient(HttpClientConfig config, ReactorRxClientProvider clientProvider, ObjectMapper objectMapper, RequestParameterSerializers requestParameterSerializers, Set<PreRequestHook> preRequestHooks ); HttpClient(HttpClientConfig config); static void setTimeout(Object proxy, int timeout, ChronoUnit timeoutUnit); void setTimeout(int timeout, ChronoUnit timeoutUnit); @SuppressWarnings("unchecked") T create(Class<T> jaxRsInterface); @Override Object invoke(Object proxy, Method method, Object[] arguments); static Observable<Response<T>> getFullResponse(Observable<T> source); static Single<Response<T>> getFullResponse(Single<T> source); static final String COOKIE; }
@Test public void shouldReturnFullResponseFromObservable() { DisposableServer server = startServer(HttpResponseStatus.OK, Mono.just("\"OK\""), httpServerRequest -> {}, httpServerResponse -> { httpServerResponse.addCookie(new DefaultCookie("cookieName", "cookieValue")); }); TestResource resource = getHttpProxy(server.port()); Response<String> stringResponse = HttpClient.getFullResponse(resource.getHello()) .toBlocking().singleOrDefault(null); assertThat(stringResponse).isNotNull(); assertThat(stringResponse.getBody()).isEqualTo("OK"); assertThat(stringResponse.getStatus()).isEqualTo(OK); assertThat(stringResponse.getHeaders().get("content-length")).isEqualTo("4"); assertThat(stringResponse.getHeader(CONTENT_LENGTH)).isEqualTo("4"); assertThat(stringResponse.getCookie("cookieName")).hasSize(1); assertThat(stringResponse.getCookie("cookieName").get(0)).isEqualTo("cookieValue"); assertThat(stringResponse.getCookie(null)).hasSize(0); assertThat(stringResponse.getCookie("bogus")).hasSize(0); } @Test public void shouldReturnFullResponseFromEmptyObservable() { DisposableServer server = startServer(HttpResponseStatus.OK, Mono.just(""), httpServerRequest -> {}, httpServerResponse -> { httpServerResponse.addCookie(new DefaultCookie("cookieName", "cookieValue")); }); TestResource resource = getHttpProxy(server.port()); Response<String> stringResponse = HttpClient.getFullResponse(resource.getHello()) .toBlocking().singleOrDefault(null); assertThat(stringResponse).isNotNull(); assertThat(stringResponse.getBody()).isNull(); assertThat(stringResponse.getStatus()).isEqualTo(OK); } @Test public void shouldWrapAndReturnNewFullResponseObservable() { DisposableServer server = startServer(HttpResponseStatus.OK, "\"OK\""); TestResource resource = getHttpProxy(server.port()); Observable<String> hello = resource.getHello(); ObservableWithResponse<String> wrappedStringResponse = ObservableWithResponse.from((ObservableWithResponse)hello, hello.doOnError(Throwable::printStackTrace)); Response<String> stringResponse = HttpClient.getFullResponse(wrappedStringResponse).toBlocking().singleOrDefault(null); assertThat(stringResponse).isNotNull(); assertThat(stringResponse.getBody()).isEqualTo("OK"); assertThat(stringResponse.getStatus()).isEqualTo(OK); assertThat(stringResponse.getHeaders().get("content-length")).isEqualTo("4"); assertThat(stringResponse.getHeader(CONTENT_LENGTH)).isEqualTo("4"); } @Test public void shouldReturnFullResponseFromSingle() { DisposableServer server = startServer(HttpResponseStatus.OK, "\"OK\""); TestResource resource = getHttpProxy(server.port()); Response<String> stringResponse = HttpClient.getFullResponse(resource.getSingle()) .toBlocking().value(); assertThat(stringResponse).isNotNull(); assertThat(stringResponse.getBody()).isEqualTo("OK"); assertThat(stringResponse.getStatus()).isEqualTo(OK); assertThat(stringResponse.getHeaders().get("content-length")).isEqualTo("4"); } @Test @SuppressWarnings("unchecked") public void shouldWrapAndReturnNewFullResponseSingle() { DisposableServer server = startServer(HttpResponseStatus.OK, "\"OK\""); TestResource resource = getHttpProxy(server.port()); Single<String> hello = resource.getSingle(); SingleWithResponse<String> wrappedStringResponse = SingleWithResponse.from((SingleWithResponse)hello, hello.doOnError(Throwable::printStackTrace)); Response<String> stringResponse = HttpClient.getFullResponse(wrappedStringResponse).toBlocking().value(); assertThat(stringResponse).isNotNull(); assertThat(stringResponse.getBody()).isEqualTo("OK"); assertThat(stringResponse.getStatus()).isEqualTo(OK); assertThat(stringResponse.getHeaders().get("content-length")).isEqualTo("4"); assertThat(stringResponse.getHeader(CONTENT_LENGTH)).isEqualTo("4"); }
HttpClient implements InvocationHandler { public static void setTimeout(Object proxy, int timeout, ChronoUnit timeoutUnit) { if (Proxy.isProxyClass(proxy.getClass())) { Object handler = Proxy.getInvocationHandler(proxy); if (handler instanceof HttpClient) { ((HttpClient)handler).setTimeout(timeout, timeoutUnit); } } } @Inject HttpClient(HttpClientConfig config, ReactorRxClientProvider clientProvider, ObjectMapper objectMapper, RequestParameterSerializers requestParameterSerializers, Set<PreRequestHook> preRequestHooks ); HttpClient(HttpClientConfig config); static void setTimeout(Object proxy, int timeout, ChronoUnit timeoutUnit); void setTimeout(int timeout, ChronoUnit timeoutUnit); @SuppressWarnings("unchecked") T create(Class<T> jaxRsInterface); @Override Object invoke(Object proxy, Method method, Object[] arguments); static Observable<Response<T>> getFullResponse(Observable<T> source); static Single<Response<T>> getFullResponse(Single<T> source); static final String COOKIE; }
@Test public void shouldNotRetryOnTimeout() { AtomicLong callCount = new AtomicLong(); DisposableServer server = startSlowServer(HttpResponseStatus.NOT_FOUND, 1000, r -> callCount.incrementAndGet()); TestResource resource = getHttpProxy(server.port()); HttpClient.setTimeout(resource, 500, ChronoUnit.MILLIS); try { resource.getHello().toBlocking().singleOrDefault(null); fail("expected exception"); } catch (WebException e) { assertThat(e.getStatus()).isEqualTo(GATEWAY_TIMEOUT); } assertThat(callCount.get()).isEqualTo(1); server.disposeNow(); } @Test public void shouldHandleLongerRequestsThan10SecondsWhenRequested() { DisposableServer server = startSlowServer(HttpResponseStatus.NOT_FOUND, 20000); TestResource resource = getHttpProxy(server.port(), 1, 30000); HttpClient.setTimeout(resource, 15000, ChronoUnit.MILLIS); try { resource.getHello().toBlocking().singleOrDefault(null); fail("expected exception"); } catch (WebException e) { assertThat(e.getStatus()).isEqualTo(GATEWAY_TIMEOUT); } server.disposeNow(); } @Test public void shouldLogRequestDetailsOnTimeout() { DisposableServer server = startServer(OK, Flux.never(), r -> { }); try { TestResource resource = getHttpProxy(server.port()); HttpClient.setTimeout(resource, 10, ChronoUnit.MILLIS); resource.servertest("mode").toBlocking().single(); fail("expected timeout"); } catch (Exception e) { OutputStream baos = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(baos, true); e.printStackTrace(stream); assertThat(baos.toString()).contains("Timeout after 10 ms calling localhost:" + server.port() + "/hello/servertest/mode"); } finally { server.disposeNow(); } }
ConnectionCounter { public boolean awaitZero(int time, TimeUnit timeUnit) { try { boolean success = connectionsZero.tryAcquire(time, timeUnit); if (success) { connectionsZero.release(); } return success; } catch (Exception e) { return false; } } ConnectionCounter(); ConnectionCounter(AtomicLong connections, Semaphore connectionsZero); void increase(); void decrease(); boolean awaitZero(int time, TimeUnit timeUnit); long getCount(); }
@Test public void testZeroConnections() { assertTrue(connectionCounter.awaitZero(0, TimeUnit.SECONDS)); } @Test public void shouldReturnFalseWhenExceptionOccuresDuringAwaitZero() throws InterruptedException { Semaphore connectionsZero = mock(Semaphore.class); when(connectionsZero.tryAcquire(anyLong(), any(TimeUnit.class))).thenThrow(new InterruptedException()); ConnectionCounter connectionCounter = new ConnectionCounter(new AtomicLong(), connectionsZero); assertFalse(connectionCounter.awaitZero(10, TimeUnit.SECONDS)); }
RwServer extends Thread { public DisposableServer getServer() { return server; } @Inject RwServer(ServerConfig config, CompositeRequestHandler compositeRequestHandler, ConnectionCounter connectionCounter); RwServer(ServerConfig config, CompositeRequestHandler compositeRequestHandler, ConnectionCounter connectionCounter, LoopResources loopResources); RwServer(ServerConfig config, ConnectionCounter connectionCounter, HttpServer httpServer, CompositeRequestHandler compositeRequestHandler, LoopResources loopResources); @Override void run(); DisposableServer getServer(); static void registerShutdownDependency(Runnable blockShutdownUntil); }
@Test public void shouldSetServerToNullIfConfigSaysDisabled() throws InterruptedException { ServerConfig serverConfig = new ServerConfig(); serverConfig.setEnabled(false); serverConfig.setPort(0); RwServer rwServer = new RwServer(serverConfig, compositeRequestHandler, connectionCounter, null); rwServer.join(); assertNull(rwServer.getServer()); } @Test public void shouldStartTheServerIfConfigSaysEnabled() throws InterruptedException { ServerConfig serverConfig = new ServerConfig(); serverConfig.setPort(0); AtomicInteger startInvocedNumberOfTimes = new AtomicInteger(0); RwServer rwServer = null; try { rwServer = new RwServer(serverConfig, compositeRequestHandler, connectionCounter, null) { @Override public void start() { startInvocedNumberOfTimes.incrementAndGet(); } }; rwServer.join(); assertThat(rwServer.getServer()).isNotNull().isInstanceOf(DisposableServer.class); assertThat(startInvocedNumberOfTimes.get()).isEqualTo(1); } finally { if (rwServer != null) { rwServer.getServer().disposeNow(); } } }
JaxRsRequestHandler implements RequestHandler { @Override public Publisher<Void> apply(HttpServerRequest request, HttpServerResponse response) { JaxRsRequest jaxRsRequest = new JaxRsRequest(request, collector); JaxRsResource<?> resource = resources.findResource(jaxRsRequest); if (resource == null) { return null; } preHandle(request, resource); long requestStartTime = System.currentTimeMillis(); Publisher<Void> resourceCall = null; JaxRsResourceInterceptor.JaxRsResourceContext resourceContext = new JaxRsResourceCallContext(request, resource); try { requestInterceptors.preHandle(resourceContext); resourceCall = resource.call(jaxRsRequest) .flatMap(result -> Mono.from(writeResult(response, result))) .onErrorResume(e -> Mono.from(exceptionHandler.handleException(request, response, e))) .doAfterTerminate(() -> resource.log(request, response, requestStartTime)); return resourceCall; } finally { requestInterceptors.postHandle(resourceContext, resourceCall); } } @Inject JaxRsRequestHandler(JaxRsResourcesProvider services, JaxRsResourceFactory jaxRsResourceFactory, ExceptionHandler exceptionHandler, ByteBufCollector collector, JaxRsResourceInterceptors requestInterceptors ); JaxRsRequestHandler(JaxRsResourcesProvider services, JaxRsResourceFactory jaxRsResourceFactory, ExceptionHandler exceptionHandler, ByteBufCollector collector); JaxRsRequestHandler(Object[] services, JaxRsResourceFactory jaxRsResourceFactory, ExceptionHandler exceptionHandler, Boolean classReloading); JaxRsRequestHandler(Object[] services, JaxRsResourceFactory jaxRsResourceFactory, ExceptionHandler exceptionHandler, Boolean classReloading, JaxRsResourceInterceptors requestInterceptors ); JaxRsRequestHandler(Object[] services, JaxRsResourceFactory jaxRsResourceFactory, ExceptionHandler exceptionHandler, ByteBufCollector collector, Boolean classReloading, JaxRsResourceInterceptors requestInterceptors ); @Override Publisher<Void> apply(HttpServerRequest request, HttpServerResponse response); }
@Test public void shouldInterceptResourceCall() { MockHttpServerRequest request = new MockHttpServerRequest("/"); MockHttpServerResponse response = new MockHttpServerResponse(); Publisher<Void> result = handler.apply(request, response); assertThat(interceptor.preHandled).isNotNull(); assertThat(interceptor.postHandled).isNotNull(); assertThat(interceptor.resourceCall).isSameAs(result); }
RwServer extends Thread { public static void registerShutdownDependency(Runnable blockShutdownUntil) { if (RwServer.blockShutdownUntil != null && blockShutdownUntil != null) { throw new IllegalStateException("Shutdown dependency is already registered"); } RwServer.blockShutdownUntil = blockShutdownUntil; } @Inject RwServer(ServerConfig config, CompositeRequestHandler compositeRequestHandler, ConnectionCounter connectionCounter); RwServer(ServerConfig config, CompositeRequestHandler compositeRequestHandler, ConnectionCounter connectionCounter, LoopResources loopResources); RwServer(ServerConfig config, ConnectionCounter connectionCounter, HttpServer httpServer, CompositeRequestHandler compositeRequestHandler, LoopResources loopResources); @Override void run(); DisposableServer getServer(); static void registerShutdownDependency(Runnable blockShutdownUntil); }
@Test public void shouldNotOverrideShutdownDependency() { RwServer.registerShutdownDependency(() -> {}); try { RwServer.registerShutdownDependency(() -> {}); fail(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Shutdown dependency is already registered"); } }
RwServer extends Thread { static void awaitShutdownDependency(int shutdownTimeoutSeconds) { if (blockShutdownUntil == null) { return; } LOG.info("Wait for completion of shutdown dependency"); Thread thread = new Thread(blockShutdownUntil); thread.start(); try { thread.join(Duration.ofSeconds(shutdownTimeoutSeconds).toMillis()); } catch (InterruptedException e) { LOG.error("Fail while waiting shutdown dependency", e); } LOG.info("Shutdown dependency completed, continue..."); } @Inject RwServer(ServerConfig config, CompositeRequestHandler compositeRequestHandler, ConnectionCounter connectionCounter); RwServer(ServerConfig config, CompositeRequestHandler compositeRequestHandler, ConnectionCounter connectionCounter, LoopResources loopResources); RwServer(ServerConfig config, ConnectionCounter connectionCounter, HttpServer httpServer, CompositeRequestHandler compositeRequestHandler, LoopResources loopResources); @Override void run(); DisposableServer getServer(); static void registerShutdownDependency(Runnable blockShutdownUntil); }
@Test public void shouldSkipAwaitingShutdownDependencyIfNotSet() throws NoSuchFieldException, IllegalAccessException { Appender mockAppender = LoggingMockUtil.createMockedLogAppender(RwServer.class); RwServer.awaitShutdownDependency(new ServerConfig().getShutdownTimeoutSeconds()); verify(mockAppender, never()).doAppend(any()); }