Example usage for java.lang Double MAX_VALUE

List of usage examples for java.lang Double MAX_VALUE

Introduction

In this page you can find the example usage for java.lang Double MAX_VALUE.

Prototype

double MAX_VALUE

To view the source code for java.lang Double MAX_VALUE.

Click Source Link

Document

A constant holding the largest positive finite value of type double , (2-2-52)·21023.

Usage

From source file:com.luhonghai.litedb.ApplicationTest.java

/**
 * Just a very simple test/*ww  w . j  a  v  a2  s.  c  o m*/
 * @throws AnnotationNotFound
 * @throws InvalidAnnotationData
 * @throws LiteDatabaseException
 */
public void testLiteDatabase() throws LiteDatabaseException, AnnotationNotFound, InvalidAnnotationData {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm.SSS", Locale.getDefault());

    ContactDao contactDao = new ContactDao(databaseHelper);

    // Try to delete all current records
    if (databaseHelper.isTableExists(contactDao.getAnnotationHelper().getTableName()))
        contactDao.deleteAll();
    Contact contact = new Contact();
    contact.setName("1st Name");
    contact.setCreatedDate(new Date(System.currentTimeMillis()));
    contact.setCreatedDate1(contact.getCreatedDate());
    contact.setCreatedDate2(contact.getCreatedDate());
    // Try to insert new record
    long id = contactDao.insert(contact);
    // Try to get count
    assertEquals(1, contactDao.count("contact_name = ?", new String[] { "1st Name" }));
    // Try to get record by id
    Contact refContact = contactDao.get(id);
    assertEquals(refContact.getName(), contact.getName());
    assertEquals(refContact.getCreatedDate3(), null);
    // less than 2 millisecond difference is okay
    assertTrue(Math.abs(contact.getCreatedDate().getTime() - refContact.getCreatedDate().getTime()) <= 2);
    // less than 2 millisecond difference is okay
    assertTrue(Math.abs(contact.getCreatedDate().getTime() - refContact.getCreatedDate1().getTime()) <= 2);
    // less than 2 millisecond difference is okay
    assertTrue(Math.abs(contact.getCreatedDate().getTime() - refContact.getCreatedDate2().getTime()) <= 2);
    refContact.setName("2nd Name");
    refContact.setJob("Job");
    refContact.setAge(26);
    refContact.setSalary(3000.0f);
    refContact.setBalance(Double.MAX_VALUE);
    BlobData blobData = new BlobData(UUID.randomUUID().toString());
    refContact.setBlobData(blobData);
    // Try to update record
    contactDao.update(refContact);
    // Try to list all record
    List<Contact> contactList = contactDao.listAll();
    for (Contact mContact : contactList) {
        assertEquals("VN84000000000", mContact.getPhone());
        assertEquals("2nd Name", mContact.getName());
        assertEquals("Job", mContact.getJob());
        assertEquals(Double.MAX_VALUE, mContact.getBalance());
        assertEquals(3000.0f, mContact.getSalary());
        assertEquals(26, mContact.getAge());
        assertEquals(blobData, mContact.getBlobData());
    }

    contactDao.deleteByKey(id);
    assertEquals(0, contactDao.count());
}

From source file:ch.aonyx.broker.ib.api.order.Order.java

public Order() {
    limitPrice = Double.MAX_VALUE;
    stopPrice = Double.MAX_VALUE;
    transmit = true;/*  w w w.j  a  v  a  2 s.  c  o m*/
    designatedLocation = EMPTY;
    exemptionCode = -1;
    minimumQuantity = Integer.MAX_VALUE;
    percentageOffset = Double.MAX_VALUE;
    nbboPriceCap = Double.MAX_VALUE;
    startingPrice = Double.MAX_VALUE;
    stockReferencePrice = Double.MAX_VALUE;
    delta = Double.MAX_VALUE;
    lowerStockPriceRange = Double.MAX_VALUE;
    upperStockPriceRange = Double.MAX_VALUE;
    volatility = Double.MAX_VALUE;
    deltaNeutralOrderType = EMPTY;
    deltaNeutralAuxPrice = Double.MAX_VALUE;
    deltaNeutralSettlingFirm = EMPTY;
    deltaNeutralClearingAccount = EMPTY;
    deltaNeutralClearingIntent = EMPTY;
    trailingStopPrice = Double.MAX_VALUE;
    trailingPercent = Double.MAX_VALUE;
    basisPoint = Double.MAX_VALUE;
    basisPointType = Integer.MAX_VALUE;
    scaleInitialLevelSize = Integer.MAX_VALUE;
    scaleSubsequentLevelSize = Integer.MAX_VALUE;
    scalePriceIncrement = Double.MAX_VALUE;
    scalePriceAdjustValue = Double.MAX_VALUE;
    scalePriceAdjustInterval = Integer.MAX_VALUE;
    scaleProfitOffset = Double.MAX_VALUE;
    scaleInitPosition = Integer.MAX_VALUE;
    scaleInitFillQuantity = Integer.MAX_VALUE;
}

