Example usage for java.util Arrays copyOfRange

List of usage examples for java.util Arrays copyOfRange

Introduction

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

Prototype

public static boolean[] copyOfRange(boolean[] original, int from, int to) 

Source Link

Document

Copies the specified range of the specified array into a new array.

Usage

From source file:com.blockwithme.longdb.leveldb.Util.java

/** Split column.
 * /*from w w  w . j a  va  2  s  . c  o  m*/
 * @param theRowColumnPair
 *        the combined row column pair
 * @return the column id */
public static long splitColumn(final byte[] theRowColumnPair) {
    return toLong(Arrays.copyOfRange(theRowColumnPair, LONG_BYTES, LONG_BYTES_X_2));
}

From source file:de.psdev.energylogger.parser.EnergyLoggerDataParserImpl.java

@Override
public List<LogEntry> parseFileContents(InputStream input) throws IOException {
    if (!(input instanceof BufferedInputStream)) {
        input = new BufferedInputStream(input);
    }/*from ww w . ja  v  a 2  s  . c om*/
    final List<LogEntry> logEntries = new ArrayList<LogEntry>();

    final byte[] data = IOUtils.toByteArray(input);
    int counter = 0;
    final Calendar currentDate = GregorianCalendar.getInstance();
    FileType fileType = FileType.UNKNOWN;

    while (counter < data.length) {
        if (fileType == FileType.DATA) {
            if (Arrays.equals(Arrays.copyOfRange(data, counter, counter + START_CODE.length), START_CODE)) {
                counter += START_CODE.length;
                currentDate.setTime(
                        parseDate(Arrays.copyOfRange(data, counter, counter + START_DATE_BYTES_LENGTH)));
                counter += START_DATE_BYTES_LENGTH;
            } else if (Arrays.equals(Arrays.copyOfRange(data, counter, counter + EOF_CODE.length), EOF_CODE)) {
                break;
            } else {
                final byte[] dataBytes = Arrays.copyOfRange(data, counter, counter + DATA_BYTES_LENGTH);
                final double avgVoltage = parseDouble(dataBytes[0], dataBytes[1]) / 10;
                final double avgCurrent = parseDouble(dataBytes[2], dataBytes[3]) / 1000;
                final double avgPowerFactor = parseDouble(dataBytes[4]) / 100;
                final LogEntry logEntry = new LogEntryImpl();
                logEntry.setVoltage(avgVoltage);
                logEntry.setCurrent(avgCurrent);
                logEntry.setPowerfactor(avgPowerFactor);
                logEntry.setTimestamp(currentDate.getTime());
                logEntries.add(logEntry);
                currentDate.add(Calendar.MINUTE, 1);
                counter += DATA_BYTES_LENGTH;
            }

        } else if (fileType == FileType.INFO) {
            LOG.warn("got INFO file - ignoring because of invalid data");
            break;
        } else if (fileType == FileType.UNKNOWN) {
            if (Arrays.equals(Arrays.copyOfRange(data, counter, counter + INFO_FILE_START_CODE.length),
                    INFO_FILE_START_CODE)) { // INFO FILE
                fileType = FileType.INFO;
            } else if (Arrays.equals(Arrays.copyOfRange(data, counter, counter + START_CODE.length),
                    START_CODE)) {
                fileType = FileType.DATA;
            } else {
                throw new RuntimeException("Unknown Filetype");
            }

        }
    }
    return logEntries;
}

From source file:juicebox.tools.utils.juicer.hiccups.GPUController.java

