List of usage examples for java.lang Double MIN_VALUE
double MIN_VALUE
To view the source code for java.lang Double MIN_VALUE.
Click Source Link
From source file:org.mcisb.kinetics.KineticsCalculator.java
/** * //w w w. j av a 2s . c om * @param substrateConcentrations * @param initialRates * @param vMax * @param kM * @return double[] * @throws SingularMatrixException */ private static double[] levenbergMarquardt(final double[] substrateConcentrations, final double[] initialRates, final double vMax, final double kM) throws SingularMatrixException { final double TOLERANCE_X = 1e-9; final double TOLERANCE_F = 1e-6; final double MAX_ITERATIONS = 100; double lambda = 1e-3; double[] parameters = new double[] { vMax, kM }; double[] parametersChange = new double[parameters.length]; double[] errorsOld = new double[substrateConcentrations.length]; Arrays.fill(errorsOld, Double.POSITIVE_INFINITY); double[] errorsNew = null; final double[][] j = new double[substrateConcentrations.length][parameters.length]; for (int i = 0; i < MAX_ITERATIONS; i++) { parameters = MathUtils.add(parameters, parametersChange); final double[] f = new double[substrateConcentrations.length]; for (int s = 0; s < substrateConcentrations.length; s++) { final double denominator = Math.max(parameters[1] + substrateConcentrations[s], Math.sqrt(Double.MIN_VALUE)); f[s] = parameters[0] * substrateConcentrations[s] / denominator; j[s][0] = substrateConcentrations[s] / denominator; j[s][1] = -parameters[0] * substrateConcentrations[s] / Math.pow(denominator, 2); } final double[][] jtj = MathUtils.multiply(MathUtils.transpose(j), j); final double[][] im = MathUtils.getIdentityMatrix(parameters.length); final double[][] iml = MathUtils.scalarMultiply(im, lambda); final double[][] jtjiml = MathUtils.add(jtj, iml); final double[][] c = MathUtils.inverse(jtjiml); errorsNew = MathUtils.subtract(initialRates, f); parametersChange = MathUtils.multiply(MathUtils.multiply(c, MathUtils.transpose(j)), errorsNew); double error = 0; for (int s = 0; s < parameters.length; s++) { error = Math.max(error, Math.abs(parametersChange[s] / parameters[s])); } if (MathUtils.twoNorm(errorsNew) > MathUtils.twoNorm(errorsOld)) { lambda *= 10; } else { lambda /= 10; if (error < TOLERANCE_X || ((MathUtils.twoNorm(errorsOld) - MathUtils.twoNorm(errorsNew)) / MathUtils.twoNorm(errorsOld) < TOLERANCE_F)) { break; } } errorsOld = errorsNew; } final double vMaxRecalculated = parameters[0]; final double kMRecalculated = parameters[1]; final double sigma = MathUtils.dot(errorsNew, errorsNew) / (substrateConcentrations.length - parameters.length); final double[][] c = MathUtils.scalarMultiply( MathUtils.inverse(MathUtils.multiply(MathUtils.transpose(j), j), Double.MIN_VALUE), sigma); return new double[] { vMaxRecalculated, kMRecalculated, Math.sqrt(c[0][0]), Math.sqrt(c[1][1]) }; }
From source file:geogebra.kernel.EquationSolver.java
private static double findZero(double t, double target, double eqn[]) { double slopeqn[] = { eqn[1], 2 * eqn[2], 3 * eqn[3] }; double slope; double origdelta = 0; double origt = t; while (true) { slope = solveEqn(slopeqn, 2, t); if (slope == 0.0) // At a local minima - must return return t; double y = solveEqn(eqn, 3, t); if (y == 0.0) // Found it! - return it return t; // assert(slope != 0 && y != 0); double delta = -(y / slope); // assert(delta != 0); if (origdelta == 0.0) { origdelta = delta;//from w w w .j a v a 2 s . c om } if (t < target) { if (delta < 0) return t; } else if (t > target) { if (delta > 0) return t; } else return (delta > 0 ? (target + java.lang.Double.MIN_VALUE) : (target - java.lang.Double.MIN_VALUE)); double newt = t + delta; if (t == newt) // The deltas are so small that we aren't moving... return t; if (delta * origdelta < 0) { // We have reversed our path. int tag = (origt < t ? getTag(target, origt, t) : getTag(target, t, origt)); if (tag != INSIDE) // Local minima found away from target - return the middle return (origt + t) / 2; // Local minima somewhere near target - move to target // and let the slope determine the resulting t. t = target; } else { t = newt; } } }
From source file:com.udojava.evalex.Expression.java
/** * Creates a new expression instance from an expression string with a given * default match context./*from w w w . j av a 2 s. co m*/ * * @param expression The expression. E.g. <code>"2.4*sin(3)/(2-4)"</code> or * <code>"sin(y)>0 & max(z, 3)>3"</code> */ public Expression(String expression, LinkedList<String> hist, Variables vars) { this.history = hist; this.expression = expression; mainVars = vars; addOperator(new Operator("+", 20, true, "Addition") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.ARRAY) { MyComplex vo = new MyComplex(v1.list); vo.list.add(v2); return vo; } return v1.add(v2); } }); addOperator(new Operator("-", 20, true, "Subtraction") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.ARRAY) { MyComplex vo = new MyComplex(v1.list); vo.list.removeIf(o -> o.equals(v2)); return vo; } return v1.subtract(v2); } }); addOperator(new Operator("*", 30, true, "Real number multiplication") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return v1.multiply(v2); } }); addOperator(new Operator("/", 30, true, "Real number division") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return v1.divide(v2); } }); addOperator(new Operator("%", 30, true, "Remainder of integer division") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { double r = v1.real % v2.real; return new MyComplex(r); } }); addOperator( new Operator("^", 40, false, "Exponentation. See: https://en.wikipedia.org/wiki/Exponentiation") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return v1.pow(v2); } }); addOperator(new Operator("&&", 4, false, "Logical AND. Evaluates to 1 if both operands are not 0") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { boolean b1 = (v1.real == 0.0 && v2.real == 0.0); return new MyComplex(b1 ? 1 : 0); } }); addOperator(new Operator("||", 2, false, "Logical OR. Evaluates to 0 if both operands are 0") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { boolean b1 = (v1.real == 0.0 && v2.real == 0.0); return new MyComplex(b1 ? 0 : 1); } }); addOperator(new Operator(">", 10, false, "Greater than. See: See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real > v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() > v2.abs() ? 1 : 0); } } }); addOperator(new Operator(">=", 10, false, "Greater or equal") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real >= v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() >= v2.abs() ? 1 : 0); } } }); addOperator(new Operator("<", 10, false, "Less than. See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real < v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() < v2.abs() ? 1 : 0); } } }); addOperator(new Operator("<=", 10, false, "less or equal") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real <= v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() <= v2.abs() ? 1 : 0); } } }); addOperator(new Operator("->", 7, false, "Set variable v to new value ") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1 instanceof PitDecimal) { PitDecimal target = (PitDecimal) v1; String s = target.getVarToken(); setVariable(s, v2); return v2; } throw new ExpressionException("LHS not variable"); } }); addOperator(new Operator("=", 7, false, "Equality") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real == v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() == v2.abs() ? 1 : 0); } } }); addOperator(new Operator("!=", 7, false, "Inequality. See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) { return new MyComplex(v1.real != v2.real ? 1 : 0); } else { return new MyComplex(v1.abs() != v2.abs() ? 1 : 0); } } }); addOperator( new Operator("or", 7, false, "Bitwise OR. See: https://en.wikipedia.org/wiki/Logical_disjunction") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real | (long) v2.real); } }); addOperator(new Operator("and", 7, false, "Bitwise AND. See: https://en.wikipedia.org/wiki/Logical_conjunction") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real & (long) v2.real); } }); addOperator(new Operator("xor", 7, false, "Bitwise XOR, See: https://en.wikipedia.org/wiki/Exclusive_or") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real ^ (long) v2.real); } }); addOperator(new Operator("!", 50, true, "Factorial. See https://en.wikipedia.org/wiki/Factorial") { public BigInteger factorial(long n) { BigInteger factorial = BigInteger.ONE; for (long i = 1; i <= n; i++) { factorial = factorial.multiply(BigInteger.valueOf(i)); } return factorial; } @Override public MyComplex eval(MyComplex v1, MyComplex v2) { BigInteger fact = factorial((long) v1.real); return new MyComplex(fact, BigInteger.ZERO); } }); addOperator(new Operator("~", 8, false, "Bitwise negation") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { BigInteger bi = v2.toBigIntegerReal(); int c = bi.bitLength(); if (c == 0) { return new MyComplex(1); } for (int s = 0; s < c; s++) { bi = bi.flipBit(s); } return new MyComplex(bi); } }); addOperator(new Operator("shl", 8, false, "Left Bit shift") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real << (long) v2.real); } }); addOperator(new Operator("shr", 8, false, "Right bit shift") { @Override public MyComplex eval(MyComplex v1, MyComplex v2) { return new MyComplex((long) v1.real >>> (long) v2.real); } }); addFunction(new Function("NOT", 1, "evaluates to 0 if argument != 0") { @Override public MyComplex eval(List<MyComplex> parameters) { boolean zero = parameters.get(0).abs() == 0; return new MyComplex(zero ? 1 : 0); } }); addFunction(new Function("RND", 2, "Give random number in the range between first and second argument") { @Override public MyComplex eval(List<MyComplex> parameters) { double low = parameters.get(0).real; double high = parameters.get(1).real; return new MyComplex(low + Math.random() * (high - low)); } }); MersenneTwister mers = new MersenneTwister(System.nanoTime()); addFunction(new Function("MRS", 0, "Mersenne twister random generator") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(mers.nextDouble()); } }); addFunction(new Function("BIN", 2, "Binomial Coefficient 'n choose k'") { @Override public MyComplex eval(List<MyComplex> parameters) { int n = (int) parameters.get(0).real; int k = (int) parameters.get(1).real; double d = CombinatoricsUtils.binomialCoefficientDouble(n, k); return new MyComplex(d); } }); addFunction(new Function("STIR", 2, "Stirling number of 2nd kind: http://mathworld.wolfram.com/StirlingNumberoftheSecondKind.html") { @Override public MyComplex eval(List<MyComplex> parameters) { int n = (int) parameters.get(0).real; int k = (int) parameters.get(1).real; double d = CombinatoricsUtils.stirlingS2(n, k); return new MyComplex(d); } }); addFunction(new Function("SIN", 1, "Sine function") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).sin(); } }); addFunction(new Function("COS", 1, "Cosine function") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).cos(); } }); addFunction(new Function("TAN", 1, "Tangent") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).tan(); } }); addFunction(new Function("ASIN", 1, "Reverse Sine") { // added by av @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).asin(); } }); addFunction(new Function("ACOS", 1, "Reverse Cosine") { // added by av @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).acos(); } }); addFunction(new Function("ATAN", 1, "Reverse Tangent") { // added by av @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).atan(); } }); addFunction(new Function("SINH", 1, "Hyperbolic Sine") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).sinh(); } }); addFunction(new Function("COSH", 1, "Hyperbolic Cosine") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).cosh(); } }); addFunction(new Function("TANH", 1, "Hyperbolic Tangent") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).tanh(); } }); addFunction(new Function("RAD", 1, "Transform degree to radian") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.toRadians(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("DEG", 1, "Transform radian to degree") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.toDegrees(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("MAX", -1, "Find the biggest value in a list") { @Override public MyComplex eval(List<MyComplex> parameters) { MyComplex save = new MyComplex(Double.MIN_VALUE); if (parameters.size() == 0) { throw new ExpressionException("MAX requires at least one parameter"); } // if (parameters.get(0).type == ValueType.ARRAY) // parameters = parameters.get(0).list; if (parameters.get(0).type == ValueType.COMPLEX) { for (MyComplex parameter : parameters) { if (parameter.abs() > save.abs()) { save = parameter; } } save.type = ValueType.COMPLEX; } else { for (MyComplex parameter : parameters) { if (parameter.real > save.real) { save = parameter; } } save.type = ValueType.REAL; } return save; } }); /////////////////////////////////////////////////////// addFunction(new Function("IF", 3, "Conditional: give param3 if param1 is 0, otherwise param2") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.get(0).real == 0.0) { return parameters.get(2); } return parameters.get(1); } }); addFunction(new Function("PERC", 2, "Get param1 percent of param2") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).divide(new MyComplex(100)).multiply(parameters.get(1)); } }); addFunction(new Function("PER", 2, "How many percent is param1 of param2") { @Override public MyComplex eval(List<MyComplex> parameters) { return parameters.get(0).multiply(new MyComplex(100)).divide(parameters.get(1)); } }); addFunction(new Function("H", 1, "Evaluate _history element") { @Override public MyComplex eval(List<MyComplex> parameters) { int i = (int) parameters.get(0).real; Expression ex = new Expression(history.get(i), history, mainVars); return ex.eval(); } }); addFunction(new Function("MERS", 1, "Calculate Mersenne Number") { @Override public MyComplex eval(List<MyComplex> parameters) { MyComplex p = parameters.get(0); return new MyComplex(2).pow(p).subtract(new MyComplex(1)); } }); addFunction(new Function("GCD", 2, "Find greatest common divisor of 2 values") { @Override public MyComplex eval(List<MyComplex> parameters) { double a = parameters.get(0).real; double b = parameters.get(1).real; long r = ArithmeticUtils.gcd((long) a, (long) b); return new MyComplex(r); } }); addFunction(new Function("LCM", 2, "Find least common multiple of 2 values") { @Override public MyComplex eval(List<MyComplex> parameters) { double a = parameters.get(0).real; double b = parameters.get(1).real; long r = ArithmeticUtils.lcm((long) a, (long) b); return new MyComplex(r); } }); addFunction(new Function("AMEAN", -1, "Arithmetic mean of a set of values") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.size() == 0) { throw new ExpressionException("MEAN requires at least one parameter"); } Mean m = new Mean(); double[] d = MyComplex.getRealArray(parameters); double d2 = m.evaluate(d); return new MyComplex(d2); } }); // addFunction(new Function("BYT", -1, // "Value from sequence of bytes") // { // @Override // public MyComplex eval (List<MyComplex> parameters) // { // if (parameters.size() == 0) // { // return MyComplex.ZERO; // } // BigInteger res = BigInteger.ZERO; // for (MyComplex parameter : parameters) // { // if (parameter.intValue() < 0 || parameter.intValue() > 255) // { // throw new ExpressionException("not a byte value"); // } // res = res.shiftLeft(8); // res = res.or(parameter.toBigInteger()); // } // return new MyComplex(res, BigInteger.ZERO); // } // }); addFunction(new Function("SEQ", 3, "Generate Sequence p1=start, p2=step, p3=count") { @Override public MyComplex eval(List<MyComplex> parameters) { double start = parameters.get(0).real; ArrayList<MyComplex> arr = new ArrayList<>(); for (int s = 0; s < (int) (parameters.get(2).real); s++) { arr.add(new MyComplex(start)); start += parameters.get(1).real; } return new MyComplex(arr); } }); addFunction(new Function("PROD", -1, "Product of real values") { @Override public MyComplex eval(List<MyComplex> parameters) { Product p = new Product(); double[] d = MyComplex.getRealArray(parameters); return new MyComplex(p.evaluate(d)); } }); addFunction(new Function("SUM", -1, "Sum of values") { @Override public MyComplex eval(List<MyComplex> parameters) { Sum p = new Sum(); double[] d = MyComplex.getRealArray(parameters); return new MyComplex(p.evaluate(d)); } }); addFunction(new Function("ANG", 1, "Angle phi of complex number in radians") { @Override public MyComplex eval(List<MyComplex> parameters) { double b = parameters.get(0).angle(); return new MyComplex(b); } }); addFunction(new Function("IM", 1, "Get imaginary part") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(parameters.get(0).imaginary); } }); addFunction(new Function("RE", 1, "Get real part") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(parameters.get(0).real); } }); addFunction(new Function("POL", 2, "Make complex number from polar coords. angle is first arg") { @Override public MyComplex eval(List<MyComplex> parameters) { double angle = parameters.get(0).real; double len = parameters.get(1).real; Complex c = ComplexUtils.polar2Complex(len, angle); return new MyComplex(c); } }); addFunction(new Function("GMEAN", -1, "Geometric mean of a set of values") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.size() == 0) { throw new ExpressionException("MEAN requires at least one parameter"); } GeometricMean m = new GeometricMean(); double[] d = MyComplex.getRealArray(parameters); double d2 = m.evaluate(d); return new MyComplex(d2); } }); addFunction(new Function("HMEAN", -1, "Harmonic mean of a set of values") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.size() == 0) { throw new ExpressionException("MEAN requires at least one parameter"); } MyComplex res = new MyComplex(0); int num = 0; for (MyComplex parameter : parameters) { res = res.add(new MyComplex(1).divide(parameter)); num++; } res = new MyComplex(res.abs()); return new MyComplex(num).divide(res); } }); addFunction(new Function("VAR", -1, "Variance of a set of values") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.size() == 0) { throw new ExpressionException("MEAN requires at least one parameter"); } double[] arr = new double[parameters.size()]; for (int s = 0; s < parameters.size(); s++) { arr[s] = parameters.get(s).real; } return new MyComplex(variance(arr)); } }); addFunction(new Function("NPR", 1, "Next prime number greater or equal the argument") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(nextPrime((int) parameters.get(0).real)); } }); addFunction(new Function("NSWP", 1, "Swap nibbles") { @Override public MyComplex eval(List<MyComplex> parameters) { BigInteger bi = parameters.get(0).toBigIntegerReal(); String s = bi.toString(16); s = new StringBuilder(s).reverse().toString(); return new MyComplex(new BigInteger(s, 16), BigInteger.ZERO); } }); addFunction(new Function("BSWP", 1, "Swap bytes") { @Override public MyComplex eval(List<MyComplex> parameters) { BigInteger bi = parameters.get(0).toBigIntegerReal(); String s = bi.toString(16); while (s.length() % 4 != 0) { s = s + "0"; } if (bi.intValue() < 256) { s = "00" + s; } s = Misc.reverseHex(s); return new MyComplex(new BigInteger(s, 16), BigInteger.ZERO); } }); addFunction(new Function("PYT", 2, "Pythagoras's result = sqrt(param1^2+param2^2) https://en.wikipedia.org/wiki/Pythagorean_theorem") { @Override public MyComplex eval(List<MyComplex> par) { double a = par.get(0).real; double b = par.get(1).real; return new MyComplex(Math.sqrt(a * a + b * b)); } }); addFunction(new Function("FIB", 1, "Fibonacci number") { // --Commented out by Inspection (2/19/2017 7:46 PM):private final Operator exp = operators.get("^"); @Override public MyComplex eval(List<MyComplex> par) { return Misc.iterativeFibonacci((int) par.get(0).real); } }); /////////////////////////////////////////////// addFunction(new Function("MIN", -1, "Find the smallest in a list of values") { @Override public MyComplex eval(List<MyComplex> parameters) { MyComplex save = new MyComplex(Double.MAX_VALUE); if (parameters.size() == 0) { throw new ExpressionException("MAX requires at least one parameter"); } if (parameters.get(0).type == ValueType.COMPLEX) { for (MyComplex parameter : parameters) { if (parameter.abs() < save.abs()) { save = parameter; } } save.type = ValueType.COMPLEX; } else { for (MyComplex parameter : parameters) { if (parameter.real < save.real) { save = parameter; } } save.type = ValueType.REAL; } return save; } }); addFunction(new Function("ABS", 1, "Get absolute value of a number") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(parameters.get(0).abs()); } }); addFunction(new Function("LN", 1, "Logarithm base e of the argument") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.log(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("LOG", 1, "Logarithm base 10 of the argument") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.log10(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("FLOOR", 1, "Rounds DOWN to nearest Integer") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.floor(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("CEIL", 1, "Rounds UP to nearest Integer") { @Override public MyComplex eval(List<MyComplex> parameters) { double d = Math.ceil(parameters.get(0).real); return new MyComplex(d); } }); addFunction(new Function("ROU", 1, "Rounds to nearest Integer") { @Override public MyComplex eval(List<MyComplex> parameters) { int d = (int) (parameters.get(0).real + 0.5); return new MyComplex(d); } }); addFunction(new Function("SQRT", 1, "Square root") { @Override public MyComplex eval(List<MyComplex> parameters) { MyComplex p = parameters.get(0); if (p.type == ValueType.REAL) { return new MyComplex(Math.sqrt(p.real)); } return p.sqrt(); } }); addFunction(new Function("ARR", -1, "Create array") { @Override public MyComplex eval(List<MyComplex> parameters) { return new MyComplex(parameters); } }); addFunction(new Function("POLY", -1, "Treat array as Polynom") { @Override public MyComplex eval(List<MyComplex> parameters) { double[] d = MyComplex.getRealArray(parameters); PolynomialFunction p = new PolynomialFunction(d); return new MyComplex(p); } }); addFunction(new Function("DRVE", -1, "Make derivative of polynomial") { @Override public MyComplex eval(List<MyComplex> parameters) { PolynomialFunction p; if (parameters.get(0).isPoly()) { p = new PolynomialFunction(parameters.get(0).getRealArray()); } else { double[] d = MyComplex.getRealArray(parameters); p = new PolynomialFunction(d); } return new MyComplex(p.polynomialDerivative()); } }); addFunction(new Function("ADRVE", -1, "Make antiderivative of polynomial. Constant is always zero") { @Override public MyComplex eval(List<MyComplex> parameters) { PolynomialFunction p; if (parameters.get(0).isPoly()) { p = new PolynomialFunction(parameters.get(0).getRealArray()); } else { double[] d = MyComplex.getRealArray(parameters); p = new PolynomialFunction(d); } return new MyComplex(Misc.antiDerive(p)); } }); addFunction(new Function("PVAL", 2, "Compute value of polynom for the given argument.") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.get(0).isPoly()) { PolynomialFunction p = new PolynomialFunction(parameters.get(0).getRealArray()); double v = p.value(parameters.get(1).real); return new MyComplex(v); } throw new ExpressionException("first arg must be polynomial"); } }); addFunction(new Function("INTGR", 3, "Numerical integration") { @Override public MyComplex eval(List<MyComplex> parameters) { if (parameters.get(0).isPoly()) { PolynomialFunction p = new PolynomialFunction(parameters.get(0).getRealArray()); double start = parameters.get(1).real; double end = parameters.get(2).real; SimpsonIntegrator si = new SimpsonIntegrator(); double d = si.integrate(1000, p, start, end); return new MyComplex(d); } throw new ExpressionException("first arg must be polynomial"); } }); }
From source file:shapeReduction.ShapeReductorByClustering.java
private double findMaxRadiusInThisShape(PointIfc center) { double maxRadius = Double.MIN_VALUE; for (int i = 0; i < shapeCollectionPoints.getSize(); i++) { PointIfc point = shapeCollectionPoints.getPointFromId(i).getCoords(); double distance = MathTools.computeDistance(center.getCoords(), point.getCoords()); if (distance > maxRadius) { maxRadius = distance;//from w w w .j a va 2s. c om } } return maxRadius; }
From source file:edu.rice.cs.bioinfo.programs.phylonet.algos.network.InferMLNetworkFromSequences.java
protected double findNonUltrametricOptimalBranchLength(final String[] gtTaxa, final Network<Object> speciesNetwork, final Map<String, String> allele2species, final List<Tuple<char[], Integer>> sequences, final RateModel rModel, final double theta) { boolean continueRounds = true; // keep trying to improve network for (NetNode<Object> node : speciesNetwork.dfs()) { for (NetNode<Object> parent : node.getParents()) { node.setParentDistance(parent, theta); if (node.isNetworkNode()) { //node.setParentDistance(parent,0.0); node.setParentProbability(parent, 0.5); }/*from w w w. j a v a 2 s . com*/ } } //long start = System.currentTimeMillis(); double initalProb = computeProbability(gtTaxa, speciesNetwork, allele2species, sequences, rModel, theta); //System.out.println(initalProb); //System.out.print("\n"+(System.currentTimeMillis()-start)); //computeProbability(speciesNetwork, distinctTrees, species2alleles, nbTreeAndCountAndBinaryIDList); final Container<Double> lnGtProbOfSpeciesNetwork = new Container<Double>(initalProb); // records the GTProb of the network at all times //final Container<Integer> callCount = new Container<Integer>(0); int roundIndex = 0; for (; roundIndex < _maxRounds && continueRounds; roundIndex++) { /* * Prepare a random ordering of network edge examinations each of which attempts to change a branch length or hybrid prob to improve the GTProb score. */ double lnGtProbLastRound = lnGtProbOfSpeciesNetwork.getContents(); List<Proc> assigmentActions = new ArrayList<Proc>(); // store adjustment commands here. Will execute them one by one later. for (final NetNode<Object> parent : edu.rice.cs.bioinfo.programs.phylonet.structs.network.util.Networks .postTraversal(speciesNetwork)) { for (final NetNode<Object> child : parent.getChildren()) { assigmentActions.add(new Proc() { public void execute() { UnivariateFunction functionToOptimize = new UnivariateFunction() { public double value(double suggestedBranchLength) { //System.out.print(" l/"+child.getName()+" "); //callCount.setContents(callCount.getContents()+1); double incumbentBranchLength = child.getParentDistance(parent); child.setParentDistance(parent, suggestedBranchLength); double lnProb = computeProbability(gtTaxa, speciesNetwork, allele2species, sequences, rModel, theta); //System.out.println("Changing branch ("+parent.getName()+","+child.getName()+") to " + suggestedBranchLength); //System.out.println(network2String(speciesNetwork)+": " + lnProb); if (lnProb > lnGtProbOfSpeciesNetwork.getContents()) // did improve, keep change { lnGtProbOfSpeciesNetwork.setContents(lnProb); } else // didn't improve, roll back change { child.setParentDistance(parent, incumbentBranchLength); } return lnProb; } }; BrentOptimizer optimizer = new BrentOptimizer(_Brent1, _Brent2); // very small numbers so we control when brent stops, not brent. try { optimizer.optimize(_maxTryPerBranch, functionToOptimize, GoalType.MAXIMIZE, Double.MIN_VALUE, _maxBranchLength); } catch (TooManyEvaluationsException e) // _maxAssigmentAttemptsPerBranchParam exceeded { } } }); } } for (final NetNode<Object> child : speciesNetwork.getNetworkNodes()) // find every hybrid node { Iterator<NetNode<Object>> hybridParents = child.getParents().iterator(); final NetNode hybridParent1 = hybridParents.next(); final NetNode hybridParent2 = hybridParents.next(); assigmentActions.add(new Proc() { public void execute() { UnivariateFunction functionToOptimize = new UnivariateFunction() { public double value(double suggestedProb) { //callCount.setContents(callCount.getContents()+1); //System.out.print(" p/"+child.getName()+" "); double incumbentHybridProbParent1 = child.getParentProbability(hybridParent1); child.setParentProbability(hybridParent1, suggestedProb); child.setParentProbability(hybridParent2, 1.0 - suggestedProb); double lnProb = computeProbability(gtTaxa, speciesNetwork, allele2species, sequences, rModel, theta); //System.out.println("Changing node probability to "+ suggestedProb); //System.out.println(network2String(speciesNetwork)+": " + lnProb); //System.out.println(Math.abs(computeProbability(speciesNetwork, distinctTrees, species2alleles, nbTreeAndCountAndBinaryIDList) - lnProb)); if (lnProb > lnGtProbOfSpeciesNetwork.getContents()) // change improved GTProb, keep it { lnGtProbOfSpeciesNetwork.setContents(lnProb); } else // change did not improve, roll back { child.setParentProbability(hybridParent1, incumbentHybridProbParent1); child.setParentProbability(hybridParent2, 1.0 - incumbentHybridProbParent1); } return lnProb; } }; BrentOptimizer optimizer = new BrentOptimizer(_Brent1, _Brent2); // very small numbers so we control when brent stops, not brent. try { optimizer.optimize(_maxTryPerBranch, functionToOptimize, GoalType.MAXIMIZE, 0, 1.0); } catch (TooManyEvaluationsException e) // _maxAssigmentAttemptsPerBranchParam exceeded { } //System.out.println(network2String(speciesNetwork) + " : " + lnGtProbOfSpeciesNetwork.getContents()); } }); } // add hybrid probs to hybrid edges if (_seed == null) { //Collections.shuffle(assigmentActions); } for (Proc assigment : assigmentActions) // for each change attempt, perform attempt { assigment.execute(); } if (((double) lnGtProbOfSpeciesNetwork.getContents()) == lnGtProbLastRound) // if no improvement was made wrt to last around, stop trying to find a better assignment { continueRounds = false; } else if (lnGtProbOfSpeciesNetwork.getContents() > lnGtProbLastRound) // improvement was made, ensure it is large enough wrt to improvement threshold to continue searching { double improvementPercentage = Math.pow(Math.E, (lnGtProbOfSpeciesNetwork.getContents() - lnGtProbLastRound)) - 1.0; // how much did we improve over last round if (improvementPercentage < _improvementThreshold) // improved, but not enough to keep searching { continueRounds = false; } } else { throw new IllegalStateException("Should never have decreased prob."); } } //System.out.println(callCount.getContents()); //System.out.println(computeProbability(speciesNetwork, distinctTrees, species2alleles, nbTreeAndCountAndBinaryIDList) + " vs. " + lnGtProbOfSpeciesNetwork.getContents()); return lnGtProbOfSpeciesNetwork.getContents(); }
From source file:org.fhcrc.cpl.viewer.align.commandline.CollapseFractionsCLM.java
protected void normalizeIntensities(List<Double[]> intensitiesAllRuns) throws CommandLineModuleExecutionException { Double[] firstRunIntensities = intensitiesAllRuns.get(0); PanelWithScatterPlot pwspAllRunsNorm = null; if (showCharts) { pwspAllRunsNorm = new PanelWithScatterPlot(); pwspAllRunsNorm.setAxisLabels("Original", "Mapped"); pwspAllRunsNorm.setName("RunNormalization"); }/* w w w . ja v a 2 s . c o m*/ ApplicationContext.infoMessage("Rows in array: " + firstRunIntensities.length); for (int i = 1; i < arrayAnalyzer.getRunCount(); i++) { ApplicationContext.infoMessage("Normalizing fraction " + i); Double[] intensitiesThisRun = intensitiesAllRuns.get(i); List<Double> firstRunIntensitiesJustThisRun = new ArrayList<Double>(); List<Double> thisRunIntensitiesJustThisRun = new ArrayList<Double>(); for (int j = 0; j < firstRunIntensities.length; j++) { if (intensitiesThisRun[j] == null || firstRunIntensities[j] == null) continue; boolean foundInAnotherRun = false; for (int k = 1; k < arrayAnalyzer.getRunCount(); k++) { if (k != i && intensitiesAllRuns.get(k)[j] != null) { foundInAnotherRun = true; break; } } if (!foundInAnotherRun) { firstRunIntensitiesJustThisRun.add(firstRunIntensities[j]); thisRunIntensitiesJustThisRun.add(intensitiesThisRun[j]); } } ApplicationContext.infoMessage("values in common between ONLY unfrac and fraction " + i + ":" + firstRunIntensitiesJustThisRun.size()); List<Double> logFirst = new ArrayList<Double>(); List<Double> logThis = new ArrayList<Double>(); double minx = Double.MAX_VALUE; double maxx = Double.MIN_VALUE; for (int l = 0; l < firstRunIntensitiesJustThisRun.size(); l++) { logFirst.add(Math.log(firstRunIntensitiesJustThisRun.get(l))); logThis.add(Math.log(thisRunIntensitiesJustThisRun.get(l))); minx = Math.min(Math.log(thisRunIntensitiesJustThisRun.get(l)), minx); maxx = Math.max(Math.log(thisRunIntensitiesJustThisRun.get(l)), maxx); } if (logFirst.size() < minFeaturesInFracAndUnfrac) { ApplicationContext.infoMessage( "WARNING: unable to normalize run " + i + ", not enough in common with unfractionated run"); continue; } double[] coeffs = null; // try // { // //todo: un-hardcode //// coeffs = RegressionUtilities.modalRegression(logFirst, logThis, 1, 6, 2.0); // } // catch (IOException e) // { // throw new CommandLineModuleExecutionException("Failure in modal regression",e); // } //todo: un-hardcode Pair<double[], double[]> lowLeverageLowResPoints = RegressionUtilities .selectValuesWithLowLeverageAndStudentizedResidual(logThis, logFirst, 17, 1.8, false, 1, false, true); //try //{ // coeffs = RegressionUtilities.modalRegression( // lowLeverageLowResPoints.first, lowLeverageLowResPoints.second); //} //catch (IOException e) //{throw new CommandLineModuleExecutionException(e);} coeffs = calcGoodRegressionCoeffs(logThis, logFirst); if (showCharts) { PanelWithScatterPlot pwsp = new PanelWithScatterPlot(lowLeverageLowResPoints.first, lowLeverageLowResPoints.second, "logintensities" + i); pwsp.addData(logThis, logFirst, "used datapoints"); pwsp.setAxisLabels("current fraction", "unfractionated run"); pwsp.addLineOrCurve(coeffs, minx, maxx); pwsp.displayInTab(); } List<Double> origNotNullIntensities = null; if (showCharts) { origNotNullIntensities = new ArrayList<Double>(); for (int l = 0; l < intensitiesThisRun.length; l++) { if (intensitiesThisRun[l] != null) { origNotNullIntensities.add(Math.log(intensitiesThisRun[l])); } } } for (int l = 0; l < intensitiesThisRun.length; l++) { if (intensitiesThisRun[l] != null) intensitiesThisRun[l] = Math.exp( RegressionUtilities.mapValueUsingCoefficients(coeffs, Math.log(intensitiesThisRun[l]))); } if (showCharts) { List<Double> mappedNotNullIntensities = new ArrayList<Double>(); for (int l = 0; l < intensitiesThisRun.length; l++) { if (intensitiesThisRun[l] != null) { mappedNotNullIntensities.add(Math.log(intensitiesThisRun[l])); } } pwspAllRunsNorm.addData(origNotNullIntensities, mappedNotNullIntensities, "mappedintensities" + i); } } if (showCharts) pwspAllRunsNorm.displayInTab(); }
From source file:org.janusgraph.diskstorage.lucene.LuceneIndex.java
private static final Filter numericFilter(String key, Cmp relation, Number value) { switch (relation) { case EQUAL:/* ww w . j av a 2s . c om*/ return AttributeUtil.isWholeNumber(value) ? NumericRangeFilter.newLongRange(key, value.longValue(), value.longValue(), true, true) : NumericRangeFilter.newDoubleRange(key, value.doubleValue(), value.doubleValue(), true, true); case NOT_EQUAL: BooleanFilter q = new BooleanFilter(); if (AttributeUtil.isWholeNumber(value)) { q.add(NumericRangeFilter.newLongRange(key, Long.MIN_VALUE, value.longValue(), true, false), BooleanClause.Occur.SHOULD); q.add(NumericRangeFilter.newLongRange(key, value.longValue(), Long.MAX_VALUE, false, true), BooleanClause.Occur.SHOULD); } else { q.add(NumericRangeFilter.newDoubleRange(key, Double.MIN_VALUE, value.doubleValue(), true, false), BooleanClause.Occur.SHOULD); q.add(NumericRangeFilter.newDoubleRange(key, value.doubleValue(), Double.MAX_VALUE, false, true), BooleanClause.Occur.SHOULD); } return q; case LESS_THAN: return (AttributeUtil.isWholeNumber(value)) ? NumericRangeFilter.newLongRange(key, Long.MIN_VALUE, value.longValue(), true, false) : NumericRangeFilter.newDoubleRange(key, Double.MIN_VALUE, value.doubleValue(), true, false); case LESS_THAN_EQUAL: return (AttributeUtil.isWholeNumber(value)) ? NumericRangeFilter.newLongRange(key, Long.MIN_VALUE, value.longValue(), true, true) : NumericRangeFilter.newDoubleRange(key, Double.MIN_VALUE, value.doubleValue(), true, true); case GREATER_THAN: return (AttributeUtil.isWholeNumber(value)) ? NumericRangeFilter.newLongRange(key, value.longValue(), Long.MAX_VALUE, false, true) : NumericRangeFilter.newDoubleRange(key, value.doubleValue(), Double.MAX_VALUE, false, true); case GREATER_THAN_EQUAL: return (AttributeUtil.isWholeNumber(value)) ? NumericRangeFilter.newLongRange(key, value.longValue(), Long.MAX_VALUE, true, true) : NumericRangeFilter.newDoubleRange(key, value.doubleValue(), Double.MAX_VALUE, true, true); default: throw new IllegalArgumentException("Unexpected relation: " + relation); } }
From source file:ca.uhn.hl7v2.testpanel.ui.TestPanelWindow.java
/** * Initialize the contents of the frame. *///from ww w . j a v a 2 s . co m private void initialize() { myframe = new JFrame(); myframe.setVisible(false); List<Image> l = new ArrayList<Image>(); l.add(Toolkit.getDefaultToolkit() .getImage(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/hapi_16.png"))); l.add(Toolkit.getDefaultToolkit() .getImage(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/hapi_64.png"))); myframe.setIconImages(l); myframe.setTitle("HAPI TestPanel"); myframe.setBounds(100, 100, 796, 603); myframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); myframe.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent theE) { myController.close(); } }); JMenuBar menuBar = new JMenuBar(); myframe.setJMenuBar(menuBar); JMenu mnFile = new JMenu("File"); mnFile.setMnemonic('f'); menuBar.add(mnFile); JMenuItem mntmExit = new JMenuItem("Exit"); mntmExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { myController.close(); } }); JMenuItem mntmNewMessage = new JMenuItem("New Message..."); mntmNewMessage.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myController.addMessage(); } }); mntmNewMessage.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/message_hl7.png"))); mnFile.add(mntmNewMessage); mySaveMenuItem = new JMenuItem("Save"); mySaveMenuItem.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); mySaveMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSaveMessages(); } }); mnFile.add(mySaveMenuItem); mySaveAsMenuItem = new JMenuItem("Save As..."); mySaveAsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSaveMessagesAs(); } }); mnFile.add(mySaveAsMenuItem); mymenuItem_3 = new JMenuItem("Open"); mymenuItem_3.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); mymenuItem_3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myController.openMessages(); } }); myRevertToSavedMenuItem = new JMenuItem("Revert to Saved"); myRevertToSavedMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myController.revertMessage((Hl7V2MessageCollection) myController.getLeftSelectedItem()); } }); mnFile.add(myRevertToSavedMenuItem); mnFile.add(mymenuItem_3); myRecentFilesMenu = new JMenu("Open Recent"); mnFile.add(myRecentFilesMenu); JSeparator separator = new JSeparator(); mnFile.add(separator); mnFile.add(mntmExit); JMenu mnNewMenu = new JMenu("View"); mnNewMenu.setMnemonic('v'); menuBar.add(mnNewMenu); myShowLogConsoleMenuItem = new JMenuItem("Show Log Console"); myShowLogConsoleMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Prefs.getInstance().setShowLogConsole(!Prefs.getInstance().getShowLogConsole()); updateLogScrollPaneVisibility(); myframe.validate(); } }); mnNewMenu.add(myShowLogConsoleMenuItem); mymenu_1 = new JMenu("Test"); menuBar.add(mymenu_1); mymenuItem_1 = new JMenuItem("Populate TestPanel with Sample Message and Connections..."); mymenuItem_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myController.populateWithSampleMessageAndConnections(); } }); mymenu_1.add(mymenuItem_1); mymenu_3 = new JMenu("Tools"); menuBar.add(mymenu_3); mnHl7V2FileDiff = new JMenuItem("HL7 v2 File Diff..."); mnHl7V2FileDiff.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (myHl7V2FileDiff == null) { myHl7V2FileDiff = new Hl7V2FileDiffController(myController); } myHl7V2FileDiff.show(); } }); mymenu_3.add(mnHl7V2FileDiff); mymenuItem_5 = new JMenuItem("HL7 v2 File Sort..."); mymenuItem_5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (myHl7V2FileSort == null) { myHl7V2FileSort = new Hl7V2FileSortController(myController); } myHl7V2FileSort.show(); } }); mymenu_3.add(mymenuItem_5); mymenu_2 = new JMenu("Conformance"); menuBar.add(mymenu_2); mymenuItem_2 = new JMenuItem("Profiles and Tables..."); mymenuItem_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myController.showProfilesAndTablesEditor(); } }); mymenu_2.add(mymenuItem_2); mymenu = new JMenu("Help"); mymenu.setMnemonic('H'); menuBar.add(mymenu); mymenuItem = new JMenuItem("About HAPI TestPanel..."); mymenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showAboutDialog(); } }); mymenuItem.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/hapi_16.png"))); mymenu.add(mymenuItem); mymenuItem_4 = new JMenuItem("Licenses..."); mymenuItem_4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new LicensesDialog().setVisible(true); } }); mymenu.add(mymenuItem_4); myframe.getContentPane().setLayout(new BorderLayout(0, 0)); JSplitPane outerSplitPane = new JSplitPane(); outerSplitPane.setBorder(null); myframe.getContentPane().add(outerSplitPane); JSplitPane leftSplitPane = new JSplitPane(); leftSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); outerSplitPane.setLeftComponent(leftSplitPane); JPanel messagesPanel = new JPanel(); leftSplitPane.setLeftComponent(messagesPanel); GridBagLayout gbl_messagesPanel = new GridBagLayout(); gbl_messagesPanel.columnWidths = new int[] { 110, 0 }; gbl_messagesPanel.rowHeights = new int[] { 20, 30, 118, 0, 0 }; gbl_messagesPanel.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; gbl_messagesPanel.rowWeights = new double[] { 0.0, 0.0, 100.0, 1.0, Double.MIN_VALUE }; messagesPanel.setLayout(gbl_messagesPanel); JLabel lblMessages = new JLabel("Messages"); GridBagConstraints gbc_lblMessages = new GridBagConstraints(); gbc_lblMessages.insets = new Insets(0, 0, 5, 0); gbc_lblMessages.gridx = 0; gbc_lblMessages.gridy = 0; messagesPanel.add(lblMessages, gbc_lblMessages); JToolBar messagesToolBar = new JToolBar(); messagesToolBar.setFloatable(false); messagesToolBar.setRollover(true); messagesToolBar.setAlignmentX(Component.LEFT_ALIGNMENT); GridBagConstraints gbc_messagesToolBar = new GridBagConstraints(); gbc_messagesToolBar.insets = new Insets(0, 0, 5, 0); gbc_messagesToolBar.weightx = 1.0; gbc_messagesToolBar.anchor = GridBagConstraints.NORTHWEST; gbc_messagesToolBar.gridx = 0; gbc_messagesToolBar.gridy = 1; messagesPanel.add(messagesToolBar, gbc_messagesToolBar); JButton msgOpenButton = new JButton(""); msgOpenButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myController.openMessages(); } }); myAddMessageButton = new JButton(""); myAddMessageButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myController.addMessage(); } }); myAddMessageButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/add.png"))); myAddMessageButton.setToolTipText("New Message"); myAddMessageButton.setBorderPainted(false); myAddMessageButton.addMouseListener(new HoverButtonMouseAdapter(myAddMessageButton)); messagesToolBar.add(myAddMessageButton); myDeleteMessageButton = new JButton(""); myDeleteMessageButton.setToolTipText("Close Selected Message"); myDeleteMessageButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myController.closeMessage((Hl7V2MessageCollection) myController.getLeftSelectedItem()); } }); myDeleteMessageButton.setBorderPainted(false); myDeleteMessageButton.addMouseListener(new HoverButtonMouseAdapter(myDeleteMessageButton)); myDeleteMessageButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/close.png"))); messagesToolBar.add(myDeleteMessageButton); msgOpenButton.setBorderPainted(false); msgOpenButton.setToolTipText("Open Messages from File"); msgOpenButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/open.png"))); msgOpenButton.addMouseListener(new HoverButtonMouseAdapter(msgOpenButton)); messagesToolBar.add(msgOpenButton); myMsgSaveButton = new JButton(""); myMsgSaveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSaveMessages(); } }); myMsgSaveButton.setBorderPainted(false); myMsgSaveButton.setToolTipText("Save Selected Messages to File"); myMsgSaveButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/save.png"))); myMsgSaveButton.addMouseListener(new HoverButtonMouseAdapter(myMsgSaveButton)); messagesToolBar.add(myMsgSaveButton); myMessagesList = new JList(); myMessagesList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (myMessagesList.getSelectedIndex() >= 0) { ourLog.debug("New messages selection " + myMessagesList.getSelectedIndex()); myController.setLeftSelectedItem(myMessagesList.getSelectedValue()); myOutboundConnectionsList.clearSelection(); myOutboundConnectionsList.repaint(); myInboundConnectionsList.clearSelection(); myInboundConnectionsList.repaint(); } updateLeftToolbarButtons(); } }); GridBagConstraints gbc_MessagesList = new GridBagConstraints(); gbc_MessagesList.gridheight = 2; gbc_MessagesList.weightx = 1.0; gbc_MessagesList.weighty = 1.0; gbc_MessagesList.fill = GridBagConstraints.BOTH; gbc_MessagesList.gridx = 0; gbc_MessagesList.gridy = 2; messagesPanel.add(myMessagesList, gbc_MessagesList); JPanel connectionsPanel = new JPanel(); leftSplitPane.setRightComponent(connectionsPanel); GridBagLayout gbl_connectionsPanel = new GridBagLayout(); gbl_connectionsPanel.columnWidths = new int[] { 194, 0 }; gbl_connectionsPanel.rowHeights = new int[] { 0, 30, 0, 0, 0, 0, 0 }; gbl_connectionsPanel.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; gbl_connectionsPanel.rowWeights = new double[] { 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, Double.MIN_VALUE }; connectionsPanel.setLayout(gbl_connectionsPanel); JLabel lblConnections = new JLabel("Sending Connections"); lblConnections.setHorizontalAlignment(SwingConstants.CENTER); GridBagConstraints gbc_lblConnections = new GridBagConstraints(); gbc_lblConnections.insets = new Insets(0, 0, 5, 0); gbc_lblConnections.anchor = GridBagConstraints.NORTH; gbc_lblConnections.fill = GridBagConstraints.HORIZONTAL; gbc_lblConnections.gridx = 0; gbc_lblConnections.gridy = 0; connectionsPanel.add(lblConnections, gbc_lblConnections); JToolBar toolBar = new JToolBar(); toolBar.setFloatable(false); GridBagConstraints gbc_toolBar = new GridBagConstraints(); gbc_toolBar.insets = new Insets(0, 0, 5, 0); gbc_toolBar.anchor = GridBagConstraints.NORTH; gbc_toolBar.fill = GridBagConstraints.HORIZONTAL; gbc_toolBar.gridx = 0; gbc_toolBar.gridy = 1; connectionsPanel.add(toolBar, gbc_toolBar); myAddConnectionButton = new JButton(""); myAddConnectionButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myController.addOutboundConnection(); } }); myAddConnectionButton.setBorderPainted(false); myAddConnectionButton.addMouseListener(new HoverButtonMouseAdapter(myAddConnectionButton)); myAddConnectionButton.setBorder(null); myAddConnectionButton.setToolTipText("New Connection"); myAddConnectionButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/add.png"))); toolBar.add(myAddConnectionButton); myDeleteOutboundConnectionButton = new JButton(""); myDeleteOutboundConnectionButton.setToolTipText("Delete Selected Connection"); myDeleteOutboundConnectionButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (myController.getLeftSelectedItem() instanceof OutboundConnection) { myController.removeOutboundConnection((OutboundConnection) myController.getLeftSelectedItem()); } } }); myDeleteOutboundConnectionButton.setBorderPainted(false); myDeleteOutboundConnectionButton .addMouseListener(new HoverButtonMouseAdapter(myDeleteOutboundConnectionButton)); myDeleteOutboundConnectionButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/delete.png"))); toolBar.add(myDeleteOutboundConnectionButton); myStartOneOutboundButton = new JButton(""); myStartOneOutboundButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (myController.getLeftSelectedItem() instanceof OutboundConnection) { myController.startOutboundConnection((OutboundConnection) myController.getLeftSelectedItem()); } } }); myStartOneOutboundButton.setBorderPainted(false); myStartOneOutboundButton.setToolTipText("Start selected connection"); myStartOneOutboundButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/start_one.png"))); myStartOneOutboundButton.addMouseListener(new HoverButtonMouseAdapter(myStartOneOutboundButton)); toolBar.add(myStartOneOutboundButton); myStartAllOutboundButton = new JButton(""); myStartAllOutboundButton.setBorderPainted(false); myStartAllOutboundButton.setToolTipText("Start all sending connections"); myStartAllOutboundButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/start_all.png"))); myStartAllOutboundButton.addMouseListener(new HoverButtonMouseAdapter(myStartAllOutboundButton)); myStartAllOutboundButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent theE) { myController.startAllOutboundConnections(); } }); toolBar.add(myStartAllOutboundButton); myStopAllOutboundButton = new JButton(""); myStopAllOutboundButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myController.stopAllOutboundConnections(); } }); myStopAllOutboundButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/stop_all.png"))); myStopAllOutboundButton.setToolTipText("Stop all sending connections"); myStopAllOutboundButton.setBorderPainted(false); myStopAllOutboundButton.addMouseListener(new HoverButtonMouseAdapter(myStopAllOutboundButton)); toolBar.add(myStopAllOutboundButton); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBorder(null); GridBagConstraints gbc_scrollPane = new GridBagConstraints(); gbc_scrollPane.fill = GridBagConstraints.BOTH; gbc_scrollPane.insets = new Insets(0, 0, 5, 0); gbc_scrollPane.gridx = 0; gbc_scrollPane.gridy = 2; connectionsPanel.add(scrollPane, gbc_scrollPane); myOutboundConnectionsList = new JList(); myOutboundConnectionsList.setBorder(null); myOutboundConnectionsList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (myOutboundConnectionsList.getSelectedIndex() >= 0) { ourLog.debug( "New outbound connection selection " + myOutboundConnectionsList.getSelectedIndex()); myController.setLeftSelectedItem(myOutboundConnectionsList.getSelectedValue()); myMessagesList.clearSelection(); myMessagesList.repaint(); myInboundConnectionsList.clearSelection(); myInboundConnectionsList.repaint(); } updateLeftToolbarButtons(); } }); scrollPane.setViewportView(myOutboundConnectionsList); JLabel lblReceivingConnections = new JLabel("Receiving Connections"); lblReceivingConnections.setHorizontalAlignment(SwingConstants.CENTER); GridBagConstraints gbc_lblReceivingConnections = new GridBagConstraints(); gbc_lblReceivingConnections.insets = new Insets(0, 0, 5, 0); gbc_lblReceivingConnections.gridx = 0; gbc_lblReceivingConnections.gridy = 3; connectionsPanel.add(lblReceivingConnections, gbc_lblReceivingConnections); JToolBar toolBar_1 = new JToolBar(); toolBar_1.setFloatable(false); GridBagConstraints gbc_toolBar_1 = new GridBagConstraints(); gbc_toolBar_1.anchor = GridBagConstraints.WEST; gbc_toolBar_1.insets = new Insets(0, 0, 5, 0); gbc_toolBar_1.gridx = 0; gbc_toolBar_1.gridy = 4; connectionsPanel.add(toolBar_1, gbc_toolBar_1); myAddInboundConnectionButton = new JButton(""); myAddInboundConnectionButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myController.addInboundConnection(); } }); myAddInboundConnectionButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/add.png"))); myAddInboundConnectionButton.setToolTipText("New Connection"); myAddInboundConnectionButton.setBorderPainted(false); myAddInboundConnectionButton.addMouseListener(new HoverButtonMouseAdapter(myAddInboundConnectionButton)); toolBar_1.add(myAddInboundConnectionButton); myDeleteInboundConnectionButton = new JButton(""); myDeleteInboundConnectionButton.setToolTipText("Delete Selected Connection"); myDeleteInboundConnectionButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (myController.getLeftSelectedItem() instanceof InboundConnection) { myController.removeInboundConnection((InboundConnection) myController.getLeftSelectedItem()); } } }); myDeleteInboundConnectionButton.setBorderPainted(false); myDeleteInboundConnectionButton .addMouseListener(new HoverButtonMouseAdapter(myDeleteInboundConnectionButton)); myDeleteInboundConnectionButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/delete.png"))); toolBar_1.add(myDeleteInboundConnectionButton); myStartOneInboundButton = new JButton(""); myStartOneInboundButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (myController.getLeftSelectedItem() instanceof InboundConnection) { myController.startInboundConnection((InboundConnection) myController.getLeftSelectedItem()); } } }); myStartOneInboundButton.setBorderPainted(false); myStartOneInboundButton.setToolTipText("Start selected connection"); myStartOneInboundButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/start_one.png"))); myStartOneInboundButton.addMouseListener(new HoverButtonMouseAdapter(myStartOneInboundButton)); toolBar_1.add(myStartOneInboundButton); myStartAllInboundButton = new JButton(""); myStartAllInboundButton.setBorderPainted(false); myStartAllInboundButton.setToolTipText("Start all receiving connections"); myStartAllInboundButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/start_all.png"))); myStartAllInboundButton.addMouseListener(new HoverButtonMouseAdapter(myStartAllInboundButton)); myStartAllInboundButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent theE) { myController.startAllInboundConnections(); } }); toolBar_1.add(myStartAllInboundButton); myStopAllInboundButton = new JButton(""); myStopAllInboundButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myController.stopAllInboundConnections(); } }); myStopAllInboundButton.setIcon( new ImageIcon(TestPanelWindow.class.getResource("/ca/uhn/hl7v2/testpanel/images/stop_all.png"))); myStopAllInboundButton.setToolTipText("Stop all receiving connections"); myStopAllInboundButton.setBorderPainted(false); myStopAllInboundButton.addMouseListener(new HoverButtonMouseAdapter(myStopAllInboundButton)); toolBar_1.add(myStopAllInboundButton); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBorder(null); GridBagConstraints gbc_scrollPane_1 = new GridBagConstraints(); gbc_scrollPane_1.fill = GridBagConstraints.BOTH; gbc_scrollPane_1.gridx = 0; gbc_scrollPane_1.gridy = 5; connectionsPanel.add(scrollPane_1, gbc_scrollPane_1); myInboundConnectionsList = new JList(); myInboundConnectionsList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (myInboundConnectionsList.getSelectedIndex() >= 0) { ourLog.debug("New inbound connection selection " + myInboundConnectionsList.getSelectedIndex()); myController.setLeftSelectedItem(myInboundConnectionsList.getSelectedValue()); myMessagesList.clearSelection(); myMessagesList.repaint(); myOutboundConnectionsList.clearSelection(); myOutboundConnectionsList.repaint(); myInboundConnectionsList.repaint(); } updateLeftToolbarButtons(); } }); scrollPane_1.setViewportView(myInboundConnectionsList); leftSplitPane.setDividerLocation(200); myWorkspacePanel = new JPanel(); myWorkspacePanel.setBorder(null); outerSplitPane.setRightComponent(myWorkspacePanel); myWorkspacePanel.setLayout(new BorderLayout(0, 0)); outerSplitPane.setDividerLocation(200); myLogScrollPane = new LogTable(); myLogScrollPane.setPreferredSize(new Dimension(454, 120)); myLogScrollPane.setMaximumSize(new Dimension(32767, 120)); myframe.getContentPane().add(myLogScrollPane, BorderLayout.SOUTH); updateLogScrollPaneVisibility(); updateLeftToolbarButtons(); }
From source file:ml.shifu.shifu.core.processor.EvalModelProcessor.java
private double[] locateMaxMinScoreFromFile(SourceType sourceType, String maxMinScoreFolder) throws IOException { List<Scanner> scanners = null; double maxScore = Double.MIN_VALUE; double minScore = Double.MAX_VALUE; try {/* w ww . ja va2 s. com*/ // here only works for 1 reducer scanners = ShifuFileUtils.getDataScanners(maxMinScoreFolder, sourceType); for (Scanner scanner : scanners) { if (scanner.hasNext()) { String line = scanner.nextLine().trim(); String[] splits = line.split(","); if (splits.length >= 2) { double localMaxScore = Double.parseDouble(splits[0]); if (maxScore < localMaxScore) { maxScore = localMaxScore; } Double localMinScore = Double.parseDouble(splits[1]); if (minScore > localMinScore) { minScore = localMinScore; } } } } } finally { if (scanners != null) { for (Scanner scanner : scanners) { if (scanner != null) { scanner.close(); } } } } return new double[] { maxScore, minScore }; }
From source file:net.sf.json.TestJSONObject.java
public void testFromBean_use_wrappers() { JSONObject json = JSONObject.fromObject(Boolean.TRUE); assertTrue(json.isEmpty());// w ww .ja v a 2 s .co m json = JSONObject.fromObject(new Byte(Byte.MIN_VALUE)); assertTrue(json.isEmpty()); json = JSONObject.fromObject(new Short(Short.MIN_VALUE)); assertTrue(json.isEmpty()); json = JSONObject.fromObject(new Integer(Integer.MIN_VALUE)); assertTrue(json.isEmpty()); json = JSONObject.fromObject(new Long(Long.MIN_VALUE)); assertTrue(json.isEmpty()); json = JSONObject.fromObject(new Float(Float.MIN_VALUE)); assertTrue(json.isEmpty()); json = JSONObject.fromObject(new Double(Double.MIN_VALUE)); assertTrue(json.isEmpty()); json = JSONObject.fromObject(new Character('A')); assertTrue(json.isEmpty()); }