From source file:gov.va.isaac.gui.preferences.PreferencesViewController.java

public void aboutToShow() {
    // Using allValid_ to prevent rerunning content of aboutToShow()
    if (allValid_ == null) {
        // These listeners are for debug and testing only. They may be removed at any time.
        UserProfileBindings userProfileBindings = AppContext.getService(UserProfileBindings.class);
        for (Property<?> property : userProfileBindings.getAll()) {
            property.addListener(new ChangeListener<Object>() {
                @Override//from   w  w w  .j a  v  a2 s  . c o  m
                public void changed(ObservableValue<? extends Object> observable, Object oldValue,
                        Object newValue) {
                    logger.debug("{} property changed from {} to {}", property.getName(), oldValue, newValue);
                }
            });
        }

        // load fields before initializing allValid_
        // in case plugin.validationFailureMessageProperty() initialized by getNode()
        tabPane_.getTabs().clear();
        List<PreferencesPluginViewI> sortableList = new ArrayList<>();
        Comparator<PreferencesPluginViewI> comparator = new Comparator<PreferencesPluginViewI>() {
            @Override
            public int compare(PreferencesPluginViewI o1, PreferencesPluginViewI o2) {
                if (o1.getTabOrder() == o2.getTabOrder()) {
                    return o1.getName().compareTo(o2.getName());
                } else {
                    return o1.getTabOrder() - o2.getTabOrder();
                }
            }
        };
        for (PreferencesPluginViewI plugin : plugins_) {
            sortableList.add(plugin);
        }
        Collections.sort(sortableList, comparator);
        for (PreferencesPluginViewI plugin : sortableList) {
            logger.debug("Adding PreferencesPluginView tab \"{}\"", plugin.getName());
            Label tabLabel = new Label(plugin.getName());

            tabLabel.setMaxHeight(Double.MAX_VALUE);
            tabLabel.setMaxWidth(Double.MAX_VALUE);
            Tab pluginTab = new Tab();
            pluginTab.setGraphic(tabLabel);
            Region content = plugin.getContent();
            content.setMaxWidth(Double.MAX_VALUE);
            content.setMaxHeight(Double.MAX_VALUE);
            content.setPadding(new Insets(5.0));

            Label errorMessageLabel = new Label();
            errorMessageLabel.textProperty().bind(plugin.validationFailureMessageProperty());
            errorMessageLabel.setAlignment(Pos.BOTTOM_CENTER);
            TextErrorColorHelper.setTextErrorColor(errorMessageLabel);

            VBox vBox = new VBox();
            vBox.getChildren().addAll(errorMessageLabel, content);
            vBox.setMaxWidth(Double.MAX_VALUE);
            vBox.setAlignment(Pos.TOP_CENTER);

            plugin.validationFailureMessageProperty().addListener(new ChangeListener<String>() {
                @Override
                public void changed(ObservableValue<? extends String> observable, String oldValue,
                        String newValue) {
                    if (newValue != null && !StringUtils.isEmpty(newValue)) {
                        TextErrorColorHelper.setTextErrorColor(tabLabel);
                    } else {
                        TextErrorColorHelper.clearTextErrorColor(tabLabel);
                    }
                }
            });
            //Initialize, if stored value is wrong
            if (StringUtils.isNotEmpty(plugin.validationFailureMessageProperty().getValue())) {
                TextErrorColorHelper.setTextErrorColor(tabLabel);
            }
            pluginTab.setContent(vBox);
            tabPane_.getTabs().add(pluginTab);
        }

        allValid_ = new ValidBooleanBinding() {
            {
                ArrayList<ReadOnlyStringProperty> pluginValidationFailureMessages = new ArrayList<>();
                for (PreferencesPluginViewI plugin : plugins_) {
                    pluginValidationFailureMessages.add(plugin.validationFailureMessageProperty());
                }
                bind(pluginValidationFailureMessages
                        .toArray(new ReadOnlyStringProperty[pluginValidationFailureMessages.size()]));
                setComputeOnInvalidate(true);
            }

            @Override
            protected boolean computeValue() {
                for (PreferencesPluginViewI plugin : plugins_) {
                    if (plugin.validationFailureMessageProperty().get() != null
                            && plugin.validationFailureMessageProperty().get().length() > 0) {
                        this.setInvalidReason(plugin.validationFailureMessageProperty().get());

                        logger.debug("Setting PreferencesView allValid_ to false because \"{}\"",
                                this.getReasonWhyInvalid().get());
                        return false;
                    }
                }

                logger.debug("Setting PreferencesView allValid_ to true");

                this.clearInvalidReason();
                return true;
            }
        };

        okButton_.disableProperty().bind(allValid_.not());
        // set focus on default
        // Platform.runLater(...);
    }

    // Reload persisted values every time view opened
    for (PreferencesPluginViewI plugin : plugins_) {
        plugin.getContent();
    }
}