public GPUOutputContainer process(MatrixZoomData zd, double[] normalizationVector, double[] expectedVector,
        int[] rowBounds, int[] columnBounds, int matrixSize, float[] thresholdBL, float[] thresholdDonut,
        float[] thresholdH, float[] thresholdV, NormalizationType normalizationType)
        throws NegativeArraySizeException, IOException {

    RealMatrix localizedRegionData = HiCFileTools.extractLocalBoundedRegion(zd, rowBounds[0], rowBounds[1],
            columnBounds[0], columnBounds[1], matrixSize, matrixSize, normalizationType);

    float[] observedVals = Floats
            .toArray(Doubles.asList(MatrixTools.flattenedRowMajorOrderMatrix(localizedRegionData)));

    // slice KR vector to localized region
    float[] distanceExpectedKRVector = Floats.toArray(Doubles.asList(expectedVector));

    float[] kr1CPU = Floats
            .toArray(Doubles.asList(Arrays.copyOfRange(normalizationVector, rowBounds[0], rowBounds[1])));
    float[] kr2CPU = Floats
            .toArray(Doubles.asList(Arrays.copyOfRange(normalizationVector, columnBounds[0], columnBounds[1])));

    if (kr1CPU.length < matrixSize)
        kr1CPU = ArrayTools.padEndOfArray(kr1CPU, matrixSize, Float.NaN);
    if (kr2CPU.length < matrixSize)
        kr2CPU = ArrayTools.padEndOfArray(kr2CPU, matrixSize, Float.NaN);

    float[] boundRowIndex = new float[1];
    boundRowIndex[0] = rowBounds[0];/*from   w w w.ja  v a 2s . c  o  m*/
    float[] boundColumnIndex = new float[1];
    boundColumnIndex[0] = columnBounds[0];

    //long gpu_time1 = System.currentTimeMillis();

    // transfer host (CPU) memory to device (GPU) memory
    CUdeviceptr observedKRGPU = GPUHelper.allocateInput(observedVals);
    CUdeviceptr expectedDistanceVectorGPU = GPUHelper.allocateInput(distanceExpectedKRVector);
    CUdeviceptr kr1GPU = GPUHelper.allocateInput(kr1CPU);
    CUdeviceptr kr2GPU = GPUHelper.allocateInput(kr2CPU);
    CUdeviceptr thresholdBLGPU = GPUHelper.allocateInput(thresholdBL);
    CUdeviceptr thresholdDonutGPU = GPUHelper.allocateInput(thresholdDonut);
    CUdeviceptr thresholdHGPU = GPUHelper.allocateInput(thresholdH);
    CUdeviceptr thresholdVGPU = GPUHelper.allocateInput(thresholdV);
    CUdeviceptr boundRowIndexGPU = GPUHelper.allocateInput(boundRowIndex);
    CUdeviceptr boundColumnIndexGPU = GPUHelper.allocateInput(boundColumnIndex);

    // create empty gpu arrays for the results
    int flattenedSize = matrixSize * matrixSize;
    CUdeviceptr expectedBLGPU = GPUHelper.allocateOutput(flattenedSize, Sizeof.FLOAT);
    CUdeviceptr expectedDonutGPU = GPUHelper.allocateOutput(flattenedSize, Sizeof.FLOAT);
    CUdeviceptr expectedHGPU = GPUHelper.allocateOutput(flattenedSize, Sizeof.FLOAT);
    CUdeviceptr expectedVGPU = GPUHelper.allocateOutput(flattenedSize, Sizeof.FLOAT);
    CUdeviceptr binBLGPU = GPUHelper.allocateOutput(flattenedSize, Sizeof.FLOAT);
    CUdeviceptr binDonutGPU = GPUHelper.allocateOutput(flattenedSize, Sizeof.FLOAT);
    CUdeviceptr binHGPU = GPUHelper.allocateOutput(flattenedSize, Sizeof.FLOAT);
    CUdeviceptr binVGPU = GPUHelper.allocateOutput(flattenedSize, Sizeof.FLOAT);
    CUdeviceptr observedGPU = GPUHelper.allocateOutput(flattenedSize, Sizeof.FLOAT);
    CUdeviceptr peakGPU = GPUHelper.allocateOutput(flattenedSize, Sizeof.FLOAT);

    // call the kernel on the card
    kernelLauncher.call(
            // inputs
            observedKRGPU,
            // output
            expectedBLGPU, expectedDonutGPU, expectedHGPU, expectedVGPU, observedGPU, binBLGPU, binDonutGPU,
            binHGPU, binVGPU, peakGPU,
            // thresholds
            thresholdBLGPU, thresholdDonutGPU, thresholdHGPU, thresholdVGPU,
            // distance expected
            expectedDistanceVectorGPU,
            // kr
            kr1GPU, kr2GPU,
            // bounds
            boundRowIndexGPU, boundColumnIndexGPU);

    // initialize memory to store GPU results
    float[] expectedBLResult = new float[flattenedSize];
    float[] expectedDonutResult = new float[flattenedSize];
    float[] expectedHResult = new float[flattenedSize];
    float[] expectedVResult = new float[flattenedSize];
    float[] binBLResult = new float[flattenedSize];
    float[] binDonutResult = new float[flattenedSize];
    float[] binHResult = new float[flattenedSize];
    float[] binVResult = new float[flattenedSize];
    float[] observedResult = new float[flattenedSize];
    float[] peakResult = new float[flattenedSize];

    // transfer device (GPU) memory to host (CPU) memory
    cuMemcpyDtoH(Pointer.to(expectedBLResult), expectedBLGPU, flattenedSize * Sizeof.FLOAT);
    cuMemcpyDtoH(Pointer.to(expectedDonutResult), expectedDonutGPU, flattenedSize * Sizeof.FLOAT);
    cuMemcpyDtoH(Pointer.to(expectedHResult), expectedHGPU, flattenedSize * Sizeof.FLOAT);
    cuMemcpyDtoH(Pointer.to(expectedVResult), expectedVGPU, flattenedSize * Sizeof.FLOAT);
    cuMemcpyDtoH(Pointer.to(binBLResult), binBLGPU, flattenedSize * Sizeof.FLOAT);
    cuMemcpyDtoH(Pointer.to(binDonutResult), binDonutGPU, flattenedSize * Sizeof.FLOAT);
    cuMemcpyDtoH(Pointer.to(binHResult), binHGPU, flattenedSize * Sizeof.FLOAT);
    cuMemcpyDtoH(Pointer.to(binVResult), binVGPU, flattenedSize * Sizeof.FLOAT);
    cuMemcpyDtoH(Pointer.to(observedResult), observedGPU, flattenedSize * Sizeof.FLOAT);
    cuMemcpyDtoH(Pointer.to(peakResult), peakGPU, flattenedSize * Sizeof.FLOAT);

    //long gpu_time2 = System.currentTimeMillis();
    //System.out.println("GPU Time: " + (gpu_time2-gpu_time1));

    int finalWidthX = rowBounds[5] - rowBounds[4];
    int finalWidthY = columnBounds[5] - columnBounds[4];

    // x2, y2 not inclusive here
    int x1 = rowBounds[2];
    int y1 = columnBounds[2];
    int x2 = x1 + finalWidthX;
    int y2 = y1 + finalWidthY;

    //System.out.println("flat = "+flattenedSize+" n = "+matrixSize+" x1 = "+x1+" x2 = "+x2+" y1 = "+y1+" y2 ="+y2);
    float[][] observedDenseCPU = GPUHelper.GPUArraytoCPUMatrix(observedResult, matrixSize, x1, x2, y1, y2);
    float[][] peakDenseCPU = GPUHelper.GPUArraytoCPUMatrix(peakResult, matrixSize, x1, x2, y1, y2);
    float[][] binBLDenseCPU = GPUHelper.GPUArraytoCPUMatrix(binBLResult, matrixSize, x1, x2, y1, y2);
    float[][] binDonutDenseCPU = GPUHelper.GPUArraytoCPUMatrix(binDonutResult, matrixSize, x1, x2, y1, y2);
    float[][] binHDenseCPU = GPUHelper.GPUArraytoCPUMatrix(binHResult, matrixSize, x1, x2, y1, y2);
    float[][] binVDenseCPU = GPUHelper.GPUArraytoCPUMatrix(binVResult, matrixSize, x1, x2, y1, y2);
    float[][] expectedBLDenseCPU = GPUHelper.GPUArraytoCPUMatrix(expectedBLResult, matrixSize, x1, x2, y1, y2);
    float[][] expectedDonutDenseCPU = GPUHelper.GPUArraytoCPUMatrix(expectedDonutResult, matrixSize, x1, x2, y1,
            y2);
    float[][] expectedHDenseCPU = GPUHelper.GPUArraytoCPUMatrix(expectedHResult, matrixSize, x1, x2, y1, y2);
    float[][] expectedVDenseCPU = GPUHelper.GPUArraytoCPUMatrix(expectedVResult, matrixSize, x1, x2, y1, y2);

    GPUHelper.freeUpMemory(new CUdeviceptr[] { observedKRGPU, expectedDistanceVectorGPU, kr1GPU, kr2GPU,
            thresholdBLGPU, thresholdDonutGPU, thresholdHGPU, thresholdVGPU, boundRowIndexGPU,
            boundColumnIndexGPU, expectedBLGPU, expectedDonutGPU, expectedHGPU, expectedVGPU, binBLGPU,
            binDonutGPU, binHGPU, binVGPU, observedGPU, peakGPU });

    return new GPUOutputContainer(observedDenseCPU, peakDenseCPU, binBLDenseCPU, binDonutDenseCPU, binHDenseCPU,
            binVDenseCPU, expectedBLDenseCPU, expectedDonutDenseCPU, expectedHDenseCPU, expectedVDenseCPU);
}

