_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q174000
DistributedVectorMessage.processMessage
test
@Override public void processMessage() { VectorAggregation aggregation = new VectorAggregation(rowIndex, (short) voidConfiguration.getNumberOfShards(), shardIndex, storage.getArray(key).getRow(rowIndex).dup()); aggregation.setOriginatorId(this.getOriginatorId()); transport.sendMessage(aggregation); }
java
{ "resource": "" }
q174001
BigDecimalMath.gamma
test
static public BigDecimal gamma(MathContext mc) { /* look it up if possible */ if (mc.getPrecision() < GAMMA.precision()) { return GAMMA.round(mc); } else { double eps = prec2err(0.577, mc.getPrecision()); /* Euler-Stieltjes as shown in Dilcher, Aequat Math 48 (1) (1994) 55-85 14 */ MathContext mcloc = new MathContext(2 + mc.getPrecision()); BigDecimal resul = BigDecimal.ONE; resul = resul.add(log(2, mcloc)); resul = resul.subtract(log(3, mcloc)); /* how many terms: zeta-1 falls as 1/2^(2n+1), so the * terms drop faster than 1/2^(4n+2). Set 1/2^(4kmax+2) < eps. * Leading term zeta(3)/(4^1*3) is 0.017. Leading zeta(3) is 1.2. Log(2) is 0.7 */ int kmax = (int) ((Math.log(eps / 0.7) - 2.) / 4.); mcloc = new MathContext(1 + err2prec(1.2, eps / kmax)); for (int n = 1;; n++) { /* zeta is close to 1. Division of zeta-1 through * 4^n*(2n+1) means divion through roughly 2^(2n+1) */ BigDecimal c = zeta(2 * n + 1, mcloc).subtract(BigDecimal.ONE); BigInteger fourn = BigInteger.valueOf(2 * n + 1); fourn = fourn.shiftLeft(2 * n); c = divideRound(c, fourn); resul = resul.subtract(c); if (c.doubleValue() < 0.1 * eps) { break; } } return resul.round(mc); } }
java
{ "resource": "" }
q174002
BigDecimalMath.sqrt
test
static public BigDecimal sqrt(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { throw new ArithmeticException("negative argument " + x.toString() + " of square root"); } return root(2, x); }
java
{ "resource": "" }
q174003
BigDecimalMath.cbrt
test
static public BigDecimal cbrt(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return root(3, x.negate()).negate(); } else { return root(3, x); } }
java
{ "resource": "" }
q174004
BigDecimalMath.root
test
static public BigDecimal root(final int n, final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { throw new ArithmeticException("negative argument " + x.toString() + " of root"); } if (n <= 0) { throw new ArithmeticException("negative power " + n + " of root"); } if (n == 1) { return x; } /* start the computation from a double precision estimate */ BigDecimal s = new BigDecimal(Math.pow(x.doubleValue(), 1.0 / n)); /* this creates nth with nominal precision of 1 digit */ final BigDecimal nth = new BigDecimal(n); /* Specify an internal accuracy within the loop which is * slightly larger than what is demanded by ’eps’ below. */ final BigDecimal xhighpr = scalePrec(x, 2); MathContext mc = new MathContext(2 + x.precision()); /* Relative accuracy of the result is eps. */ final double eps = x.ulp().doubleValue() / (2 * n * x.doubleValue()); for (;;) { /* s = s -(s/n-x/n/s^(n-1)) = s-(s-x/s^(n-1))/n; test correction s/n-x/s for being * smaller than the precision requested. The relative correction is (1-x/s^n)/n, */ BigDecimal c = xhighpr.divide(s.pow(n - 1), mc); c = s.subtract(c); MathContext locmc = new MathContext(c.precision()); c = c.divide(nth, locmc); s = s.subtract(c); if (Math.abs(c.doubleValue() / s.doubleValue()) < eps) { break; } } return s.round(new MathContext(err2prec(eps))); }
java
{ "resource": "" }
q174005
BigDecimalMath.exp
test
static public BigDecimal exp(BigDecimal x) { /* To calculate the value if x is negative, use exp(-x) = 1/exp(x) */ if (x.compareTo(BigDecimal.ZERO) < 0) { final BigDecimal invx = exp(x.negate()); /* Relative error in inverse of invx is the same as the relative errror in invx. * This is used to define the precision of the result. */ MathContext mc = new MathContext(invx.precision()); return BigDecimal.ONE.divide(invx, mc); } else if (x.compareTo(BigDecimal.ZERO) == 0) { /* recover the valid number of digits from x.ulp(), if x hits the * zero. The x.precision() is 1 then, and does not provide this information. */ return scalePrec(BigDecimal.ONE, -(int) (Math.log10(x.ulp().doubleValue()))); } else { /* Push the number in the Taylor expansion down to a small * value where TAYLOR_NTERM terms will do. If x<1, the n-th term is of the order * x^n/n!, and equal to both the absolute and relative error of the result * since the result is close to 1. The x.ulp() sets the relative and absolute error * of the result, as estimated from the first Taylor term. * We want x^TAYLOR_NTERM/TAYLOR_NTERM! < x.ulp, which is guaranteed if * x^TAYLOR_NTERM < TAYLOR_NTERM*(TAYLOR_NTERM-1)*...*x.ulp. */ final double xDbl = x.doubleValue(); final double xUlpDbl = x.ulp().doubleValue(); if (Math.pow(xDbl, TAYLOR_NTERM) < TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0) * xUlpDbl) { /* Add TAYLOR_NTERM terms of the Taylor expansion (Euler’s sum formula) */ BigDecimal resul = BigDecimal.ONE; /* x^i */ BigDecimal xpowi = BigDecimal.ONE; /* i factorial */ BigInteger ifac = BigInteger.ONE; /* TAYLOR_NTERM terms to be added means we move x.ulp() to the right * for each power of 10 in TAYLOR_NTERM, so the addition won’t add noise beyond * what’s already in x. */ MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / TAYLOR_NTERM)); for (int i = 1; i <= TAYLOR_NTERM; i++) { ifac = ifac.multiply(BigInteger.valueOf(i)); xpowi = xpowi.multiply(x); final BigDecimal c = xpowi.divide(new BigDecimal(ifac), mcTay); resul = resul.add(c); if (Math.abs(xpowi.doubleValue()) < i && Math.abs(c.doubleValue()) < 0.5 * xUlpDbl) { break; } } /* exp(x+deltax) = exp(x)(1+deltax) if deltax is <<1. So the relative error * in the result equals the absolute error in the argument. */ MathContext mc = new MathContext(err2prec(xUlpDbl / 2.)); return resul.round(mc); } else { /* Compute exp(x) = (exp(0.1*x))^10. Division by 10 does not lead * to loss of accuracy. */ int exSc = (int) (1.0 - Math.log10(TAYLOR_NTERM * (TAYLOR_NTERM - 1.0) * (TAYLOR_NTERM - 2.0) * xUlpDbl / Math.pow(xDbl, TAYLOR_NTERM)) / (TAYLOR_NTERM - 1.0)); BigDecimal xby10 = x.scaleByPowerOfTen(-exSc); BigDecimal expxby10 = exp(xby10); /* Final powering by 10 means that the relative error of the result * is 10 times the relative error of the base (First order binomial expansion). * This looses one digit. */ MathContext mc = new MathContext(expxby10.precision() - exSc); /* Rescaling the powers of 10 is done in chunks of a maximum of 8 to avoid an invalid operation 17 * response by the BigDecimal.pow library or integer overflow. */ while (exSc > 0) { int exsub = Math.min(8, exSc); exSc -= exsub; MathContext mctmp = new MathContext(expxby10.precision() - exsub + 2); int pex = 1; while (exsub-- > 0) { pex *= 10; } expxby10 = expxby10.pow(pex, mctmp); } return expxby10.round(mc); } } }
java
{ "resource": "" }
q174006
BigDecimalMath.exp
test
static public BigDecimal exp(final MathContext mc) { /* look it up if possible */ if (mc.getPrecision() < E.precision()) { return E.round(mc); } else { /* Instantiate a 1.0 with the requested pseudo-accuracy * and delegate the computation to the public method above. */ BigDecimal uni = scalePrec(BigDecimal.ONE, mc.getPrecision()); return exp(uni); } }
java
{ "resource": "" }
q174007
BigDecimalMath.pow
test
static public BigDecimal pow(final BigDecimal x, final BigDecimal y) { if (x.compareTo(BigDecimal.ZERO) < 0) { throw new ArithmeticException("Cannot power negative " + x.toString()); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else { /* return x^y = exp(y*log(x)) ; */ BigDecimal logx = log(x); BigDecimal ylogx = y.multiply(logx); BigDecimal resul = exp(ylogx); /* The estimation of the relative error in the result is |log(x)*err(y)|+|y*err(x)/x| */ double errR = Math.abs(logx.doubleValue() * y.ulp().doubleValue() / 2.) + Math.abs(y.doubleValue() * x.ulp().doubleValue() / 2. / x.doubleValue()); MathContext mcR = new MathContext(err2prec(1.0, errR)); return resul.round(mcR); } }
java
{ "resource": "" }
q174008
BigDecimalMath.powRound
test
static public BigDecimal powRound(final BigDecimal x, final int n) { /* The relative error in the result is n times the relative error in the input. * The estimation is slightly optimistic due to the integer rounding of the logarithm. */ MathContext mc = new MathContext(x.precision() - (int) Math.log10((double) (Math.abs(n)))); return x.pow(n, mc); }
java
{ "resource": "" }
q174009
BigDecimalMath.sin
test
static public BigDecimal sin(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return sin(x.negate()).negate(); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else { /* reduce modulo 2pi */ BigDecimal res = mod2pi(x); double errpi = 0.5 * Math.abs(x.ulp().doubleValue()); int val = 2 + err2prec(FastMath.PI, errpi); MathContext mc = new MathContext(val); BigDecimal p = pi(mc); mc = new MathContext(x.precision()); if (res.compareTo(p) > 0) { /* pi<x<=2pi: sin(x)= - sin(x-pi) */ return sin(subtractRound(res, p)).negate(); } else if (res.multiply(new BigDecimal(2)).compareTo(p) > 0) { /* pi/2<x<=pi: sin(x)= sin(pi-x) */ return sin(subtractRound(p, res)); } else { /* for the range 0<=x<Pi/2 one could use sin(2x)=2sin(x)cos(x) * to split this further. Here, use the sine up to pi/4 and the cosine higher up. */ if (res.multiply(new BigDecimal(4)).compareTo(p) > 0) { /* x>pi/4: sin(x) = cos(pi/2-x) */ return cos(subtractRound(p.divide(new BigDecimal(2)), res)); } else { /* Simple Taylor expansion, sum_{i=1..infinity} (-1)^(..)res^(2i+1)/(2i+1)! */ BigDecimal resul = res; /* x^i */ BigDecimal xpowi = res; /* 2i+1 factorial */ BigInteger ifac = BigInteger.ONE; /* The error in the result is set by the error in x itself. */ double xUlpDbl = res.ulp().doubleValue(); /* The error in the result is set by the error in x itself. * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value. * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision; * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision */ int k = (int) (res.precision() / Math.log10(1.0 / res.doubleValue())) / 2; MathContext mcTay = new MathContext(err2prec(res.doubleValue(), xUlpDbl / k)); for (int i = 1;; i++) { /* TBD: at which precision will 2*i or 2*i+1 overflow? */ ifac = ifac.multiply(BigInteger.valueOf(2 * i)); ifac = ifac.multiply(BigInteger.valueOf(2 * i + 1)); xpowi = xpowi.multiply(res).multiply(res).negate(); BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); resul = resul.add(corr); if (corr.abs().doubleValue() < 0.5 * xUlpDbl) { break; } } /* The error in the result is set by the error in x itself. */ mc = new MathContext(res.precision()); return resul.round(mc); } } } /* sin */ }
java
{ "resource": "" }
q174010
BigDecimalMath.tan
test
static public BigDecimal tan(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else if (x.compareTo(BigDecimal.ZERO) < 0) { return tan(x.negate()).negate(); } else { /* reduce modulo pi */ BigDecimal res = modpi(x); /* absolute error in the result is err(x)/cos^2(x) to lowest order */ final double xDbl = res.doubleValue(); final double xUlpDbl = x.ulp().doubleValue() / 2.; final double eps = xUlpDbl / 2. / Math.pow(Math.cos(xDbl), 2.); if (xDbl > 0.8) { /* tan(x) = 1/cot(x) */ BigDecimal co = cot(x); MathContext mc = new MathContext(err2prec(1. / co.doubleValue(), eps)); return BigDecimal.ONE.divide(co, mc); } else { final BigDecimal xhighpr = scalePrec(res, 2); final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr); BigDecimal result = xhighpr.plus(); /* x^(2i+1) */ BigDecimal xpowi = xhighpr; Bernoulli b = new Bernoulli(); /* 2^(2i) */ BigInteger fourn = BigInteger.valueOf(4); /* (2i)! */ BigInteger fac = BigInteger.valueOf(2); for (int i = 2;; i++) { Rational f = b.at(2 * i).abs(); fourn = fourn.shiftLeft(2); fac = fac.multiply(BigInteger.valueOf(2 * i)).multiply(BigInteger.valueOf(2 * i - 1)); f = f.multiply(fourn).multiply(fourn.subtract(BigInteger.ONE)).divide(fac); xpowi = multiplyRound(xpowi, xhighprSq); BigDecimal c = multiplyRound(xpowi, f); result = result.add(c); if (Math.abs(c.doubleValue()) < 0.1 * eps) { break; } } MathContext mc = new MathContext(err2prec(result.doubleValue(), eps)); return result.round(mc); } } }
java
{ "resource": "" }
q174011
BigDecimalMath.cosh
test
static public BigDecimal cosh(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return cos(x.negate()); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ONE; } else { if (x.doubleValue() > 1.5) { /* cosh^2(x) = 1+ sinh^2(x). */ return hypot(1, sinh(x)); } else { BigDecimal xhighpr = scalePrec(x, 2); /* Simple Taylor expansion, sum_{0=1..infinity} x^(2i)/(2i)! */ BigDecimal resul = BigDecimal.ONE; /* x^i */ BigDecimal xpowi = BigDecimal.ONE; /* 2i factorial */ BigInteger ifac = BigInteger.ONE; /* The absolute error in the result is the error in x^2/2 which is x times the error in x. */ double xUlpDbl = 0.5 * x.ulp().doubleValue() * x.doubleValue(); /* The error in the result is set by the error in x^2/2 itself, xUlpDbl. * We need at most k terms to push x^(2k)/(2k)! below this value. * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl); */ int k = (int) (Math.log(xUlpDbl) / Math.log(x.doubleValue())) / 2; /* The individual terms are all smaller than 1, so an estimate of 1.0 for * the absolute value will give a safe relative error estimate for the indivdual terms */ MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / k)); for (int i = 1;; i++) { /* TBD: at which precision will 2*i-1 or 2*i overflow? */ ifac = ifac.multiply(BigInteger.valueOf(2 * i - 1)); ifac = ifac.multiply(BigInteger.valueOf(2 * i)); xpowi = xpowi.multiply(xhighpr).multiply(xhighpr); BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); resul = resul.add(corr); if (corr.abs().doubleValue() < 0.5 * xUlpDbl) { break; } } /* The error in the result is governed by the error in x itself. */ MathContext mc = new MathContext(err2prec(resul.doubleValue(), xUlpDbl)); return resul.round(mc); } } }
java
{ "resource": "" }
q174012
BigDecimalMath.sinh
test
static public BigDecimal sinh(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return sinh(x.negate()).negate(); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else { if (x.doubleValue() > 2.4) { /* Move closer to zero with sinh(2x)= 2*sinh(x)*cosh(x). */ BigDecimal two = new BigDecimal(2); BigDecimal xhalf = x.divide(two); BigDecimal resul = sinh(xhalf).multiply(cosh(xhalf)).multiply(two); /* The error in the result is set by the error in x itself. * The first derivative of sinh(x) is cosh(x), so the absolute error * in the result is cosh(x)*errx, and the relative error is coth(x)*errx = errx/tanh(x) */ double eps = Math.tanh(x.doubleValue()); MathContext mc = new MathContext(err2prec(0.5 * x.ulp().doubleValue() / eps)); return resul.round(mc); } else { BigDecimal xhighpr = scalePrec(x, 2); /* Simple Taylor expansion, sum_{i=0..infinity} x^(2i+1)/(2i+1)! */ BigDecimal resul = xhighpr; /* x^i */ BigDecimal xpowi = xhighpr; /* 2i+1 factorial */ BigInteger ifac = BigInteger.ONE; /* The error in the result is set by the error in x itself. */ double xUlpDbl = x.ulp().doubleValue(); /* The error in the result is set by the error in x itself. * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value. * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision; * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision */ int k = (int) (x.precision() / Math.log10(1.0 / xhighpr.doubleValue())) / 2; MathContext mcTay = new MathContext(err2prec(x.doubleValue(), xUlpDbl / k)); for (int i = 1;; i++) { /* TBD: at which precision will 2*i or 2*i+1 overflow? */ ifac = ifac.multiply(BigInteger.valueOf(2 * i)); ifac = ifac.multiply(BigInteger.valueOf(2 * i + 1)); xpowi = xpowi.multiply(xhighpr).multiply(xhighpr); BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); resul = resul.add(corr); if (corr.abs().doubleValue() < 0.5 * xUlpDbl) { break; } } /* The error in the result is set by the error in x itself. */ MathContext mc = new MathContext(x.precision()); return resul.round(mc); } } }
java
{ "resource": "" }
q174013
BigDecimalMath.tanh
test
static public BigDecimal tanh(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return tanh(x.negate()).negate(); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else { BigDecimal xhighpr = scalePrec(x, 2); /* tanh(x) = (1-e^(-2x))/(1+e^(-2x)) . */ BigDecimal exp2x = exp(xhighpr.multiply(new BigDecimal(-2))); /* The error in tanh x is err(x)/cosh^2(x). */ double eps = 0.5 * x.ulp().doubleValue() / Math.pow(Math.cosh(x.doubleValue()), 2.0); MathContext mc = new MathContext(err2prec(Math.tanh(x.doubleValue()), eps)); return BigDecimal.ONE.subtract(exp2x).divide(BigDecimal.ONE.add(exp2x), mc); } }
java
{ "resource": "" }
q174014
BigDecimalMath.asinh
test
static public BigDecimal asinh(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else { BigDecimal xhighpr = scalePrec(x, 2); /* arcsinh(x) = log(x+hypot(1,x)) */ BigDecimal logx = log(hypot(1, xhighpr).add(xhighpr)); /* The absolute error in arcsinh x is err(x)/sqrt(1+x^2) */ double xDbl = x.doubleValue(); double eps = 0.5 * x.ulp().doubleValue() / Math.hypot(1., xDbl); MathContext mc = new MathContext(err2prec(logx.doubleValue(), eps)); return logx.round(mc); } }
java
{ "resource": "" }
q174015
BigDecimalMath.acosh
test
static public BigDecimal acosh(final BigDecimal x) { if (x.compareTo(BigDecimal.ONE) < 0) { throw new ArithmeticException("Out of range argument cosh " + x.toString()); } else if (x.compareTo(BigDecimal.ONE) == 0) { return BigDecimal.ZERO; } else { BigDecimal xhighpr = scalePrec(x, 2); /* arccosh(x) = log(x+sqrt(x^2-1)) */ BigDecimal logx = log(sqrt(xhighpr.pow(2).subtract(BigDecimal.ONE)).add(xhighpr)); /* The absolute error in arcsinh x is err(x)/sqrt(x^2-1) */ double xDbl = x.doubleValue(); double eps = 0.5 * x.ulp().doubleValue() / Math.sqrt(xDbl * xDbl - 1.); MathContext mc = new MathContext(err2prec(logx.doubleValue(), eps)); return logx.round(mc); } }
java
{ "resource": "" }
q174016
BigDecimalMath.Gamma
test
static public BigDecimal Gamma(final BigDecimal x) { /* reduce to interval near 1.0 with the functional relation, Abramowitz-Stegun 6.1.33 */ if (x.compareTo(BigDecimal.ZERO) < 0) { return divideRound(Gamma(x.add(BigDecimal.ONE)), x); } else if (x.doubleValue() > 1.5) { /* Gamma(x) = Gamma(xmin+n) = Gamma(xmin)*Pochhammer(xmin,n). */ int n = (int) (x.doubleValue() - 0.5); BigDecimal xmin1 = x.subtract(new BigDecimal(n)); return multiplyRound(Gamma(xmin1), pochhammer(xmin1, n)); } else { /* apply Abramowitz-Stegun 6.1.33 */ BigDecimal z = x.subtract(BigDecimal.ONE); /* add intermediately 2 digits to the partial sum accumulation */ z = scalePrec(z, 2); MathContext mcloc = new MathContext(z.precision()); /* measure of the absolute error is the relative error in the first, logarithmic term */ double eps = x.ulp().doubleValue() / x.doubleValue(); BigDecimal resul = log(scalePrec(x, 2)).negate(); if (x.compareTo(BigDecimal.ONE) != 0) { BigDecimal gammCompl = BigDecimal.ONE.subtract(gamma(mcloc)); resul = resul.add(multiplyRound(z, gammCompl)); for (int n = 2;; n++) { /* multiplying z^n/n by zeta(n-1) means that the two relative errors add. * so the requirement in the relative error of zeta(n)-1 is that this is somewhat * smaller than the relative error in z^n/n (the absolute error of thelatter is the * absolute error in z) */ BigDecimal c = divideRound(z.pow(n, mcloc), n); MathContext m = new MathContext(err2prec(n * z.ulp().doubleValue() / 2. / z.doubleValue())); c = c.round(m); /* At larger n, zeta(n)-1 is roughly 1/2^n. The product is c/2^n. * The relative error in c is c.ulp/2/c . The error in the product should be small versus eps/10. * Error from 1/2^n is c*err(sigma-1). * We need a relative error of zeta-1 of the order of c.ulp/50/c. This is an absolute * error in zeta-1 of c.ulp/50/c/2^n, and also the absolute error in zeta, because zeta is * of the order of 1. */ if (eps / 100. / c.doubleValue() < 0.01) { m = new MathContext(err2prec(eps / 100. / c.doubleValue())); } else { m = new MathContext(2); } /* zeta(n) -1 */ BigDecimal zetm1 = zeta(n, m).subtract(BigDecimal.ONE); c = multiplyRound(c, zetm1); if (n % 2 == 0) { resul = resul.add(c); } else { resul = resul.subtract(c); } /* alternating sum, so truncating as eps is reached suffices */ if (Math.abs(c.doubleValue()) < eps) { break; } } } /* The relative error in the result is the absolute error in the * input variable times the digamma (psi) value at that point. */ double psi = 0.5772156649; double zdbl = z.doubleValue(); for (int n = 1; n < 5; n++) { psi += zdbl / n / (n + zdbl); } eps = psi * x.ulp().doubleValue() / 2.; mcloc = new MathContext(err2prec(eps)); return exp(resul).round(mcloc); } }
java
{ "resource": "" }
q174017
BigDecimalMath.broadhurstBBP
test
static protected BigDecimal broadhurstBBP(final int n, final int p, final int a[], MathContext mc) { /* Explore the actual magnitude of the result first with a quick estimate. */ double x = 0.0; for (int k = 1; k < 10; k++) { x += a[(k - 1) % 8] / Math.pow(2., p * (k + 1) / 2) / Math.pow((double) k, n); } /* Convert the relative precision and estimate of the result into an absolute precision. */ double eps = prec2err(x, mc.getPrecision()); /* Divide this through the number of terms in the sum to account for error accumulation * The divisor 2^(p(k+1)/2) means that on the average each 8th term in k has shrunk by * relative to the 8th predecessor by 1/2^(4p). 1/2^(4pc) = 10^(-precision) with c the 8term * cycles yields c=log_2( 10^precision)/4p = 3.3*precision/4p with k=8c */ int kmax = (int) (6.6 * mc.getPrecision() / p); /* Now eps is the absolute error in each term */ eps /= kmax; BigDecimal res = BigDecimal.ZERO; for (int c = 0;; c++) { Rational r = new Rational(); for (int k = 0; k < 8; k++) { Rational tmp = new Rational(BigInteger.valueOf(a[k]), BigInteger.valueOf((1 + 8 * c + k)).pow(n)); /* floor( (pk+p)/2) */ int pk1h = p * (2 + 8 * c + k) / 2; tmp = tmp.divide(BigInteger.ONE.shiftLeft(pk1h)); r = r.add(tmp); } if (Math.abs(r.doubleValue()) < eps) { break; } MathContext mcloc = new MathContext(1 + err2prec(r.doubleValue(), eps)); res = res.add(r.BigDecimalValue(mcloc)); } return res.round(mc); }
java
{ "resource": "" }
q174018
BigDecimalMath.scalePrec
test
static public BigDecimal scalePrec(final BigDecimal x, int d) { return x.setScale(d + x.scale()); }
java
{ "resource": "" }
q174019
BigDecimalMath.scalePrec
test
static public BigDecimal scalePrec(final BigDecimal x, final MathContext mc) { final int diffPr = mc.getPrecision() - x.precision(); if (diffPr > 0) { return scalePrec(x, diffPr); } else { return x; } }
java
{ "resource": "" }
q174020
BigDecimalMath.err2prec
test
static public int err2prec(BigDecimal x, BigDecimal xerr) { return err2prec(xerr.divide(x, MathContext.DECIMAL64).doubleValue()); }
java
{ "resource": "" }
q174021
SameDiff.putFunctionForId
test
public void putFunctionForId(String id, DifferentialFunction function) { if (functionInstancesById.containsKey(id)) { throw new ND4JIllegalStateException("Function by id already exists!"); } else if (function instanceof SDVariable) { throw new ND4JIllegalStateException("Function must not be a variable!"); } functionInstancesById.put(id, function); }
java
{ "resource": "" }
q174022
SameDiff.getInputsForFunction
test
public String[] getInputsForFunction(DifferentialFunction function) { if (!incomingArgsReverse.containsKey(function.getOwnName())) throw new ND4JIllegalStateException("Illegal function instance id found " + function.getOwnName()); return incomingArgsReverse.get(function.getOwnName()); }
java
{ "resource": "" }
q174023
SameDiff.updateArrayForVarName
test
public void updateArrayForVarName(String varName, INDArray arr) { if (!variableNameToArr.containsKey(varName)) { throw new ND4JIllegalStateException("Array for " + varName + " does not exist. Please use putArrayForVertexId instead."); } variableNameToArr.put(varName, arr); reverseArrayLookup.put(arr, getVariable(varName)); }
java
{ "resource": "" }
q174024
SameDiff.putShapeForVarName
test
public void putShapeForVarName(String varName, long[] shape) { if (shape == null) { throw new ND4JIllegalStateException("Shape must not be null!"); } if (variableNameToShape.containsKey(varName)) { throw new ND4JIllegalStateException("Shape for " + varName + " already exists!"); } for (int i = 0; i < shape.length; i++) { if (shape[i] < 1) { addAsPlaceHolder(varName); placeHolderOriginalShapes.put(varName, shape); return; } } variableNameToShape.put(varName, shape); }
java
{ "resource": "" }
q174025
SameDiff.associateArrayWithVariable
test
public void associateArrayWithVariable(INDArray arr, SDVariable variable) { if (variable == null) { throw new ND4JIllegalArgumentException("Variable must not be null!"); } if (arr == null) { throw new ND4JIllegalArgumentException("Array must not be null"); } reverseArrayLookup.put(arr, variable); variableNameToArr.put(variable.getVarName(), arr); if (!shapeAlreadyExistsForVarName(variable.getVarName())) putShapeForVarName(variable.getVarName(), arr.shape()); else { updateShapeForVarName(variable.getVarName(), arr.shape()); } }
java
{ "resource": "" }
q174026
SameDiff.getPropertyForFunction
test
public <T> T getPropertyForFunction(DifferentialFunction functionInstance, String propertyName) { if (!propertiesForFunction.containsKey(functionInstance.getOwnName())) { return null; } else { val map = propertiesForFunction.get(functionInstance.getOwnName()); return (T) map.get(propertyName); } }
java
{ "resource": "" }
q174027
SameDiff.addPropertyForFunction
test
public void addPropertyForFunction(DifferentialFunction functionFor, String propertyName, INDArray property) { addPropertyForFunction(functionFor, propertyName, (Object) property); }
java
{ "resource": "" }
q174028
SameDiff.addOutgoingFor
test
public void addOutgoingFor(String[] varNames, DifferentialFunction function) { if (function.getOwnName() == null) throw new ND4JIllegalStateException("Instance id can not be null. Function not initialized properly"); if (outgoingArgsReverse.containsKey(function.getOwnName())) { throw new ND4JIllegalStateException("Outgoing arguments already declared for " + function); } if (varNames == null) throw new ND4JIllegalStateException("Var names can not be null!"); for (int i = 0; i < varNames.length; i++) { if (varNames[i] == null) throw new ND4JIllegalStateException("Variable name elements can not be null!"); } outgoingArgsReverse.put(function.getOwnName(), varNames); outgoingArgs.put(varNames, function); for (val resultName : varNames) { List<DifferentialFunction> funcs = functionOutputFor.get(resultName); if (funcs == null) { funcs = new ArrayList<>(); functionOutputFor.put(resultName, funcs); } funcs.add(function); } }
java
{ "resource": "" }
q174029
SameDiff.addArgsFor
test
public void addArgsFor(String[] variables, DifferentialFunction function) { if (function.getOwnName() == null) throw new ND4JIllegalStateException("Instance id can not be null. Function not initialized properly"); //double check if function contains placeholder args for (val varName : variables) { if (isPlaceHolder(varName)) { placeHolderFunctions.add(function.getOwnName()); } } incomingArgs.put(variables, function); incomingArgsReverse.put(function.getOwnName(), variables); for (val variableName : variables) { List<DifferentialFunction> funcs = functionsArgsFor.get(variableName); if (funcs == null) { funcs = new ArrayList<>(); functionsArgsFor.put(variableName, funcs); } funcs.add(function); } }
java
{ "resource": "" }
q174030
SameDiff.hasArgs
test
public boolean hasArgs(DifferentialFunction function) { val vertexIdArgs = incomingArgsReverse.get(function.getOwnName()); if (vertexIdArgs != null) { val args = incomingArgs.get(vertexIdArgs); if (args != null) return true; } return false; }
java
{ "resource": "" }
q174031
SameDiff.eval
test
public INDArray[] eval(Map<String, INDArray> inputs) { SameDiff execPipeline = dup(); List<DifferentialFunction> opExecAction = execPipeline.exec().getRight(); if (opExecAction.isEmpty()) throw new IllegalStateException("No ops found to execute."); INDArray[] ret = new INDArray[opExecAction.size()]; for (int i = 0; i < ret.length; i++) { val varName = opExecAction.get(i).outputVariables()[0].getVarName(); ret[i] = execPipeline.getArrForVarName(varName); } return ret; }
java
{ "resource": "" }
q174032
SameDiff.one
test
public SDVariable one(String name, int[] shape) { return var(name, ArrayUtil.toLongArray(shape), new ConstantInitScheme('f', 1.0)); }
java
{ "resource": "" }
q174033
SameDiff.onesLike
test
public SDVariable onesLike(String name, SDVariable input) { return f().onesLike(name, input); }
java
{ "resource": "" }
q174034
SameDiff.zerosLike
test
public SDVariable zerosLike(String name, SDVariable input) { return f().zerosLike(name, input); }
java
{ "resource": "" }
q174035
SameDiff.removeArgFromFunction
test
public void removeArgFromFunction(String varName, DifferentialFunction function) { val args = function.args(); for (int i = 0; i < args.length; i++) { if (args[i].getVarName().equals(varName)) { /** * Since we are removing the variable reference * from the arguments we need to update both * the reverse and forward arguments. */ val reverseArgs = incomingArgsReverse.get(function.getOwnName()); incomingArgs.remove(reverseArgs); incomingArgsReverse.remove(function.getOwnName()); val newArgs = new ArrayList<String>(args.length - 1); for (int arg = 0; arg < args.length; arg++) { if (!reverseArgs[arg].equals(varName)) { newArgs.add(reverseArgs[arg]); } } val newArgsArr = newArgs.toArray(new String[newArgs.size()]); incomingArgs.put(newArgsArr, function); incomingArgsReverse.put(function.getOwnName(), newArgsArr); //no further need to scan break; } } }
java
{ "resource": "" }
q174036
SameDiff.setGradientForVariableName
test
public void setGradientForVariableName(String variableName, SDVariable variable) { if (variable == null) { throw new ND4JIllegalStateException("Unable to set null gradient for variable name " + variableName); } gradients.put(variableName, variable); }
java
{ "resource": "" }
q174037
SameDiff.avgPooling3d
test
public SDVariable avgPooling3d(SDVariable[] inputs, Pooling3DConfig pooling3DConfig) { return avgPooling3d(null, inputs, pooling3DConfig); }
java
{ "resource": "" }
q174038
SameDiff.gru
test
public SDVariable gru(String baseName, GRUCellConfiguration configuration) { return new GRUCell(this, configuration).outputVariables(baseName)[0]; }
java
{ "resource": "" }
q174039
SameDiff.exec
test
public List<DifferentialFunction> exec(List<DifferentialFunction> ops) { for (int i = 0; i < ops.size(); i++) { Op op = (Op) ops.get(i); Nd4j.getExecutioner().exec(op); } return ops; }
java
{ "resource": "" }
q174040
SameDiff.whileStatement
test
public While whileStatement(SameDiffConditional sameDiffConditional, SameDiffFunctionDefinition conditionBody, SameDiff.SameDiffFunctionDefinition loopBody , SDVariable[] inputVars) { return While.builder() .inputVars(inputVars) .condition(conditionBody) .predicate(sameDiffConditional) .trueBody(loopBody) .parent(this) .blockName("while-" + UUID.randomUUID().toString()) .build(); }
java
{ "resource": "" }
q174041
SameDiff.exec
test
public Pair<Map<SDVariable, DifferentialFunction>, List<DifferentialFunction>> exec(String functionName) { if (debugMode) { return sameDiffFunctionInstances.get(functionName).enableDebugMode().exec(); } else return sameDiffFunctionInstances.get(functionName).exec(); }
java
{ "resource": "" }
q174042
SameDiff.exec
test
public List<DifferentialFunction> exec(String functionName, List<DifferentialFunction> cachedOps) { return sameDiffFunctionInstances.get(functionName).exec(cachedOps); }
java
{ "resource": "" }
q174043
SameDiff.execBackwardAndEndResult
test
public INDArray execBackwardAndEndResult() { List<DifferentialFunction> backwards = execBackwards().getRight(); DifferentialFunction df = backwards.get(backwards.size() - 1); if (df instanceof Op) { return ((Op) df).z(); } else if (df instanceof DynamicCustomOp) { return ((DynamicCustomOp) df).getOutputArgument(0); } else { return null; } }
java
{ "resource": "" }
q174044
SameDiff.addAsPlaceHolder
test
public void addAsPlaceHolder(String varName) { placeHolderVarNames.add(varName); if (getVariable(varName) != null && getVariable(varName).getShape() != null) { placeHolderOriginalShapes.put(varName, getVariable(varName).getShape()); } }
java
{ "resource": "" }
q174045
CudaMemoryManager.allocate
test
@Override public Pointer allocate(long bytes, MemoryKind kind, boolean initialize) { AtomicAllocator allocator = AtomicAllocator.getInstance(); //log.info("Allocating {} bytes in {} memory...", bytes, kind); if (kind == MemoryKind.HOST) { Pointer ptr = NativeOpsHolder.getInstance().getDeviceNativeOps().mallocHost(bytes, 0); if (ptr == null) throw new RuntimeException("Failed to allocate " + bytes + " bytes from HOST memory"); if (initialize) Pointer.memset(ptr, 0, bytes); return ptr;//allocator.getMemoryHandler().alloc(AllocationStatus.HOST, null, null, initialize).getHostPointer(); } else if (kind == MemoryKind.DEVICE) { Pointer ptr = NativeOpsHolder.getInstance().getDeviceNativeOps().mallocDevice(bytes, null, 0); //log.info("Allocating {} bytes for device_{}", bytes, Nd4j.getAffinityManager().getDeviceForCurrentThread()); if (ptr == null) throw new RuntimeException("Failed to allocate " + bytes + " bytes from DEVICE [" + Nd4j.getAffinityManager().getDeviceForCurrentThread() + "] memory"); if (initialize) { CudaContext context = (CudaContext) AtomicAllocator.getInstance().getDeviceContext().getContext(); int i = NativeOpsHolder.getInstance().getDeviceNativeOps().memsetAsync(ptr, 0, bytes, 0, context.getSpecialStream()); if (i == 0) throw new ND4JIllegalStateException("memset failed on device_" + Nd4j.getAffinityManager().getDeviceForCurrentThread()); context.getSpecialStream().synchronize(); } return ptr; //allocator.getMemoryHandler().alloc(AllocationStatus.HOST, null, null, initialize).getDevicePointer(); } else throw new RuntimeException("Unknown MemoryKind requested: " + kind); }
java
{ "resource": "" }
q174046
DataTypeUtil.lengthForDtype
test
public static int lengthForDtype(DataBuffer.Type type) { switch (type) { case DOUBLE: return 8; case FLOAT: return 4; case INT: return 4; case HALF: return 2; case LONG: return 8; case COMPRESSED: default: throw new IllegalArgumentException("Illegal opType for length"); } }
java
{ "resource": "" }
q174047
DataTypeUtil.getDTypeForName
test
public static String getDTypeForName(DataBuffer.Type allocationMode) { switch (allocationMode) { case DOUBLE: return "double"; case FLOAT: return "float"; case INT: return "int"; case HALF: return "half"; default: return "float"; } }
java
{ "resource": "" }
q174048
DataTypeUtil.getDtypeFromContext
test
public static DataBuffer.Type getDtypeFromContext() { try { lock.readLock().lock(); if (dtype == null) { lock.readLock().unlock(); lock.writeLock().lock(); if (dtype == null) dtype = getDtypeFromContext(Nd4jContext.getInstance().getConf().getProperty("dtype")); lock.writeLock().unlock(); lock.readLock().lock(); } return dtype; } finally { lock.readLock().unlock(); } }
java
{ "resource": "" }
q174049
DefaultOpFactory.getOpNumByName
test
@Override public int getOpNumByName(String opName) { try { DifferentialFunction op = DifferentialFunctionClassHolder.getInstance().getInstance(opName); return op.opNum(); } catch (Exception e) { throw new RuntimeException("OpName failed: [" + opName + "]",e); } }
java
{ "resource": "" }
q174050
BasicWorkspaceManager.destroyAllWorkspacesForCurrentThread
test
@Override public void destroyAllWorkspacesForCurrentThread() { ensureThreadExistense(); List<MemoryWorkspace> workspaces = new ArrayList<>(); workspaces.addAll(backingMap.get().values()); for (MemoryWorkspace workspace : workspaces) { destroyWorkspace(workspace); } System.gc(); }
java
{ "resource": "" }
q174051
BasicWorkspaceManager.printAllocationStatisticsForCurrentThread
test
public synchronized void printAllocationStatisticsForCurrentThread() { ensureThreadExistense(); Map<String, MemoryWorkspace> map = backingMap.get(); log.info("Workspace statistics: ---------------------------------"); log.info("Number of workspaces in current thread: {}", map.size()); log.info("Workspace name: Allocated / external (spilled) / external (pinned)"); for (String key : map.keySet()) { long current = ((Nd4jWorkspace) map.get(key)).getCurrentSize(); long spilled = ((Nd4jWorkspace) map.get(key)).getSpilledSize(); long pinned = ((Nd4jWorkspace) map.get(key)).getPinnedSize(); log.info(String.format("%-26s %8s / %8s / %8s (%11d / %11d / %11d)", (key + ":"), StringUtils.TraditionalBinaryPrefix.long2String(current, "", 2), StringUtils.TraditionalBinaryPrefix.long2String(spilled, "", 2), StringUtils.TraditionalBinaryPrefix.long2String(pinned, "", 2), current, spilled, pinned)); } }
java
{ "resource": "" }
q174052
BaseLevel2.trmv
test
@Override public void trmv(char order, char Uplo, char TransA, char Diag, INDArray A, INDArray X) { if (Nd4j.getExecutioner().getProfilingMode() == OpExecutioner.ProfilingMode.ALL) OpProfiler.getInstance().processBlasCall(false, A, X); // FIXME: int cast if (A.data().dataType() == DataBuffer.Type.DOUBLE) { DefaultOpExecutioner.validateDataType(DataBuffer.Type.DOUBLE, A, X); dtrmv(order, Uplo, TransA, Diag, (int) X.length(), A, (int) A.size(0), X, X.majorStride()); } else { DefaultOpExecutioner.validateDataType(DataBuffer.Type.FLOAT, A, X); strmv(order, Uplo, TransA, Diag, (int) X.length(), A, (int) A.size(0), X, X.majorStride()); } OpExecutionerUtil.checkForAny(X); }
java
{ "resource": "" }
q174053
Nd4jKafkaConsumer.receive
test
public INDArray receive() { if (consumerTemplate == null) consumerTemplate = camelContext.createConsumerTemplate(); return consumerTemplate.receiveBody("direct:receive", INDArray.class); }
java
{ "resource": "" }
q174054
SameDiffOpExecutioner.exec
test
@Override public INDArray exec(Variance accumulation, boolean biasCorrected, int... dimension) { return processOp(accumulation).z(); }
java
{ "resource": "" }
q174055
SameDiffOpExecutioner.thresholdDecode
test
@Override public INDArray thresholdDecode(INDArray encoded, INDArray target) { return backendExecutioner.thresholdDecode(encoded,target); }
java
{ "resource": "" }
q174056
TFGraphMapper.getNodeName
test
public String getNodeName(String name) { //tensorflow adds colons to the end of variables representing input index, this strips those off String ret = name; if(ret.startsWith("^")) ret = ret.substring(1); if(ret.endsWith("/read")) { ret = ret.replace("/read",""); } return ret; }
java
{ "resource": "" }
q174057
NativeOpExecutioner.invoke
test
private void invoke(ScalarOp op, int[] dimension) { dimension = Shape.normalizeAxis(op.x().rank(), dimension); // do tad magic /** * Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)} * and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)} * The first item is the shape information. The second one is the offsets. */ Pair<DataBuffer, DataBuffer> tadBuffers = tadManager.getTADOnlyShapeInfo(op.x(), dimension); Pointer hostTadShapeInfo = tadBuffers.getFirst().addressPointer(); Pointer hostTadOffsets = tadBuffers.getSecond().addressPointer(); Pointer devTadShapeInfoZ = null; Pointer devTadOffsetsZ = null; /** * Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)} * and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)} * The first item is the shape information. The second one is the offsets. * * Note that this is the *result* TAD information. An op is always input (x) and output (z) * for result. * This is for assigning the result to of the operation along * the proper dimension. */ Pair<DataBuffer, DataBuffer> tadBuffersZ = tadManager.getTADOnlyShapeInfo(op.z(), dimension); devTadShapeInfoZ = tadBuffersZ.getFirst().addressPointer(); devTadOffsetsZ = tadBuffersZ.getSecond().addressPointer(); if (extraz.get() == null) extraz.set(new PointerPointer(32)); PointerPointer dummy = extraz.get().put(hostTadShapeInfo, hostTadOffsets, devTadShapeInfoZ, devTadOffsetsZ); if (op.x().data().dataType() == DataBuffer.Type.FLOAT) { loop.execScalarFloat(dummy, op.opNum(), (FloatPointer) op.x().data().addressPointer(), (LongPointer) op.x().shapeInfoDataBuffer().addressPointer(), (FloatPointer) op.z().data().addressPointer(), (LongPointer) op.z().shapeInfoDataBuffer().addressPointer(), (FloatPointer) op.y().data().addressPointer(), (FloatPointer) getPointerForExtraArgs(op), (IntPointer) Nd4j.getConstantHandler().getConstantBuffer(dimension).addressPointer(), dimension.length); } else if (op.x().data().dataType() == DataBuffer.Type.DOUBLE) { loop.execScalarDouble(dummy, op.opNum(), (DoublePointer) op.x().data().addressPointer(), (LongPointer) op.x().shapeInfoDataBuffer().addressPointer(), (DoublePointer) op.z().data().addressPointer(), (LongPointer) op.z().shapeInfoDataBuffer().addressPointer(), (DoublePointer) op.y().data().addressPointer(), (DoublePointer) getPointerForExtraArgs(op), (IntPointer) Nd4j.getConstantHandler().getConstantBuffer(dimension).addressPointer(), dimension.length); } }
java
{ "resource": "" }
q174058
WorkspaceUtils.assertNoWorkspacesOpen
test
public static void assertNoWorkspacesOpen(String msg) throws ND4JWorkspaceException { if (Nd4j.getWorkspaceManager().anyWorkspaceActiveForCurrentThread()) { List<MemoryWorkspace> l = Nd4j.getWorkspaceManager().getAllWorkspacesForCurrentThread(); List<String> workspaces = new ArrayList<>(l.size()); for (MemoryWorkspace ws : l) { if(ws.isScopeActive()) { workspaces.add(ws.getId()); } } throw new ND4JWorkspaceException(msg + " - Open/active workspaces: " + workspaces); } }
java
{ "resource": "" }
q174059
LossMixtureDensity.negativeLogLikelihood
test
private INDArray negativeLogLikelihood(INDArray labels, INDArray alpha, INDArray mu, INDArray sigma) { INDArray labelsMinusMu = labelsMinusMu(labels, mu); INDArray diffsquared = labelsMinusMu.mul(labelsMinusMu).sum(2); INDArray phitimesalphasum = phi(diffsquared, sigma).muli(alpha).sum(1); // result = See Bishop(28,29) INDArray result = Transforms.log(phitimesalphasum).negi(); return result; }
java
{ "resource": "" }
q174060
AtomicState.requestTick
test
public void requestTick(long time, TimeUnit timeUnit) { long timeframeMs = TimeUnit.MILLISECONDS.convert(time, timeUnit); long currentTime = System.currentTimeMillis(); boolean isWaiting = false; // if we have Toe request queued - we' have to wait till it finishes. try { while (isToeScheduled.get() || isToeWaiting.get() || getCurrentState() == AccessState.TOE) { if (!isWaiting) { isWaiting = true; waitingTicks.incrementAndGet(); } Thread.sleep(50); } currentState.set(AccessState.TICK.ordinal()); waitingTicks.decrementAndGet(); tickRequests.incrementAndGet(); } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q174061
AtomicState.tryRequestToe
test
public boolean tryRequestToe() { scheduleToe(); if (isToeWaiting.get() || getCurrentState() == AccessState.TOE) { //System.out.println("discarding TOE"); discardScheduledToe(); return false; } else { //System.out.println("requesting TOE"); discardScheduledToe(); requestToe(); return true; } }
java
{ "resource": "" }
q174062
AtomicState.releaseToe
test
public void releaseToe() { if (getCurrentState() == AccessState.TOE) { if (1 > 0) { //if (toeThread.get() == Thread.currentThread().getId()) { if (toeRequests.decrementAndGet() == 0) { tickRequests.set(0); tackRequests.set(0); currentState.set(AccessState.TACK.ordinal()); } } else throw new IllegalStateException("releaseToe() is called from different thread."); } else throw new IllegalStateException("Object is NOT in Toe state!"); }
java
{ "resource": "" }
q174063
AtomicState.getCurrentState
test
public AccessState getCurrentState() { if (AccessState.values()[currentState.get()] == AccessState.TOE) { return AccessState.TOE; } else { if (tickRequests.get() <= tackRequests.get()) { // TODO: looks like this piece of code should be locked :/ tickRequests.set(0); tackRequests.set(0); return AccessState.TACK; } else return AccessState.TICK; } }
java
{ "resource": "" }
q174064
EnvironmentUtils.buildEnvironment
test
public static Environment buildEnvironment() { Environment environment = new Environment(); environment.setJavaVersion(System.getProperty("java.specification.version")); environment.setNumCores(Runtime.getRuntime().availableProcessors()); environment.setAvailableMemory(Runtime.getRuntime().maxMemory()); environment.setOsArch(System.getProperty("os.arch")); environment.setOsName(System.getProperty("os.opName")); environment.setBackendUsed(Nd4j.getExecutioner().getClass().getSimpleName()); return environment; }
java
{ "resource": "" }
q174065
VectorAggregation.processMessage
test
@Override public void processMessage() { if (clipboard.isTracking(this.originatorId, this.getTaskId())) { clipboard.pin(this); if (clipboard.isReady(this.originatorId, taskId)) { VoidAggregation aggregation = clipboard.unpin(this.originatorId, taskId); // FIXME: probably there's better solution, then "screw-and-forget" one if (aggregation == null) return; VectorCompleteMessage msg = new VectorCompleteMessage(taskId, aggregation.getAccumulatedResult()); msg.setOriginatorId(aggregation.getOriginatorId()); transport.sendMessage(msg); } } }
java
{ "resource": "" }
q174066
BaseDataFetcher.initializeCurrFromList
test
protected void initializeCurrFromList(List<DataSet> examples) { if (examples.isEmpty()) log.warn("Warning: empty dataset from the fetcher"); INDArray inputs = createInputMatrix(examples.size()); INDArray labels = createOutputMatrix(examples.size()); for (int i = 0; i < examples.size(); i++) { inputs.putRow(i, examples.get(i).getFeatureMatrix()); labels.putRow(i, examples.get(i).getLabels()); } curr = new DataSet(inputs, labels); }
java
{ "resource": "" }
q174067
AtomicAllocator.initHostCollectors
test
protected void initHostCollectors() { for (int i = 0; i < configuration.getNumberOfGcThreads(); i++) { ReferenceQueue<BaseDataBuffer> queue = new ReferenceQueue<>(); UnifiedGarbageCollectorThread uThread = new UnifiedGarbageCollectorThread(i, queue); // all GC threads should be attached to default device Nd4j.getAffinityManager().attachThreadToDevice(uThread, getDeviceId()); queueMap.put(i, queue); uThread.start(); collectorsUnified.put(i, uThread); /* ZeroGarbageCollectorThread zThread = new ZeroGarbageCollectorThread((long) i, shouldStop); zThread.start(); collectorsZero.put((long) i, zThread); */ } }
java
{ "resource": "" }
q174068
AtomicAllocator.getPointer
test
@Override public Pointer getPointer(DataBuffer buffer, CudaContext context) { return memoryHandler.getDevicePointer(buffer, context); }
java
{ "resource": "" }
q174069
AtomicAllocator.synchronizeHostData
test
@Override public void synchronizeHostData(DataBuffer buffer) { // we don't want non-committed ops left behind //Nd4j.getExecutioner().push(); // we don't synchronize constant buffers, since we assume they are always valid on host side if (buffer.isConstant()) { return; } // we actually need synchronization only in device-dependant environment. no-op otherwise if (memoryHandler.isDeviceDependant()) { AllocationPoint point = getAllocationPoint(buffer.getTrackingPoint()); if (point == null) throw new RuntimeException("AllocationPoint is NULL"); memoryHandler.synchronizeThreadDevice(Thread.currentThread().getId(), memoryHandler.getDeviceId(), point); } }
java
{ "resource": "" }
q174070
AdaGradUpdater.applyUpdater
test
@Override public void applyUpdater(INDArray gradient, int iteration, int epoch) { if (historicalGradient == null) throw new IllegalStateException("Updater has not been initialized with view state"); double learningRate = config.getLearningRate(iteration, epoch); double epsilon = config.getEpsilon(); historicalGradient.addi(gradient.mul(gradient)); INDArray sqrtHistory = sqrt(historicalGradient.dup(gradientReshapeOrder), false).addi(epsilon); // lr * gradient / (sqrt(sumSquaredGradients) + epsilon) gradient.muli(sqrtHistory.rdivi(learningRate)); }
java
{ "resource": "" }
q174071
GridFlowController.synchronizeToHost
test
@Override public void synchronizeToHost(AllocationPoint point) { if (!point.isConstant() && point.isEnqueued()) { waitTillFinished(point); } super.synchronizeToHost(point); }
java
{ "resource": "" }
q174072
NDArrayIndex.create
test
public static INDArrayIndex[] create(INDArray index) { if (index.isMatrix()) { if (index.rows() > Integer.MAX_VALUE) throw new ND4JArraySizeException(); NDArrayIndex[] ret = new NDArrayIndex[(int) index.rows()]; for (int i = 0; i < index.rows(); i++) { INDArray row = index.getRow(i); val nums = new long[(int) index.getRow(i).columns()]; for (int j = 0; j < row.columns(); j++) { nums[j] = (int) row.getFloat(j); } NDArrayIndex idx = new NDArrayIndex(nums); ret[i] = idx; } return ret; } else if (index.isVector()) { long[] indices = NDArrayUtil.toLongs(index); return new NDArrayIndex[] {new NDArrayIndex(indices)}; } throw new IllegalArgumentException("Passed in ndarray must be a matrix or a vector"); }
java
{ "resource": "" }
q174073
DifferentialFunction.propertiesForFunction
test
public Map<String,Object> propertiesForFunction() { val fields = DifferentialFunctionClassHolder.getInstance().getFieldsForFunction(this); Map<String,Object> ret = new LinkedHashMap<>(); for(val entry : fields.entrySet()) { try { ret.put(entry.getKey(),fields.get(entry.getKey()).get(this)); } catch (IllegalAccessException e) { e.printStackTrace(); } } return ret; }
java
{ "resource": "" }
q174074
DifferentialFunction.hasPlaceHolderInputs
test
public boolean hasPlaceHolderInputs() { val args = args(); for(val arg : args) if(sameDiff.hasPlaceHolderVariables(arg().getVarName())) return true; return false; }
java
{ "resource": "" }
q174075
DifferentialFunction.diff
test
public List<SDVariable> diff(List<SDVariable> i_v1) { List<SDVariable> vals = doDiff(i_v1); if(vals == null){ throw new IllegalStateException("Error executing diff operation: doDiff returned null for op: " + this.opName()); } val outputVars = args(); for(int i = 0; i < vals.size(); i++) { SDVariable var = outputVars[i]; SDVariable grad = var.getGradient(); if(grad != null) { SDVariable gradVar = f().add(grad, vals.get(i)); try { vals.set(i, gradVar); } catch (UnsupportedOperationException e){ throw new UnsupportedOperationException("Use a mutable list when returning values from "+this.getClass().getSimpleName()+".doDiff (e.g. Arrays.asList instead of Collections.singletonList)", e); } sameDiff.setGradientForVariableName(var.getVarName(), gradVar); } else { SDVariable gradVar = vals.get(i); sameDiff.updateVariableNameAndReference(gradVar,var.getVarName() + "-grad"); sameDiff.setGradientForVariableName(var.getVarName(), gradVar); sameDiff.setForwardVariableForVarName(gradVar.getVarName(),var); } } return vals; }
java
{ "resource": "" }
q174076
NDArrayStrings.format
test
public String format(INDArray arr, boolean summarize) { this.scientificFormat = "0."; int addPrecision = this.precision; while (addPrecision > 0) { this.scientificFormat += "#"; addPrecision -= 1; } this.scientificFormat = this.scientificFormat + "E0"; if (this.scientificFormat.length() + 2 > this.padding) this.padding = this.scientificFormat.length() + 2; this.maxToPrintWithoutSwitching = Math.pow(10,this.precision); this.minToPrintWithoutSwitching = 1.0/(this.maxToPrintWithoutSwitching); if (summarize && arr.length() > 1000) return format(arr, 0, true); return format(arr, 0, false); }
java
{ "resource": "" }
q174077
BaseGraphMapper.importGraph
test
@Override public SameDiff importGraph(GRAPH_TYPE tfGraph) { SameDiff diff = SameDiff.create(); ImportState<GRAPH_TYPE,TENSOR_TYPE> importState = new ImportState<>(); importState.setSameDiff(diff); importState.setGraph(tfGraph); val variablesForGraph = variablesForGraph(tfGraph); importState.setVariables(variablesForGraph); //map the names of the nodes while accumulating the vertex ids //for each variable for(Map.Entry<String,TENSOR_TYPE> entry : variablesForGraph.entrySet()) { if(dataTypeForTensor(entry.getValue()) == DataBuffer.Type.UNKNOWN) { val var = importState.getSameDiff().var(entry.getKey(),null,new ZeroInitScheme('c')); //mark as place holder for validating resolution later. if(isPlaceHolder(entry.getValue())) { importState.getSameDiff().addAsPlaceHolder(var.getVarName()); if(var.getShape() != null) importState.getSameDiff().setOriginalPlaceHolderShape(var.getVarName(),var.getShape()); } continue; } val arr = getNDArrayFromTensor(entry.getKey(), entry.getValue(), tfGraph); if(arr != null) { val var = importState.getSameDiff().var(entry.getKey(),arr); //ensure the array is made available for later processing diff.associateArrayWithVariable(arr,var); } else if(getShapeFromTensor(entry.getValue()) == null) { val var = importState.getSameDiff().var(entry.getKey(),null,new ZeroInitScheme('c')); //mark as place holder for validating resolution later. //note that this vertex id can still be a place holder //with a -1 shape. Just because a shape is "known" doesn't mean //that it isn't a place holder. if(isPlaceHolder(entry.getValue())) { val originalShape = getShapeFromTensor(entry.getValue()); importState.getSameDiff().addAsPlaceHolder(var.getVarName()); if(var.getShape() != null) importState.getSameDiff().setOriginalPlaceHolderShape(var.getVarName(),originalShape); } } else { val originalShape = getShapeFromTensor(entry.getValue()); val var = importState.getSameDiff().var(entry.getKey(),originalShape); //mark as place holder for validating resolution later. //note that this vertex id can still be a place holder //with a -1 shape. Just because a shape is "known" doesn't mean //that it isn't a place holder. if(isPlaceHolder(entry.getValue())) { importState.getSameDiff().addAsPlaceHolder(var.getVarName()); importState.getSameDiff().setOriginalPlaceHolderShape(var.getVarName(),originalShape); } } } //setup vertex ids for names //handle mapping vertex ids properly val tfNodesList = getNodeList(tfGraph); for (NODE_TYPE tfNode : tfNodesList) { if(!opsToIgnore().contains(getOpType(tfNode)) || isOpIgnoreException(tfNode)) mapNodeType(tfNode,importState); } return diff; }
java
{ "resource": "" }
q174078
BaseLoader.convert
test
@Override public Blob convert(IComplexNDArray toConvert) throws IOException, SQLException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); Nd4j.writeComplex(toConvert, dos); byte[] bytes = bos.toByteArray(); Connection c = dataSource.getConnection(); Blob b = c.createBlob(); b.setBytes(1, bytes); return b; }
java
{ "resource": "" }
q174079
BaseLoader.loadComplex
test
@Override public IComplexNDArray loadComplex(Blob blob) throws SQLException, IOException { DataInputStream dis = new DataInputStream(blob.getBinaryStream()); return Nd4j.readComplex(dis); }
java
{ "resource": "" }
q174080
BaseLoader.save
test
@Override public void save(IComplexNDArray save, String id) throws IOException, SQLException { doSave(save, id); }
java
{ "resource": "" }
q174081
BaseComplexNDArray.copyRealTo
test
protected void copyRealTo(INDArray arr) { INDArray linear = arr.linearView(); IComplexNDArray thisLinear = linearView(); if (arr.isScalar()) arr.putScalar(0, getReal(0)); else for (int i = 0; i < linear.length(); i++) { arr.putScalar(i, thisLinear.getReal(i)); } }
java
{ "resource": "" }
q174082
BaseComplexNDArray.copyImagTo
test
protected void copyImagTo(INDArray arr) { INDArray linear = arr.linearView(); IComplexNDArray thisLinear = linearView(); if (arr.isScalar()) arr.putScalar(0, getReal(0)); else for (int i = 0; i < linear.length(); i++) { arr.putScalar(i, thisLinear.getImag(i)); } }
java
{ "resource": "" }
q174083
BaseComplexNDArray.epsi
test
@Override public IComplexNDArray epsi(Number other) { IComplexNDArray linear = linearView(); double otherVal = other.doubleValue(); for (int i = 0; i < linearView().length(); i++) { IComplexNumber n = linear.getComplex(i); double real = n.realComponent().doubleValue(); double diff = Math.abs(real - otherVal); if (diff <= Nd4j.EPS_THRESHOLD) linear.putScalar(i, Nd4j.createDouble(1, 0)); else linear.putScalar(i, Nd4j.createDouble(0, 0)); } return this; }
java
{ "resource": "" }
q174084
BaseComplexNDArray.assign
test
@Override public IComplexNDArray assign(IComplexNDArray arr) { if (!arr.isScalar()) LinAlgExceptions.assertSameLength(this, arr); IComplexNDArray linear = linearView(); IComplexNDArray otherLinear = arr.linearView(); for (int i = 0; i < linear.length(); i++) { linear.putScalar(i, otherLinear.getComplex(i)); } return this; }
java
{ "resource": "" }
q174085
BaseComplexNDArray.getRows
test
@Override public IComplexNDArray getRows(int[] rindices) { INDArray rows = Nd4j.create(rindices.length, columns()); for (int i = 0; i < rindices.length; i++) { rows.putRow(i, getRow(rindices[i])); } return (IComplexNDArray) rows; }
java
{ "resource": "" }
q174086
BaseComplexNDArray.putRow
test
@Override public IComplexNDArray putRow(long row, INDArray toPut) { return (IComplexNDArray) super.putRow(row, toPut); }
java
{ "resource": "" }
q174087
BaseComplexNDArray.putColumn
test
@Override public IComplexNDArray putColumn(int column, INDArray toPut) { assert toPut.isVector() && toPut.length() == rows() : "Illegal length for row " + toPut.length() + " should have been " + columns(); IComplexNDArray r = getColumn(column); if (toPut instanceof IComplexNDArray) { IComplexNDArray putComplex = (IComplexNDArray) toPut; for (int i = 0; i < r.length(); i++) { IComplexNumber n = putComplex.getComplex(i); r.putScalar(i, n); } } else { for (int i = 0; i < r.length(); i++) r.putScalar(i, Nd4j.createDouble(toPut.getDouble(i), 0)); } return this; }
java
{ "resource": "" }
q174088
BaseComplexNDArray.sub
test
@Override public IComplexNDArray sub(INDArray other, INDArray result) { return dup().subi(other, result); }
java
{ "resource": "" }
q174089
BaseComplexNDArray.add
test
@Override public IComplexNDArray add(INDArray other, INDArray result) { return dup().addi(other, result); }
java
{ "resource": "" }
q174090
BaseComplexNDArray.subi
test
@Override public IComplexNDArray subi(INDArray other, INDArray result) { IComplexNDArray cOther = (IComplexNDArray) other; IComplexNDArray cResult = (IComplexNDArray) result; if (other.isScalar()) return subi(cOther.getComplex(0), result); if (result == this) Nd4j.getBlasWrapper().axpy(Nd4j.NEG_UNIT, cOther, cResult); else if (result == other) { if (data.dataType() == (DataBuffer.Type.DOUBLE)) { Nd4j.getBlasWrapper().scal(Nd4j.NEG_UNIT.asDouble(), cResult); Nd4j.getBlasWrapper().axpy(Nd4j.UNIT, this, cResult); } else { Nd4j.getBlasWrapper().scal(Nd4j.NEG_UNIT.asFloat(), cResult); Nd4j.getBlasWrapper().axpy(Nd4j.UNIT, this, cResult); } } else { Nd4j.getBlasWrapper().copy(this, result); Nd4j.getBlasWrapper().axpy(Nd4j.NEG_UNIT, cOther, cResult); } return cResult; }
java
{ "resource": "" }
q174091
BaseComplexNDArray.addi
test
@Override public IComplexNDArray addi(INDArray other, INDArray result) { IComplexNDArray cOther = (IComplexNDArray) other; IComplexNDArray cResult = (IComplexNDArray) result; if (cOther.isScalar()) { return cResult.addi(cOther.getComplex(0), result); } if (isScalar()) { return cOther.addi(getComplex(0), result); } if (result == this) { Nd4j.getBlasWrapper().axpy(Nd4j.UNIT, cOther, cResult); } else if (result == other) { Nd4j.getBlasWrapper().axpy(Nd4j.UNIT, this, cResult); } else { INDArray resultLinear = result.linearView(); INDArray otherLinear = other.linearView(); INDArray linear = linearView(); for (int i = 0; i < resultLinear.length(); i++) { resultLinear.putScalar(i, otherLinear.getDouble(i) + linear.getDouble(i)); } } return (IComplexNDArray) result; }
java
{ "resource": "" }
q174092
BaseComplexNDArray.assign
test
@Override public IComplexNDArray assign(Number value) { IComplexNDArray one = linearView(); for (int i = 0; i < one.length(); i++) one.putScalar(i, Nd4j.createDouble(value.doubleValue(), 0)); return this; }
java
{ "resource": "" }
q174093
BaseComplexNDArray.ravel
test
@Override public IComplexNDArray ravel() { if (length() >= Integer.MAX_VALUE) throw new IllegalArgumentException("length() can not be >= Integer.MAX_VALUE"); IComplexNDArray ret = Nd4j.createComplex((int) length(), ordering()); IComplexNDArray linear = linearView(); for (int i = 0; i < length(); i++) { ret.putScalar(i, linear.getComplex(i)); } return ret; }
java
{ "resource": "" }
q174094
Eigen.eigenvalues
test
public static IComplexNDArray eigenvalues(INDArray A) { assert A.rows() == A.columns(); INDArray WR = Nd4j.create(A.rows(), A.rows()); INDArray WI = WR.dup(); Nd4j.getBlasWrapper().geev('N', 'N', A.dup(), WR, WI, dummy, dummy); return Nd4j.createComplex(WR, WI); }
java
{ "resource": "" }
q174095
Eigen.symmetricGeneralizedEigenvalues
test
public static INDArray symmetricGeneralizedEigenvalues(INDArray A, INDArray B) { assert A.rows() == A.columns(); assert B.rows() == B.columns(); INDArray W = Nd4j.create(A.rows()); A = InvertMatrix.invert(B, false).mmuli(A); Nd4j.getBlasWrapper().syev('V', 'L', A, W); return W; }
java
{ "resource": "" }
q174096
BaseLevel1.iamax
test
@Override public int iamax(IComplexNDArray arr) { if (arr.data().dataType() == DataBuffer.Type.DOUBLE) return izamax(arr.length(), arr, BlasBufferUtil.getBlasStride(arr)); return icamax(arr.length(), arr, BlasBufferUtil.getBlasStride(arr)); }
java
{ "resource": "" }
q174097
BaseLevel1.copy
test
@Override public void copy(IComplexNDArray x, IComplexNDArray y) { if (x.data().dataType() == DataBuffer.Type.DOUBLE) zcopy(x.length(), x, BlasBufferUtil.getBlasStride(x), y, BlasBufferUtil.getBlasStride(y)); else ccopy(x.length(), x, BlasBufferUtil.getBlasStride(x), y, BlasBufferUtil.getBlasStride(y)); }
java
{ "resource": "" }
q174098
BaseLevel1.scal
test
@Override public void scal(long N, IComplexNumber alpha, IComplexNDArray X) { if (X.data().dataType() == DataBuffer.Type.DOUBLE) zscal(N, alpha.asDouble(), X, BlasBufferUtil.getBlasStride(X)); else cscal(N, alpha.asFloat(), X, BlasBufferUtil.getBlasStride(X)); }
java
{ "resource": "" }
q174099
DistributedSgDotMessage.processMessage
test
@Override public void processMessage() { // this only picks up new training round //log.info("sI_{} Processing DistributedSgDotMessage taskId: {}", transport.getShardIndex(), getTaskId()); SkipGramRequestMessage sgrm = new SkipGramRequestMessage(w1, w2, rowsB, codes, negSamples, alpha, 119); if (negSamples > 0) { // unfortunately we have to get copy of negSamples here int negatives[] = Arrays.copyOfRange(rowsB, codes.length, rowsB.length); sgrm.setNegatives(negatives); } sgrm.setTaskId(this.taskId); sgrm.setOriginatorId(this.getOriginatorId()); // FIXME: get rid of THAT SkipGramTrainer sgt = (SkipGramTrainer) trainer; sgt.pickTraining(sgrm); //TODO: make this thing a single op, even specialOp is ok // we calculate dot for all involved rows int resultLength = codes.length + (negSamples > 0 ? (negSamples + 1) : 0); INDArray result = Nd4j.createUninitialized(resultLength, 1); int e = 0; for (; e < codes.length; e++) { double dot = Nd4j.getBlasWrapper().dot(storage.getArray(WordVectorStorage.SYN_0).getRow(w2), storage.getArray(WordVectorStorage.SYN_1).getRow(rowsB[e])); result.putScalar(e, dot); } // negSampling round for (; e < resultLength; e++) { double dot = Nd4j.getBlasWrapper().dot(storage.getArray(WordVectorStorage.SYN_0).getRow(w2), storage.getArray(WordVectorStorage.SYN_1_NEGATIVE).getRow(rowsB[e])); result.putScalar(e, dot); } if (voidConfiguration.getExecutionMode() == ExecutionMode.AVERAGING) { // just local bypass DotAggregation dot = new DotAggregation(taskId, (short) 1, shardIndex, result); dot.setTargetId((short) -1); dot.setOriginatorId(getOriginatorId()); transport.putMessage(dot); } else if (voidConfiguration.getExecutionMode() == ExecutionMode.SHARDED) { // send this message to everyone DotAggregation dot = new DotAggregation(taskId, (short) voidConfiguration.getNumberOfShards(), shardIndex, result); dot.setTargetId((short) -1); dot.setOriginatorId(getOriginatorId()); transport.sendMessage(dot); } }
java
{ "resource": "" }