From source file:mzmatch.ipeak.align.CowCoda.java

@SuppressWarnings("unchecked")
public static void main(String args[]) {
    final String lbl_mcq = "mcq";

    try {/*from  w w  w. j  a va  2 s . c  o  m*/
        Tool.init();

        // parse the commandline options
        final Options options = new Options();
        CmdLineParser cmdline = new CmdLineParser(options);

        // check whether we need to show the help
        cmdline.parse(args);
        if (options.help) {
            Tool.printHeader(System.out, application, version);
            cmdline.printUsage(System.out, "");
            return;
        }

        if (options.verbose) {
            Tool.printHeader(System.out, application, version);
            cmdline.printOptions();
        }

        // check the command-line parameters
        int filetype = JFreeChartTools.PDF;
        {
            if (options.ppm == -1) {
                System.err.println("[ERROR]: the ppm-value needs to be set.");
                System.exit(0);
            }
            if (options.order == -1) {
                System.err.println("[ERROR]: the order for the polynomial fit needs to be set.");
                System.exit(0);
            }
            if (options.maxrt == -1) {
                System.err.println("[ERROR]: the maximum retention time shift is not set.");
                System.exit(0);
            }

            if (options.image != null) {
                String extension = options.image.substring(options.image.lastIndexOf('.') + 1);
                if (extension.toLowerCase().equals("png"))
                    filetype = JFreeChartTools.PNG;
                else if (extension.toLowerCase().equals("pdf"))
                    filetype = JFreeChartTools.PDF;
                else {
                    System.err.println(
                            "[ERROR]: file extension of the image file needs to be either PDF or PNG.");
                    System.exit(0);
                }
            }

            // if the output directories do not exist, create them
            if (options.output != null)
                Tool.createFilePath(options.output, true);
            if (options.image != null)
                Tool.createFilePath(options.image, true);
            if (options.selection != null)
                Tool.createFilePath(options.selection, true);
        }

        // load the data
        if (options.verbose)
            System.out.println("Loading the data");
        double maxrt = 0;
        Vector<ParseResult> data = new Vector<ParseResult>();
        Vector<IPeakSet<IPeak>> matchdata = new Vector<IPeakSet<IPeak>>();
        for (String file : options.input) {
            System.out.println("- " + new File(file).getName());

            // load the mass chromatogram data
            ParseResult result = PeakMLParser.parse(new FileInputStream(file), true);
            data.add(result);

            // select the best mass chromatograms
            Vector<IPeak> selection = new Vector<IPeak>();
            for (IPeak peak : (IPeakSet<IPeak>) result.measurement) {
                maxrt = Math.max(maxrt, maxRT(peak));

                double mcq = codaDW(peak);
                peak.addAnnotation(lbl_mcq, Double.toString(mcq), Annotation.ValueType.DOUBLE);
                if (mcq >= options.codadw)
                    selection.add(peak);
            }

            // keep track of the selected mass chromatograms
            int id = options.input.indexOf(file);
            IPeakSet<IPeak> peakset = new IPeakSet<IPeak>(selection);
            peakset.setMeasurementID(id);
            for (IPeak mc : peakset)
                mc.setMeasurementID(id);
            matchdata.add(peakset);
        }

        // match the selection together
        if (options.verbose)
            System.out.println("Matching the data");
        Vector<IPeakSet<IPeak>> matches = IPeak.match((Vector) matchdata, options.ppm,
                new IPeak.MatchCompare<IPeak>() {
                    public double distance(IPeak peak1, IPeak peak2) {
                        double diff = Math.abs(peak1.getRetentionTime() - peak2.getRetentionTime());
                        if (diff > options.maxrt)
                            return -1;

                        Signal signal1 = new Signal(peak1.getSignal());
                        signal1.normalize();
                        Signal signal2 = new Signal(peak2.getSignal());
                        signal2.normalize();

                        double offset = bestOffSet(peak1, peak2, options.maxrt);
                        for (int i = 0; i < signal2.getSize(); ++i)
                            signal2.getX()[i] += offset;

                        double correlation = signal2
                                .pearsonsCorrelation(signal1)[Statistical.PEARSON_CORRELATION];
                        if (correlation < 0.5)
                            return -1;

                        // the match-function optimizes toward 0 (it's a distance)
                        return 1 - correlation;
                    }
                });

        // filter out all incomplete sets
        Vector<IPeakSet<IPeak>> valids = new Vector<IPeakSet<IPeak>>();
        for (IPeakSet<IPeak> set : matches) {
            if (set.size() < options.input.size())
                continue;
            valids.add((IPeakSet) set);
        }

        // calculate the alignment factors
        if (options.verbose)
            System.out.println("Calculating the alignment factors");
        double medians[] = new double[valids.size() + 2];
        DataFrame.Double dataframe = new DataFrame.Double(valids.size() + 2, options.input.size());

        medians[0] = 0;
        medians[medians.length - 1] = maxrt;
        for (int i = 0; i < options.input.size(); ++i) {
            dataframe.set(0, i, 0.1);
            dataframe.set(dataframe.getNrRows() - 1, i, 0);
        }

        for (int matchid = 0; matchid < valids.size(); ++matchid) {
            IPeakSet<IPeak> match = valids.get(matchid);

            // find the most central
            double offsets[][] = new double[match.size()][match.size()];
            for (int i = 0; i < match.size(); ++i)
                for (int j = i + 1; j < match.size(); ++j) {
                    offsets[i][j] = bestOffSet(match.get(i), match.get(j), options.maxrt);
                    offsets[j][i] = -offsets[i][j];
                }

            int besti = 0;
            double bestabssum = Double.MAX_VALUE;
            for (int i = 0; i < match.size(); ++i) {
                double abssum = 0;
                for (int j = 0; j < match.size(); ++j)
                    abssum += Math.abs(offsets[i][j]);
                if (abssum < bestabssum) {
                    besti = i;
                    bestabssum = abssum;
                }
            }

            for (int i = 0; i < match.size(); ++i)
                dataframe.set(matchid + 1, match.get(i).getMeasurementID(),
                        (i == besti ? 0 : offsets[i][besti]));

            medians[matchid + 1] = match.get(besti).getRetentionTime();
            dataframe.setRowName(matchid, Double.toString(match.get(besti).getRetentionTime()));
        }
        double minmedian = Statistical.min(medians);
        double maxmedian = Statistical.max(medians);

        // calculate for each profile the correction function
        PolynomialFunction functions[] = new PolynomialFunction[valids.size()];
        for (int i = 0; i < options.input.size(); ++i)
            functions[i] = PolynomialFunction.fit(options.order, medians, dataframe.getCol(i));

        // make a nice plot out of the whole thing
        if (options.verbose)
            System.out.println("Writing results");
        if (options.image != null) {
            org.jfree.data.xy.XYSeriesCollection dataset = new org.jfree.data.xy.XYSeriesCollection();
            JFreeChart linechart = ChartFactory.createXYLineChart(null, "Retention Time (seconds)", "offset",
                    dataset, PlotOrientation.VERTICAL, true, // legend
                    false, // tooltips
                    false // urls
            );

            // setup the colorkey
            Colormap colormap = new Colormap(Colormap.EXCEL);

            // get the structure behind the graph
            XYPlot plot = (XYPlot) linechart.getPlot();
            XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();

            // setup the plot area
            linechart.setBackgroundPaint(java.awt.Color.WHITE);
            linechart.setBorderVisible(false);
            linechart.setAntiAlias(true);

            plot.setBackgroundPaint(java.awt.Color.WHITE);
            plot.setDomainGridlinesVisible(true);
            plot.setRangeGridlinesVisible(true);

            // create the datasets
            for (int i = 0; i < options.input.size(); ++i) {
                org.jfree.data.xy.XYSeries series = new org.jfree.data.xy.XYSeries(dataframe.getColName(i));
                org.jfree.data.xy.XYSeries function = new org.jfree.data.xy.XYSeries(
                        dataframe.getColName(i) + "-function");
                dataset.addSeries(series);
                dataset.addSeries(function);

                renderer.setSeriesPaint(dataset.getSeriesCount() - 1, new java.awt.Color(colormap.getColor(i)));
                renderer.setSeriesPaint(dataset.getSeriesCount() - 2, new java.awt.Color(colormap.getColor(i)));

                renderer.setSeriesLinesVisible(dataset.getSeriesCount() - 2, false);
                renderer.setSeriesShapesVisible(dataset.getSeriesCount() - 2, true);

                // add the data-points
                for (int j = 0; j < valids.size(); ++j)
                    series.add(medians[j], dataframe.get(j, i));
                for (double x = minmedian; x < maxmedian; ++x)
                    function.add(x, functions[i].getY(x));
            }

            dataset.removeAllSeries();
            for (int i = 0; i < options.input.size(); ++i) {
                Function function = functions[i];

                org.jfree.data.xy.XYSeries series = new org.jfree.data.xy.XYSeries(dataframe.getColName(i));
                dataset.addSeries(series);

                renderer.setSeriesPaint(i, new java.awt.Color(colormap.getColor(i)));
                renderer.setSeriesLinesVisible(i, false);
                renderer.setSeriesShapesVisible(i, true);

                // add the data-points
                for (int j = 0; j < valids.size(); ++j)
                    series.add(medians[j], dataframe.get(j, i) - function.getY(medians[j]));
            }

            JFreeChartTools.writeAs(filetype, new FileOutputStream(options.image), linechart, 800, 500);
        }

        // save the selected
        if (options.selection != null) {
            Header header = new Header();

            // set the number of peaks to be stored
            header.setNrPeaks(valids.size());

            // create a set for the measurements
            SetInfo set = new SetInfo("", SetInfo.SET);
            header.addSetInfo(set);

            // create the measurement infos
            for (int i = 0; i < options.input.size(); ++i) {
                String file = options.input.get(i);

                // create the measurement info
                MeasurementInfo measurement = new MeasurementInfo(i, data.get(i).header.getMeasurementInfo(0));
                measurement.addFileInfo(new FileInfo(file, file));

                header.addMeasurementInfo(measurement);

                // add the file to the set
                set.addChild(new SetInfo(file, SetInfo.SET, i));
            }

            // write the data
            PeakMLWriter.write(header, (Vector) valids, null,
                    new GZIPOutputStream(new FileOutputStream(options.selection)), null);
        }

        // correct the values with the found function and save them
        for (int i = 0; i < options.input.size(); ++i) {
            Function function = functions[i];
            ParseResult result = data.get(i);

            IPeakSet<MassChromatogram<Peak>> peakset = (IPeakSet<MassChromatogram<Peak>>) result.measurement;
            for (IPeak peak : peakset)
                align(peak, function);

            File filename = new File(options.input.get(i));
            String name = filename.getName();

            PeakMLWriter.write(result.header, (Vector) peakset.getPeaks(), null,
                    new GZIPOutputStream(new FileOutputStream(options.output + "/" + name)), null);
        }
    } catch (Exception e) {
        Tool.unexpectedError(e, application);
    }
}