From source file:com.linkedin.pinot.core.realtime.impl.kafka.KafkaAvroMessageDecoder.java

@Override
public GenericRow decode(byte[] payload, int offset, int length) {
    if (payload == null || payload.length == 0 || length == 0) {
        return null;
    }//from   w ww .ja  v a2s.  c o  m

    byte[] md5 = Arrays.copyOfRange(payload, SCHEMA_HASH_START_OFFSET + offset,
            SCHEMA_HASH_END_OFFSET + offset);

    String md5String = hex(md5);
    org.apache.avro.Schema schema = null;
    if (md5ToAvroSchemaMap.containsKey(md5String)) {
        schema = md5ToAvroSchemaMap.get(md5String);
    } else {
        try {
            schema = fetchSchema(new URL(schemaRegistryBaseUrl + "/id=" + md5String));
            md5ToAvroSchemaMap.put(md5String, schema);
        } catch (Exception e) {
            schema = defaultAvroSchema;
            LOGGER.error("error fetching schema from md5 String", e);
        }
    }
    DatumReader<Record> reader = new GenericDatumReader<Record>(schema);
    try {
        GenericData.Record avroRecord = reader.read(null, decoderFactory.createBinaryDecoder(payload,
                HEADER_LENGTH + offset, length - HEADER_LENGTH, null));
        return avroRecordConvetrer.transform(avroRecord, schema);
    } catch (IOException e) {
        LOGGER.error("Caught exception while reading message", e);
        return null;
    }
}

