Example usage for java.util Arrays fill

List of usage examples for java.util Arrays fill

Introduction

In this page you can find the example usage for java.util Arrays fill.

Prototype

public static void fill(Object[] a, Object val) 

Source Link

Document

Assigns the specified Object reference to each element of the specified array of Objects.

Usage

From source file:net.sf.dsp4j.octave_3_2_4.m.polynomial.Roots.java

public static Complex[] roots(RealVector v) {

    if (v.isInfinite() || v.isNaN()) {
        throw new RuntimeException("roots: inputs must not contain Inf or NaN");
    }//w  ww.  j av  a 2 s . c  o  m

    int n = v.getDimension();

    // ## If v = [ 0 ... 0 v(k+1) ... v(k+l) 0 ... 0 ], we can remove the
    // ## leading k zeros and n - k - l roots of the polynomial are zero.

    int[] f = new int[v.getDimension()];
    if (v.getDimension() > 0) {
        int fI = 0;
        double max = v.getMaxValue();
        double min = FastMath.abs(v.getMinValue());
        if (min > max) {
            max = min;
        }
        RealVector v1 = v.mapDivide(max);
        f = OctaveBuildIn.find(v1);
    }

    Complex[] r = new Complex[0];
    if (f.length > 0 && n > 1) {
        v = v.getSubVector(f[0], f[f.length - 1] - f[0] + 1);
        if (v.getDimension() > 1) {
            double[] ones = new double[v.getDimension() - 2];
            Arrays.fill(ones, 1);
            RealMatrix A = OctaveBuildIn.diag(ones, -1);
            for (int i = 0; i < A.getRowDimension(); i++) {
                A.setEntry(i, 0, -v.getEntry(i + 1) / v.getEntry(0));
            }
            try {
                r = Eig.eig(A);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (f[f.length - 1] < n) {
                int diffLength = n - 1 - f[f.length - 1];
                if (diffLength > 0) {
                    int rl = r.length;
                    r = Arrays.copyOf(r, r.length + diffLength);
                    Arrays.fill(r, rl, r.length, Complex.ZERO);
                }
            }
        } else {
            r = new Complex[n - f[f.length - 1]];
            Arrays.fill(r, Complex.ZERO);
        }
    } else {
        r = new Complex[0];
    }
    return r;

}

From source file:controller.Parser.java

static LP parse(File f) throws FileNotFoundException {
    Scanner s = new Scanner(f);
    Pattern p = Pattern.compile(dvarreg);

    HashMap<String, Integer> x = new HashMap<String, Integer>();
    HashMap<Integer, String> xReverse = new HashMap<Integer, String>();
    int xcol = 0;

    /* Get input size and names of the decision variables. */
    int constraints = -1; // Take the objective function into account.
    while (s.hasNextLine()) {
        String line = s.nextLine();

        if (line.trim().equals(""))
            continue;

        /* /*from  w  w w.  j  av a 2  s . c om*/
         * TODO: Beware, will now accept invalid
         * files with multiple objective functions.
         */
        /*            if (!validConstraint(line) && !validObj(line)) {
        String e = "Unsupported format in file " + f;
        throw new IllegalArgumentException(e);
                    } */

        Matcher m = p.matcher(line);

        while (m.find()) {
            String var = m.group(3);
            if (validVarName(var) && !x.containsKey(var)) {
                x.put(var, xcol);
                xReverse.put(xcol++, var);
            }
        }
        constraints++;
    }

    BigFraction[][] Ndata = new BigFraction[constraints][x.size()];
    for (int i = 0; i < Ndata.length; i++) {
        Arrays.fill(Ndata[i], BigFraction.ZERO);
    }
    BigFraction[] bdata = new BigFraction[constraints];
    BigFraction[] cdata = new BigFraction[x.size()];
    Arrays.fill(cdata, BigFraction.ZERO);

    s = new Scanner(f);

    String obj = s.nextLine();
    Matcher m = p.matcher(obj);

    while (m.find()) {
        String var = m.group(3);
        if (!x.containsKey(var))
            continue;

        String sign = m.group(1);
        if (sign == null)
            sign = "+";

        String coeffStr = m.group(2);
        BigFraction coeff;
        if (coeffStr == null) {
            coeff = BigFraction.ONE;
        } else {
            coeff = new BigFraction(Double.parseDouble(coeffStr));
        }
        if (sign.equals("-"))
            coeff = coeff.negate();

        cdata[x.get(var)] = coeff;
    }

    int row = 0;
    while (s.hasNextLine()) {
        String line = s.nextLine();
        String[] split = line.split("<=");
        if (line.trim().equals(""))
            continue;
        if (split.length != 2) {
            String e = "Unsupported format in file " + f;
            throw new IllegalArgumentException(e);
        }
        m = p.matcher(line);
        bdata[row] = new BigFraction(Double.parseDouble(split[1]));

        while (m.find()) {
            String var = m.group(3);
            if (!x.containsKey(var))
                continue;

            String sign = m.group(1);
            if (sign == null)
                sign = "+";

            String coeffStr = m.group(2);
            BigFraction coeff;
            if (coeffStr == null) {
                coeff = BigFraction.ONE;
            } else {
                coeff = new BigFraction(Double.parseDouble(coeffStr));
            }
            if (sign.equals("-"))
                coeff = coeff.negate();

            Ndata[row][x.get(var)] = coeff;
        }
        row++;
    }

    return new LP(new Array2DRowFieldMatrix<BigFraction>(Ndata), new ArrayFieldVector<BigFraction>(bdata),
            new ArrayFieldVector<BigFraction>(cdata), xReverse);
}

From source file:com.opengamma.analytics.math.curve.ConstantDoublesCurve.java

/**
 * /*  w  w w  .jav a 2 s  .  c o  m*/
 * @param x An array of <i>x</i> values, not null
 * @param interpolator An interpolator, not null
 * @return An interpolated curve with constant value 
 */
public InterpolatedDoublesCurve toInterpolatedDoublesCurve(final double[] x,
        final Interpolator1D interpolator) {
    Validate.notNull(x, "x");
    Validate.notNull(interpolator, "interpolator");
    final double[] y = new double[x.length];
    Arrays.fill(y, _y);
    return InterpolatedDoublesCurve.from(x, y, interpolator);
}

From source file:edu.byu.nlp.util.IntArrays.java

public static int[] repeat(int i, int size) {
    int[] arr = new int[size];
    Arrays.fill(arr, i);
    return arr;//w w  w. j a  va 2s  .  c  om
}

From source file:kishida.cnn.layers.MaxPoolingLayer.java

@Override
public float[] backward(float[] in, float[] delta) {
    Arrays.fill(newDelta, 0);
    IntStream.range(0, inputChannels).parallel().forEach(ch -> {
        for (int x = 0; x < outputWidth; ++x) {
            for (int y = 0; y < outputHeight; ++y) {
                float max = Float.NEGATIVE_INFINITY;
                int maxX = 0;
                int maxY = 0;
                for (int i = 0; i < size; ++i) {
                    int xx = x * stride + i - size / 2;
                    if (xx < 0 || xx >= inputWidth) {
                        continue;
                    }/*from w  ww . ja v a2 s . c  o  m*/
                    for (int j = 0; j < size; ++j) {
                        int yy = y * stride + j - size / 2;
                        if (yy < 0 || yy >= inputHeight) {
                            continue;
                        }
                        float d = in[ch * inputWidth * inputHeight + xx * inputWidth + yy];
                        if (max < d) {
                            max = d;
                            maxX = xx;
                            maxY = yy;
                        }
                    }
                }
                int chxy = ch * outputWidth * outputHeight + x * outputHeight + y;
                newDelta[ch * inputWidth * inputHeight + maxX * inputHeight + maxY] += delta[chxy];
            }
        }
    });
    return newDelta;
}

From source file:com.hazelcast.qasonar.utils.Utils.java

public static String fillString(int length, char charToFill) {
    if (length == 0) {
        return "";
    }/* ww  w.j  a va2  s  .  c om*/
    char[] array = new char[length];
    Arrays.fill(array, charToFill);
    return new String(array);
}

From source file:it.scoppelletti.security.keygen.DESKeyToPropertySetProvider.java

public Properties toProperties(Key key) {
    byte[] data;//from  w  ww  .j  a v a2  s  .c  o m
    SecretKey desKey;
    SecretKeyFactory keyFactory;
    DESKeySpec param;
    Properties props;

    if (!(key instanceof SecretKey)) {
        return null;
    }

    try {
        keyFactory = SecretKeyFactory.getInstance(DESKeyFactory.ALGORITHM);
    } catch (NoSuchAlgorithmException ex) {
        return null;
    }

    try {
        desKey = keyFactory.translateKey((SecretKey) key);
    } catch (InvalidKeyException ex) {
        return null;
    }

    try {
        param = (DESKeySpec) keyFactory.getKeySpec(desKey, DESKeySpec.class);
    } catch (InvalidKeySpecException ex) {
        return null;
    }

    props = new Properties();
    props.setProperty(CryptoUtils.PROP_KEYFACTORY, DESKeyFactory.class.getName());
    data = param.getKey();
    props.setProperty(DESKeyFactory.PROP_KEY, Hex.encodeHexString(data));
    Arrays.fill(data, Byte.MIN_VALUE);

    return props;
}

From source file:it.scoppelletti.security.keygen.DESedeKeyToPropertySetProvider.java

public Properties toProperties(Key key) {
    byte[] data;//from w w  w  .  j  a  va2 s  .  c  om
    SecretKey desKey;
    SecretKeyFactory keyFactory;
    DESedeKeySpec param;
    Properties props;

    if (!(key instanceof SecretKey)) {
        return null;
    }

    try {
        keyFactory = SecretKeyFactory.getInstance(DESedeKeyFactory.ALGORITHM);
    } catch (NoSuchAlgorithmException ex) {
        return null;
    }

    try {
        desKey = keyFactory.translateKey((SecretKey) key);
    } catch (InvalidKeyException ex) {
        return null;
    }

    try {
        param = (DESedeKeySpec) keyFactory.getKeySpec(desKey, DESedeKeySpec.class);
    } catch (InvalidKeySpecException ex) {
        return null;
    }

    props = new Properties();
    props.setProperty(CryptoUtils.PROP_KEYFACTORY, DESedeKeyFactory.class.getName());
    data = param.getKey();
    props.setProperty(DESedeKeyFactory.PROP_KEY, Hex.encodeHexString(data));
    Arrays.fill(data, Byte.MIN_VALUE);

    return props;
}

From source file:gedi.atac.DirichletTest.java

@Override
public void accept(ReferenceSequence reference, GenomicRegion region, PixelLocationMapping pixelMapping,
        PixelBlockToValuesMap data) {//from www .  ja  v  a  2  s  .c  o m

    int bases = 0;
    int bins = data.size();

    double[] alpha = new double[bins];

    for (int b = 0; b < data.size(); b++) {
        PixelLocationMappingBlock bl = data.getBlock(b);
        bases += bl.getStopBp() + 1 - bl.getStartBp();

        alpha[b] = NumericArrayFunction.Sum.applyAsDouble(data.getValues(b)) + 1;
    }

    double[] p = alpha.clone();
    ArrayUtils.normalize(p);

    double lh1 = logProbability(alpha, p);
    Arrays.fill(p, 1.0 / bins);
    double lh0 = logProbability(alpha, p);

    double lr = 2 * lh1 - 2 * lh0;

    ChiSquaredDistribution d = new ChiSquaredDistribution(bins - 2);

    System.out.printf("Bases=%d\nBins=%d\nLR=%.4g\np=%.5g", bases, bins, lr, 1 - d.cumulativeProbability(lr));

}

From source file:edu.utexas.cs.tactex.tariffoptimization.OptimizerWrapperGradientAscent.java

@Override
public TreeMap<Double, TariffSpecification> findOptimum(TariffUtilityEstimate tariffUtilityEstimate,
        int NUM_RATES, int numEval) {

    double[] startingVertex = new double[NUM_RATES]; // start from the fixed-rate tariff's offset
    Arrays.fill(startingVertex, 0.0);

    // temporary solution - getting fixed rate tariff to determine step size and scaling STEP_SIZE proportionally
    TariffSpecification bestFixedRateSpec = tariffUtilityEstimate.getCorrespondingSpec(startingVertex);
    double bestFixedRate = bestFixedRateSpec.getRates().get(0).getValue();
    double rateRatio = bestFixedRate / REFERENCE_RATE;
    // Note: using rateRatio has not been good enough, so trying powers of it (remember it's > 1)
    //STEP_SIZE = Math.max(REFERENCE_STEP_SIZE, (rateRatio * rateRatio) * REFERENCE_STEP_SIZE);
    STEP_SIZE = Math.max(REFERENCE_STEP_SIZE, Math.abs(rateRatio) * REFERENCE_STEP_SIZE);
    log.debug("STEP_SIZE = " + STEP_SIZE + " REFERENCE_STEP_SIZE=" + REFERENCE_STEP_SIZE + " bestFixedRate="
            + bestFixedRate + " REFERENCE_RATE=" + REFERENCE_RATE);

    evaluations = 0;//from  w  w  w . ja v a 2 s .  com
    TreeMap<Double, TariffSpecification> eval2TOUTariff = new TreeMap<Double, TariffSpecification>();

    // OUTER LOOP
    //for( STEP_SIZE = 0.005; STEP_SIZE < 0.100; STEP_SIZE += 0.005) {
    //  log.info("STARTING A LOOP: STEP_SIZE=" + STEP_SIZE);

    // first compute numerical gradient
    RealVector gradient = new ArrayRealVector(NUM_RATES);
    for (int i = 0; i < NUM_RATES; ++i) {
        gradient.setEntry(i, computePartialDerivative(i, tariffUtilityEstimate, NUM_RATES, eval2TOUTariff));
    }
    gradient = gradient.unitVector();

    // taking steps in the gradient direction
    double previousPointValue = -Double.MAX_VALUE;
    final double alpha = STEP_SIZE;
    RealVector rateOffsets = new ArrayRealVector(NUM_RATES); // initializes with 0s?
    double currentPointValue = evaluatePoint(tariffUtilityEstimate, rateOffsets.toArray());
    eval2TOUTariff.put(currentPointValue, tariffUtilityEstimate.getCorrespondingSpec(rateOffsets.toArray()));
    while (!converged(currentPointValue, previousPointValue) && evaluations < MAX_EVALUATIONS) {
        previousPointValue = currentPointValue;
        rateOffsets = rateOffsets.add(gradient.mapMultiply(alpha));
        currentPointValue = evaluatePoint(tariffUtilityEstimate, rateOffsets.toArray());
        eval2TOUTariff.put(currentPointValue,
                tariffUtilityEstimate.getCorrespondingSpec(rateOffsets.toArray()));
    }

    log.info("gradient ascent finished after " + evaluations + " evaluations");

    //}

    // return map
    return eval2TOUTariff;
}