From source file:za.org.opengov.stockout.service.impl.FacilityServiceImpl.java

/**
 * {@inheritDoc}//from   www .  j  a  v  a2s .co m
 */
@Override
public Facility getNearestFacilityWithStock(Product product, Facility originFacility) {
    List<Facility> facilitiesWithStock = getAllFacilitiesWithStock(product);
    double originLng = 0.0;
    double originLat = 0.0;

    if (originFacility.getLongitudeDecimalDegrees() != null) {
        originLng = originFacility.getLongitudeDecimalDegrees();
    }
    if (originFacility.getLatitudeDecimalDegress() != null) {
        originLat = originFacility.getLatitudeDecimalDegress();
    }

    Facility closestFacility = null;
    double bestDistance = Double.MAX_VALUE;

    // search for the nearest facility using Euclidean distance (as the crow
    // flies)
    // using the facility's coordinates
    for (Facility f : facilitiesWithStock) {
        double destLng = 0.0;
        double destLat = 0.0;
        if (f.getLongitudeDecimalDegrees() != null)
            destLng = f.getLongitudeDecimalDegrees();
        if (f.getLatitudeDecimalDegress() != null)
            destLat = f.getLatitudeDecimalDegress();

        double distance = Math.sqrt(
                (destLng - originLng) * (destLng - originLng) + (destLat - originLat) * (destLat - originLat));
        if (distance < bestDistance) {
            bestDistance = distance;
            closestFacility = f;
        }
    }

    return closestFacility;
}