From source file:com.tinspx.util.io.ChannelSourceTest.java

@Test
public void testBAChannelSource() throws IOException {
    ChannelSource s = ChannelSource.of(INPUT);
    assertTrue(s.hasKnownSize());/*from  w w w .ja  va 2  s  . c o m*/
    assertEquals(INPUT.length, s.size());
    ByteSourceTests.testByteSource(s, INPUT);

    int off = 443, len = 17167;
    s = ChannelSource.of(INPUT, off, len);
    assertTrue(s.hasKnownSize());
    assertEquals(len, s.size());
    ByteSourceTests.testByteSource(s, Arrays.copyOfRange(INPUT, off, off + len));
}

From source file:bachelorthesis.captchabuilder.builder.BorderParser.java

private static CaptchaBuilder parseBorderProducer(BorderProducerType borderProducerType,
        String[] borderProducerOptions, CaptchaBuilder builder) throws ParseException {
    BorderProducerBuilder borderProducerBuilder = new BorderProducerBuilder(borderProducerType);

    if (borderProducerOptions.length == 0) {
        //return builder.addBorder(borderProducerBuilder.create());
        builder.addBuildSequence(borderProducerBuilder);
        return builder;
    }// w  ww  .j  a va  2s  . c o  m

    if (borderProducerOptions.length > BorderProducerOptions.values().length) {
        throw new ParseException(
                "BorderProducer takes a max of " + BorderProducerOptions.values().length + " arguments");
    }

    for (String boderproducerOption : borderProducerOptions) {
        if (!boderproducerOption.isEmpty()) {
            try {
                String[] optionArgs = boderproducerOption.split(CaptchaConstants.buildSequencelvl4Delim);
                BorderProducerOptions borderProducerOptionType = BorderProducerOptions.valueOf(optionArgs[0]);
                String[] borderProducerOptionArgs = Arrays.copyOfRange(optionArgs, 1, optionArgs.length);
                borderProducerBuilder = parseBorderProducerOption(borderProducerOptionType,
                        borderProducerOptionArgs, borderProducerBuilder);
            } catch (IllegalArgumentException e) {
                throw new ParseException(e.getMessage());
            }
        }

    }

    //return builder.addBorder(borderProducerBuilder.create());
    builder.addBuildSequence(borderProducerBuilder);
    return builder;
}

From source file:bachelorthesis.captchabuilder.builder.NoiseParser.java