From source file:com.rapidminer.operator.preprocessing.filter.InfiniteValueReplenishment.java

/**
 * Replaces the values/*ww  w  .  j  av a 2  s  .c o  m*/
 *
 * @throws UndefinedParameterError
 */
@Override
public double getReplenishmentValue(int functionIndex, ExampleSet exampleSet, Attribute attribute)
        throws UndefinedParameterError {
    int chosen = getParameterAsInt(PARAMETER_REPLENISHMENT_WHAT);
    switch (functionIndex) {
    case NONE:
        return Double.POSITIVE_INFINITY;
    case ZERO:
        return 0.0;
    case MAX_BYTE:
        return (chosen == 0) ? Byte.MAX_VALUE : Byte.MIN_VALUE;
    case MAX_INT:
        return (chosen == 0) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
    case MAX_DOUBLE:
        return (chosen == 0) ? Double.MAX_VALUE : -Double.MAX_VALUE;
    case MISSING:
        return Double.NaN;
    case VALUE:
        return getParameterAsDouble(PARAMETER_REPLENISHMENT_VALUE);
    default:
        throw new RuntimeException("Illegal value functionIndex: " + functionIndex);
    }
}

From source file:com.redhat.lightblue.metadata.types.BinaryTypeTest.java

License:asdf