private static CaptchaBuilder parseNoiseProducer(NoiseProducerType noiseProducerType,
        String[] noiseProducerOptions, CaptchaBuilder builder) throws ParseException {
    NoiseProducerBuilder noiseProducerBuilder = new NoiseProducerBuilder(noiseProducerType);

    if (noiseProducerOptions.length == 0) {
        //return builder.addNoise(noiseProducerBuilder.create());
        builder.addBuildSequence(noiseProducerBuilder);
        return builder;
    }//from  w  ww.  ja  va  2s  . co m

    if (noiseProducerOptions.length > NoiseProducerOptions.values().length) {
        throw new ParseException(
                "NoiseProducer takes a max of " + NoiseProducerOptions.values().length + " arguments");
    }

    for (String noiseProducerOption : noiseProducerOptions) {
        String[] optionArgs = noiseProducerOption.split(CaptchaConstants.buildSequencelvl4Delim);
        try {
            NoiseProducerOptions noiseProducerOptionType = NoiseProducerOptions.valueOf(optionArgs[0]);
            String[] noiseProducerOptionArgs = Arrays.copyOfRange(optionArgs, 1, optionArgs.length);
            noiseProducerBuilder = parseNoiseProducerOption(noiseProducerOptionType, noiseProducerOptionArgs,
                    noiseProducerBuilder);
        } catch (IllegalArgumentException e) {
            throw new ParseException(e.getMessage());
        }
    }

    //return builder.addNoise(noiseProducerBuilder.create());
    builder.addBuildSequence(noiseProducerBuilder);
    return builder;
}

From source file:de.tudarmstadt.ukp.dkpro.tc.weka.task.CrossValidationTask.java

@Override
public void execute(TaskContext aContext) throws Exception {

    File arffFile = new File(
            aContext.getStorageLocation(INPUT_KEY, AccessMode.READONLY).getPath() + "/" + TRAINING_DATA_KEY);

    Instances data = WekaUtils.getInstances(arffFile, multiLabel);

    Instances randData = new Instances(data);

    FOLDS = getFolds(randData);/*ww  w . j  av  a 2s  . com*/

    // this will make the Crossvalidation outcome unpredictable
    randData.randomize(new Random(new Date().getTime()));
    randData.stratify(FOLDS);

    Classifier cl;
    String[] mlArgs;

    for (int n = 0; n < FOLDS; n++) {
        aContext.message("Performing " + FOLDS + "-fold cross-validation (" + n + ", with "
                + Arrays.asList(classificationArguments) + ")");

        // Train-Test-split
        Instances train = randData.trainCV(FOLDS, n);
        Instances test = randData.testCV(FOLDS, n);

        if (multiLabel) {
            mlArgs = Arrays.copyOfRange(classificationArguments, 1, classificationArguments.length);
            cl = AbstractClassifier.forName(classificationArguments[0], new String[] {});
            ((MultilabelClassifier) cl).setOptions(mlArgs);
        } else {
            cl = AbstractClassifier.forName(classificationArguments[0],
                    Arrays.copyOfRange(classificationArguments, 1, classificationArguments.length));
        }

        Instances filteredTrainData;
        Instances filteredTestData;

        if (train.attribute(Constants.ID_FEATURE_NAME) != null) {

            int instanceIdOffset = // TaskUtils.getInstanceIdAttributeOffset(trainData);
                    train.attribute(Constants.ID_FEATURE_NAME).index() + 1;

            Remove remove = new Remove();
            remove.setAttributeIndices(Integer.toString(instanceIdOffset));
            remove.setInvertSelection(false);
            remove.setInputFormat(train);

            filteredTrainData = Filter.useFilter(train, remove);
            filteredTestData = Filter.useFilter(test, remove);
        } else {
            filteredTrainData = new Instances(train);
            filteredTestData = new Instances(test);
        }

        // train the classifier on the train set split
        cl.buildClassifier(filteredTrainData);

        // file to hold Crossvalidation results
        File evalOutput = new File(aContext.getStorageLocation(OUTPUT_KEY, AccessMode.READWRITE).getPath() + "/"
                + StringUtils.replace(EVALUATION_DATA_KEY, "#", String.valueOf(n)));

        // evaluation
        if (multiLabel) {
            Result r = Evaluation.evaluateModel((MultilabelClassifier) cl, filteredTrainData, filteredTestData,
                    threshold);
            Result.writeResultToFile(r, evalOutput.getAbsolutePath());
            // add predictions for test set
            double[] t = WekaUtils.getMekaThreshold(threshold, r, filteredTrainData);
            for (int j = 0; j < filteredTestData.numInstances(); j++) {
                Instance predicted = filteredTestData.instance(j);
                // multi-label classification results
                double[] labelPredictions = cl.distributionForInstance(predicted);
                for (int i = 0; i < labelPredictions.length; i++) {
                    predicted.setValue(i, labelPredictions[i] >= t[i] ? 1. : 0.);
                }
                test.add(predicted);
            }
            int numLabels = filteredTestData.classIndex();

            // add attributes to store gold standard classification
            Add filter = new Add();
            for (int i = 0; i < numLabels; i++) {
                filter.setAttributeIndex(new Integer(numLabels + i + 1).toString());
                filter.setNominalLabels("0,1");
                filter.setAttributeName(test.attribute(i).name() + "_classification");
                filter.setInputFormat(test);
                test = Filter.useFilter(test, filter);
            }
            // fill values of gold standard classification with original values from test set
            for (int i = 0; i < test.size(); i++) {
                for (int j = 0; j < numLabels; j++) {
                    test.instance(i).setValue(j + numLabels, test.instance(i).value(j));
                }
            }
        } else {
            weka.classifiers.Evaluation eval = new weka.classifiers.Evaluation(filteredTrainData);
            eval.evaluateModel(cl, filteredTestData);
            weka.core.SerializationHelper.write(evalOutput.getAbsolutePath(), eval);

            Add filter = new Add();

            filter.setAttributeIndex(new Integer(test.classIndex() + 1).toString());
            filter.setAttributeName("goldlabel");
            filter.setInputFormat(test);
            test = Filter.useFilter(test, filter);

            // fill values of gold standard classification with original values from test set
            for (int i = 0; i < test.size(); i++) {

                test.instance(i).setValue(test.classIndex() - 1, filteredTestData.instance(i).classValue());

            }

            for (int i = 0; i < filteredTestData.numInstances(); i++) {
                double prediction = cl.classifyInstance(filteredTestData.instance(i));
                Instance instance = test.instance(i);
                instance.setClassValue(prediction);
            }
        }

        // Write out the predictions
        DataSink.write(aContext.getStorageLocation(OUTPUT_KEY, AccessMode.READWRITE).getAbsolutePath() + "/"
                + StringUtils.replace(PREDICTIONS_KEY, "#", String.valueOf(n)), test);
    }
}