@Test
public void testEqualsFalse() {
    assertFalse(binaryType.equals(Double.MAX_VALUE));
}

From source file:br.unicamp.ic.recod.gpsi.applications.gpsiJGAPSelectorEvolver.java

@Override
public void run() throws InvalidConfigurationException, InterruptedException, Exception {

    int i, j, k;// w w  w  . j  a  va2  s .co m
    byte nFolds = 5;
    gpsiDescriptor descriptor;
    gpsiMLDataset mlDataset;
    gpsiVoxelRawDataset dataset;
    GPGenotype gp;
    double[][] fitnessCurves;
    String[] curveLabels = new String[] { "train", "train_val", "val" };
    double bestScore, currentScore;
    IGPProgram current;
    IGPProgram[] elite = null;

    Mean mean = new Mean();
    StandardDeviation sd = new StandardDeviation();

    double validationScore, trainScore;
    double[][][] samples;

    for (byte f = 0; f < nFolds; f++) {

        System.out.println("\nRun " + (f + 1) + "\n");

        rawDataset.assignFolds(new byte[] { f, (byte) ((f + 1) % nFolds), (byte) ((f + 2) % nFolds) },
                new byte[] { (byte) ((f + 3) % nFolds) }, new byte[] { (byte) ((f + 4) % nFolds) });
        dataset = (gpsiVoxelRawDataset) rawDataset;
        gp = create(config, dataset.getnBands(), fitness, null);

        // 0: train, 1: train_val, 2: val
        fitnessCurves = new double[super.numGenerations + numGenerationsSel][];
        bestScore = -Double.MAX_VALUE;

        if (validation > 0)
            elite = new IGPProgram[validation];

        for (int generation = 0; generation < numGenerationsSel; generation++) {

            gp.evolve(1);
            gp.getGPPopulation().sortByFitness();

            if (validation > 0)
                elite = mergeElite(elite, gp.getGPPopulation().getGPPrograms(), generation);

            if (this.dumpGens) {

                double[][][] dists;
                descriptor = new gpsiScalarSpectralIndexDescriptor(
                        new gpsiJGAPVoxelCombiner(fitness.getB(), gp.getGPPopulation().getGPPrograms()[0]));
                mlDataset = new gpsiMLDataset(descriptor);
                mlDataset.loadWholeDataset(rawDataset, true);

                dists = (new gpsiWholeSampler()).sample(mlDataset.getTrainingEntities(), this.classLabels);
                for (i = 0; i < this.classLabels.length; i++) {
                    stream.register(new gpsiDoubleCsvIOElement(dists[i], null,
                            "gens/f" + (f + 1) + "/" + classLabels[i] + "/" + (generation + 1) + ".csv"));
                }

            }

            fitnessCurves[generation] = new double[] { gp.getAllTimeBest().getFitnessValue() - 1.0 };
            System.out.printf("%3dg: %.4f\n", generation + 1, fitnessCurves[generation][0]);

        }

        HashSet<Integer> variables = new HashSet<>();
        for (IGPProgram ind : elite) {
            for (CommandGene node : ind.getChromosome(0).getFunctions()) {
                if (node instanceof Variable) {
                    variables.add(Integer.parseInt(node.getName().replace('b', '0')));
                }
            }
        }

        int[] vars = variables.stream().mapToInt(p -> p).toArray();
        Arrays.sort(vars);
        stream.register(new gpsiStringIOElement(Arrays.toString(vars), "selected_bands/f" + (f + 1) + ".out"));

        gp = create(config, dataset.getnBands(), fitness, vars);
        gp.addFittestProgram(elite[0]);

        for (int generation = numGenerationsSel; generation < numGenerationsSel
                + super.numGenerations; generation++) {

            gp.evolve(1);
            gp.getGPPopulation().sortByFitness();

            if (validation > 0)
                elite = mergeElite(elite, gp.getGPPopulation().getGPPrograms(), generation);

            if (this.dumpGens) {

                double[][][] dists;
                descriptor = new gpsiScalarSpectralIndexDescriptor(
                        new gpsiJGAPVoxelCombiner(fitness.getB(), gp.getGPPopulation().getGPPrograms()[0]));
                mlDataset = new gpsiMLDataset(descriptor);
                mlDataset.loadWholeDataset(rawDataset, true);

                dists = (new gpsiWholeSampler()).sample(mlDataset.getTrainingEntities(), this.classLabels);
                for (i = 0; i < this.classLabels.length; i++) {
                    stream.register(new gpsiDoubleCsvIOElement(dists[i], null,
                            "gens/f" + (f + 1) + "/" + classLabels[i] + "/" + (generation + 1) + ".csv"));
                }

            }

            fitnessCurves[generation] = new double[] { gp.getAllTimeBest().getFitnessValue() - 1.0 };
            System.out.printf("%3dg: %.4f\n", generation + 1, fitnessCurves[generation][0]);

        }

        best = new IGPProgram[2];
        best[0] = gp.getAllTimeBest();
        for (i = 0; i < super.validation; i++) {

            current = elite[i];

            descriptor = new gpsiScalarSpectralIndexDescriptor(
                    new gpsiJGAPVoxelCombiner(fitness.getB(), current));
            mlDataset = new gpsiMLDataset(descriptor);
            mlDataset.loadWholeDataset(rawDataset, true);

            samples = this.fitness.getSampler().sample(mlDataset.getValidationEntities(), classLabels);

            validationScore = fitness.getScore().score(samples);
            trainScore = current.getFitnessValue() - 1.0;

            currentScore = mean.evaluate(new double[] { trainScore, validationScore })
                    - sd.evaluate(new double[] { trainScore, validationScore });

            if (currentScore > bestScore) {
                best[1] = current;
                bestScore = currentScore;
            }

        }

        stream.register(new gpsiDoubleCsvIOElement(fitnessCurves, curveLabels, "curves/f" + (f + 1) + ".csv"));

        System.out.println("Best solution for trainning: " + gp.getAllTimeBest().toStringNorm(0));
        stream.register(new gpsiStringIOElement(gp.getAllTimeBest().toStringNorm(0),
                "programs/f" + (f + 1) + "train.program"));

        if (validation > 0) {
            System.out.println("Best solution for trainning and validation: " + best[1].toStringNorm(0));
            stream.register(new gpsiStringIOElement(best[1].toStringNorm(0),
                    "programs/f" + (f + 1) + "train_val.program"));
        }

        descriptor = new gpsiScalarSpectralIndexDescriptor(new gpsiJGAPVoxelCombiner(fitness.getB(), best[0]));
        gpsi1NNToMomentScalarClassificationAlgorithm classificationAlgorithm = new gpsi1NNToMomentScalarClassificationAlgorithm(
                new Mean());
        gpsiClassifier classifier = new gpsiClassifier(descriptor, classificationAlgorithm);

        classifier.fit(this.rawDataset.getTrainingEntities());
        classifier.predict(this.rawDataset.getTestEntities());

        int[][] confusionMatrix = classifier.getConfusionMatrix();

        stream.register(new gpsiIntegerCsvIOElement(confusionMatrix, null,
                "confusion_matrices/f" + (f + 1) + "_train.csv"));

        if (validation > 0) {
            descriptor = new gpsiScalarSpectralIndexDescriptor(
                    new gpsiJGAPVoxelCombiner(fitness.getB(), best[1]));
            classificationAlgorithm = new gpsi1NNToMomentScalarClassificationAlgorithm(new Mean());
            classifier = new gpsiClassifier(descriptor, classificationAlgorithm);

            classifier.fit(this.rawDataset.getTrainingEntities());
            classifier.predict(this.rawDataset.getTestEntities());

            confusionMatrix = classifier.getConfusionMatrix();

            stream.register(new gpsiIntegerCsvIOElement(confusionMatrix, null,
                    "confusion_matrices/f" + (f + 1) + "_train_val.csv"));

        }

    }

}