From source file:com.opengamma.analytics.math.interpolation.MonotonicityPreservingQuinticSplineInterpolator.java

@Override
public PiecewisePolynomialResult interpolate(final double[] xValues, final double[] yValues) {

    ArgumentChecker.notNull(xValues, "xValues");
    ArgumentChecker.notNull(yValues, "yValues");

    ArgumentChecker.isTrue(xValues.length == yValues.length | xValues.length + 2 == yValues.length,
            "(xValues length = yValues length) or (xValues length + 2 = yValues length)");
    ArgumentChecker.isTrue(xValues.length > 2, "Data points should be more than 2");

    final int nDataPts = xValues.length;
    final int yValuesLen = yValues.length;

    for (int i = 0; i < nDataPts; ++i) {
        ArgumentChecker.isFalse(Double.isNaN(xValues[i]), "xValues containing NaN");
        ArgumentChecker.isFalse(Double.isInfinite(xValues[i]), "xValues containing Infinity");
    }//from  w  w  w . ja  v a  2 s .  c  om
    for (int i = 0; i < yValuesLen; ++i) {
        ArgumentChecker.isFalse(Double.isNaN(yValues[i]), "yValues containing NaN");
        ArgumentChecker.isFalse(Double.isInfinite(yValues[i]), "yValues containing Infinity");
    }

    for (int i = 0; i < nDataPts - 1; ++i) {
        for (int j = i + 1; j < nDataPts; ++j) {
            ArgumentChecker.isFalse(xValues[i] == xValues[j], "xValues should be distinct");
        }
    }

    double[] xValuesSrt = Arrays.copyOf(xValues, nDataPts);
    double[] yValuesSrt = new double[nDataPts];
    if (nDataPts == yValuesLen) {
        yValuesSrt = Arrays.copyOf(yValues, nDataPts);
    } else {
        yValuesSrt = Arrays.copyOfRange(yValues, 1, nDataPts + 1);
    }
    ParallelArrayBinarySort.parallelBinarySort(xValuesSrt, yValuesSrt);

    final double[] intervals = _solver.intervalsCalculator(xValuesSrt);
    final double[] slopes = _solver.slopesCalculator(yValuesSrt, intervals);
    final PiecewisePolynomialResult result = _method.interpolate(xValues, yValues);

    ArgumentChecker.isTrue(result.getOrder() >= 3, "Primary interpolant should be degree >= 2");

    final double[] initialFirst = _function.differentiate(result, xValuesSrt).getData()[0];
    final double[] initialSecond = _function.differentiateTwice(result, xValuesSrt).getData()[0];
    double[] first = firstDerivativeCalculator(yValuesSrt, intervals, slopes, initialFirst);

    boolean modFirst = false;
    int k;
    double[] aValues = aValuesCalculator(slopes, first);
    double[] bValues = bValuesCalculator(slopes, first);
    double[][] intervalsA = getIntervalsA(intervals, slopes, first, bValues);
    double[][] intervalsB = getIntervalsB(intervals, slopes, first, aValues);
    while (modFirst == false) {
        k = 0;
        for (int i = 0; i < nDataPts - 2; ++i) {
            if (first[i + 1] > 0.) {
                if (intervalsA[i + 1][1] + Math.abs(intervalsA[i + 1][1]) * ERROR < intervalsB[i][0]
                        - Math.abs(intervalsB[i][0]) * ERROR
                        | intervalsA[i + 1][0] - Math.abs(intervalsA[i + 1][0]) * ERROR > intervalsB[i][1]
                                + Math.abs(intervalsB[i][1]) * ERROR) {
                    ++k;
                    first[i + 1] = firstDerivativesRecalculator(intervals, slopes, aValues, bValues, i + 1);
                }
            }
        }
        if (k == 0) {
            modFirst = true;
        }
        aValues = aValuesCalculator(slopes, first);
        bValues = bValuesCalculator(slopes, first);
        intervalsA = getIntervalsA(intervals, slopes, first, bValues);
        intervalsB = getIntervalsB(intervals, slopes, first, aValues);
    }
    final double[] second = secondDerivativeCalculator(initialSecond, intervalsA, intervalsB);
    final double[][] coefs = _solver.solve(yValuesSrt, intervals, slopes, first, second);

    for (int i = 0; i < nDataPts - 1; ++i) {
        for (int j = 0; j < 6; ++j) {
            ArgumentChecker.isFalse(Double.isNaN(coefs[i][j]), "Too large input");
            ArgumentChecker.isFalse(Double.isInfinite(coefs[i][j]), "Too large input");
        }
    }

    return new PiecewisePolynomialResult(new DoubleMatrix1D(xValuesSrt), new DoubleMatrix2D(coefs), 6, 1);
}