From source file:com.github.cambierr.lorawanpacket.semtech.Rxpk.java

private Rxpk() {
    time = null;//from w w  w  .  j a  v  a  2 s  . co  m
    tmst = Integer.MAX_VALUE;
    freq = Double.MAX_VALUE;
    chan = Integer.MAX_VALUE;
    rfch = Integer.MAX_VALUE;
    stat = Integer.MAX_VALUE;
    modu = null;
    datr = null;
    codr = null;
    rssi = Integer.MAX_VALUE;
    lsnr = Double.MAX_VALUE;
    size = Integer.MAX_VALUE;
    data = null;
}

From source file:eu.optimis.mi.gui.client.userwidget.graph.GraphicReportDiagramPanel.java

public ChartModel getLineChartModel() {
    ChartModel cm = new ChartModel("");

    cm.setBackgroundColour("#FFFFFF");
    // Create general X- and Y-Label
    // Check Y-Label for unit!
    cm.setXLegend(new Text("Hours", "font-size: 14px; font-family: Verdana; text-align: center;"));
    cm.setYLegend(new Text(store.getAt(1).getMetricName() + " (" + store.getAt(1).getMetricUnit() + ")",
            "font-size: 14px; font-family: Verdana; text-align: center;"));

    // Values should be 24*x all the time!!!
    // point 1, timestamp
    int interval = getEndHour() - getStartHour();
    double valuesInInterval = store.getCount() / interval;
    // double steps = store.getCount() / 24.0;
    System.out.println(store.getCount() + "     " + valuesInInterval);
    // Create min and max values for the y-axis
    // Labeled xAxis.... perhaps there's a better solution available
    // Label and get the values at once!
    double old_val_max = 0;
    double old_val_min = Double.MAX_VALUE;
    double max_val = 0;
    double min_val = Double.MAX_VALUE;
    XAxis xa = new XAxis();
    // Steps/* w  w w .ja  va2s  . c om*/
    xa.setSteps(valuesInInterval);

    // Point 2
    Label l;
    for (int i = 0; i < store.getCount(); i++) {
        max_val = Math.max(old_val_max, Double.parseDouble(store.getAt(i).getMetricValue()));
        old_val_max = max_val;
        min_val = Math.min(old_val_min, Double.parseDouble(store.getAt(i).getMetricValue()));
        old_val_min = min_val;
        // Again, i/Steps
        if (i == 0) {
            // l = new Label("0");
            l = new Label(Integer.toString(getStartHour()));
            l.setSize(10);
            xa.addLabels(l);
        } else if (i == store.getCount() - 1) {
            l = new Label(Integer.toString(getEndHour()));
            // l = new Label("24");
            l.setSize(10);
            xa.addLabels(l);
        } else {
            l = new Label("");
            xa.addLabels(l);
        }
    }
    xa.setGridColour("#E0E0E0");
    xa.setOffset(false);
    cm.setXAxis(xa);

    // If max = min, set new values to get a better visualization
    if (min_val == max_val) {
        // min_val -= steps * 2;
        // max_val += steps * 2;
        min_val -= valuesInInterval * 2;
        max_val += valuesInInterval * 2;
    }

    YAxis ya = new YAxis();
    // Calculate Steps and max
    // ya.setRange(min_val, max_val,
    // (max_val-min_val)/(store.getCount()/steps));
    ya.setRange(min_val, max_val, (max_val - min_val) / 6.0);
    ya.setGridColour("#E0E0E0");
    ya.setOffset(false);
    cm.setYAxis(ya);

    // Chart with LineProvider
    LineChart lchart = new LineChart();
    lchart.setColour("#FF0000");
    lchart.setAnimateOnShow(false);
    LineDataProvider lineProvider = new LineDataProvider("metric_value");
    lineProvider.bind(store);
    lchart.setDataProvider(lineProvider);
    cm.addChartConfig(lchart);

    return cm;

}