From source file:bachelorthesis.captchabuilder.builder.GimpyParser.java

private static CaptchaBuilder parseGimpyRenderer(GimpyRendererType gimpyRendererType, String[] gimpyOptions,
        CaptchaBuilder builder) throws ParseException {
    GimpyRendererBuilder gimpyRendererBuilder = new GimpyRendererBuilder(gimpyRendererType);

    if (gimpyOptions.length == 0) {
        //return builder.gimp(gimpyRendererBuilder.create());
        builder.addBuildSequence(gimpyRendererBuilder);
        return builder;
    }//w  w  w. ja  va 2s.c o  m

    if (gimpyOptions.length > GimpyRendererOptions.values().length) {
        throw new ParseException(
                "BackgroundProducer takes a max of " + GimpyRendererOptions.values().length + " arguments");
    }

    for (String gimpyRendererOption : gimpyOptions) {
        String[] optionArgs = gimpyRendererOption.split(CaptchaConstants.buildSequencelvl4Delim);
        try {
            GimpyRendererOptions gimpyRendererOptionType = GimpyRendererOptions.valueOf(optionArgs[0]);
            String[] gimpyRendererOptionArgs = Arrays.copyOfRange(optionArgs, 1, optionArgs.length);
            gimpyRendererBuilder = parseGimpyRendererOption(gimpyRendererOptionType, gimpyRendererOptionArgs,
                    gimpyRendererBuilder);
        } catch (IllegalArgumentException e) {
            throw new ParseException(e.getMessage());
        }
    }

    //return builder.gimp(gimpyRendererBuilder.create());
    builder.addBuildSequence(gimpyRendererBuilder);
    return builder;
}