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:classif.Prototyper.java

public double classifyInstance(Instance sample) throws Exception {
    // transform instance to sequence
    MonoDoubleItemSet[] sequence = new MonoDoubleItemSet[sample.numAttributes() - 1];
    int shift = (sample.classIndex() == 0) ? 1 : 0;
    for (int t = 0; t < sequence.length; t++) {
        sequence[t] = new MonoDoubleItemSet(sample.value(t + shift));
    }//  w  ww . j  a v a  2  s . co m
    Sequence seq = new Sequence(sequence);

    double minD = Double.MAX_VALUE;
    String classValue = null;
    for (ClassedSequence s : prototypes) {
        double tmpD = seq.distance(s.sequence);
        if (tmpD < minD) {
            minD = tmpD;
            classValue = s.classValue;
        }
    }
    // System.out.println(prototypes.size());
    return sample.classAttribute().indexOfValue(classValue);
}

From source file:eu.ggnet.dwoss.receipt.shipment.ShipmentUpdateStage.java

private void init(Shipment s) {

    okButton.setOnAction((ActionEvent event) -> {
        shipment = getShipment();/*from   ww  w  .  ja va 2  s .co m*/
        if (isValid())
            close();
    });

    cancelButton.setOnAction((ActionEvent event) -> {
        close();
    });

    idField = new TextField(Long.toString(s.getId()));
    idField.setDisable(true);
    shipIdField = new TextField(s.getShipmentId());

    Callback<ListView<TradeName>, ListCell<TradeName>> cb = new Callback<ListView<TradeName>, ListCell<TradeName>>() {
        @Override
        public ListCell<TradeName> call(ListView<TradeName> param) {
            return new ListCell<TradeName>() {
                @Override
                protected void updateItem(TradeName item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item == null || empty)
                        setText("Hersteller whlen...");
                    else
                        setText(item.getName());
                }
            };
        }
    };

    Set<TradeName> contractors = Client.lookup(MandatorSupporter.class).loadContractors().all();
    ownerBox = new ComboBox<>(FXCollections.observableArrayList(contractors));
    ownerBox.setMaxWidth(MAX_VALUE);
    ownerBox.setCellFactory(cb);
    ownerBox.getSelectionModel().selectedItemProperty().addListener(
            (ObservableValue<? extends TradeName> observable, TradeName oldValue, TradeName newValue) -> {
                if (newValue == null)
                    return;
                shipment.setContractor(newValue);
                manufacturerBox.getSelectionModel().select(newValue.getManufacturer());
            });

    ObservableList<TradeName> manufacturers = FXCollections.observableArrayList(TradeName.getManufacturers());
    manufacturerBox = new ComboBox<>(manufacturers);
    manufacturerBox.setMaxWidth(MAX_VALUE);
    manufacturerBox.setCellFactory(cb);
    SingleSelectionModel<TradeName> sm = ownerBox.getSelectionModel();
    if (s.getContractor() == null)
        sm.selectFirst();
    else
        sm.select(s.getContractor());
    if (shipment.getDefaultManufacturer() != null)
        manufacturerBox.getSelectionModel().select(shipment.getDefaultManufacturer());

    statusBox = new ComboBox<>(FXCollections.observableArrayList(Shipment.Status.values()));
    statusBox.setMaxWidth(MAX_VALUE);
    statusBox.getSelectionModel().select(s.getStatus() == null ? OPENED : s.getStatus());

    GridPane grid = new GridPane();
    grid.addRow(1, new Label("ID:"), idField);
    grid.addRow(2, new Label("Shipment ID:"), shipIdField);
    grid.addRow(3, new Label("Besitzer:"), ownerBox);
    grid.addRow(4, new Label("Hersteller:"), manufacturerBox);
    grid.addRow(5, new Label("Status"), statusBox);
    grid.setMaxWidth(MAX_VALUE);
    grid.vgapProperty().set(2.);
    grid.getColumnConstraints().add(0,
            new ColumnConstraints(100, 100, Double.MAX_VALUE, Priority.SOMETIMES, HPos.LEFT, false));
    grid.getColumnConstraints().add(1,
            new ColumnConstraints(100, 150, Double.MAX_VALUE, Priority.ALWAYS, HPos.LEFT, true));

    HBox hButtonBox = new HBox(okButton, cancelButton);
    hButtonBox.alignmentProperty().set(Pos.TOP_RIGHT);

    errorLabel.setWrapText(true);
    BorderPane rootPane = new BorderPane(grid, errorLabel, null, hButtonBox, null);

    this.setTitle(s.getId() > 0 ? "Shipment bearbeiten" : "Shipment anlegen");
    this.setScene(new Scene(rootPane));
    this.setResizable(false);
}

From source file:com.github.rvesse.airline.restrictions.factories.RangeRestrictionFactory.java

protected RangeRestriction createDoubleRange(Annotation annotation) {
    DoubleRange sRange = (DoubleRange) annotation;
    return new RangeRestriction(
            sRange.min() != Double.MIN_VALUE || !sRange.minInclusive() ? Double.valueOf(sRange.min()) : null,
            sRange.minInclusive(),// w w  w. ja  v a 2  s.  co m
            sRange.max() != Double.MAX_VALUE || !sRange.maxInclusive() ? Double.valueOf(sRange.max()) : null,
            sRange.maxInclusive(), DOUBLE_COMPARATOR);
}

From source file:at.thinkingco2.serverapplication.JourneyCalculation.java

/**
 * Method calculates which journey out of the journeyList is best fitting to
 * take the journeyNew with it./*w  w  w . jav a2  s . c om*/
 * 
 * @param journeyListWihtDriver
 *            List of journeys which can be used to take the journeyNew with
 *            them
 * @param journeyWithoutDriver
 *            Journey which should be added to one of the journeys in the
 *            journeyList
 * @return true if match found for journeyWithoutDriver otherwise false.
 */
private boolean calculateBestFittingJourney(List<JourneyBean> journeyListWihtDriver,
        JourneyBean journeyWithoutDriver) {
    this.clearObject();

    Timestamp time = journeyWithoutDriver.getArrivleTime();
    Integer numberChildrenAdd = journeyWithoutDriver.getChildren().size();
    boolean matchFound = false;

    List<JourneyBean> waypointList = new ArrayList<JourneyBean>();

    List<JourneyBean> tmpList = new ArrayList<JourneyBean>();

    Integer usedSeats;

    for (JourneyBean i : journeyListWihtDriver) {
        if (i.getRouteId() == null) {
            Set<ChildBean> childSet = i.getChildren();
            usedSeats = childSet.size() + 1;
        } else {
            usedSeats = jAccess.getUsedSeats(i.getRouteId());
        }
        if (ThinkingCO2Time.timestampsInIntervall(i.getArrivleTime(), time, timeIntervall)
                && (usedSeats + numberChildrenAdd) < CarAccess.getInstance()
                        .getCarByLicenseNumber(i.getLicenseNumber()).getSeats()) {
            tmpList.add(i);
        }
    }

    MinimalJourney minJ = new MinimalJourney();
    Double duration;
    Double durationWithWaypoint;
    Double timeDiff = Double.MAX_VALUE;
    Integer routeID;

    for (JourneyBean i : tmpList) {
        waypointList.clear();

        if ((routeID = i.getRouteId()) != null) {
            waypointList.addAll(this.jAccess.getJourneysByRouteID(routeID));
            waypointList.remove(i);
        }

        minJ.minRoute(i, waypointList);
        duration = minJ.getDuration();

        waypointList.add(journeyWithoutDriver);

        minJ.minRoute(i, waypointList);
        durationWithWaypoint = minJ.getDuration();

        if ((durationWithWaypoint - duration) < timeDiff) {
            timeDiff = durationWithWaypoint - duration;
            this.bestFittingJourney = i;
            this.resultingAddressList = minJ.getAddressList();
            this.resultingJSON = minJ.getMinRouteJson();
            this.resultingJourneyList = waypointList;
            this.resultingJourneyList.add(i);
            matchFound = true;
        }
    }

    System.out.println("The new Journey: " + journeyWithoutDriver.toString());
    System.out.println("can be added to");
    if (bestFittingJourney != null) {
        System.out.println(bestFittingJourney.toString());
    } else {
        System.out.println("nobody");
    }
    System.out.println("Resulting AddressList: ");
    for (AddressBean i : this.resultingAddressList) {
        System.out.println(i.getCountry() + " " + i.getZip() + " " + i.getCity() + " " + i.getStreet() + " "
                + i.getHousenumber());
    }
    return matchFound;
}

From source file:com.beoui.geocell.GeocellManager.java

/**
 * Returns an efficient set of geocells to search in a bounding box query.
        //from  w ww.  j a  va2 s.c  om
  This method is guaranteed to return a set of geocells having the same
  resolution (except in the case of antimeridian search i.e when east < west).
        
 * @param bbox: A geotypes.Box indicating the bounding box being searched.
 * @param costFunction: A function that accepts two arguments:
 * numCells: the number of cells to search
 * resolution: the resolution of each cell to search
    and returns the 'cost' of querying against this number of cells
    at the given resolution.)
 * @return A list of geocell strings that contain the given box.
 */
public static List<String> bestBboxSearchCells(BoundingBox bbox, CostFunction costFunction) {
    if (bbox.getEast() < bbox.getWest()) {
        BoundingBox bboxAntimeridian1 = new BoundingBox(bbox.getNorth(), bbox.getEast(), bbox.getSouth(),
                GeocellUtils.MIN_LONGITUDE);
        BoundingBox bboxAntimeridian2 = new BoundingBox(bbox.getNorth(), GeocellUtils.MAX_LONGITUDE,
                bbox.getSouth(), bbox.getWest());
        List<String> antimeridianList = bestBboxSearchCells(bboxAntimeridian1, costFunction);
        antimeridianList.addAll(bestBboxSearchCells(bboxAntimeridian2, costFunction));
        return antimeridianList;
    }

    String cellNE = GeocellUtils.compute(bbox.getNorthEast(), GeocellManager.MAX_GEOCELL_RESOLUTION);
    String cellSW = GeocellUtils.compute(bbox.getSouthWest(), GeocellManager.MAX_GEOCELL_RESOLUTION);

    // The current lowest BBOX-search cost found; start with practical infinity.
    double minCost = Double.MAX_VALUE;

    // The set of cells having the lowest calculated BBOX-search cost.
    List<String> minCostCellSet = new ArrayList<String>();

    // First find the common prefix, if there is one.. this will be the base
    // resolution.. i.e. we don't have to look at any higher resolution cells.
    int minResolution = 0;
    int maxResoltuion = Math.min(cellNE.length(), cellSW.length());
    while (minResolution < maxResoltuion
            && cellNE.substring(0, minResolution + 1).startsWith(cellSW.substring(0, minResolution + 1))) {
        minResolution++;
    }

    // Iteravely calculate all possible sets of cells that wholely contain
    // the requested bounding box.
    for (int curResolution = minResolution; curResolution < GeocellManager.MAX_GEOCELL_RESOLUTION
            + 1; curResolution++) {
        String curNE = cellNE.substring(0, curResolution);
        String curSW = cellSW.substring(0, curResolution);

        int numCells = GeocellUtils.interpolationCount(curNE, curSW);
        if (numCells > MAX_FEASIBLE_BBOX_SEARCH_CELLS) {
            continue;
        }

        List<String> cellSet = GeocellUtils.interpolate(curNE, curSW);
        Collections.sort(cellSet);

        double cost;
        if (costFunction == null) {
            cost = DEFAULT_COST_FUNCTION.defaultCostFunction(cellSet.size(), curResolution);
        } else {
            cost = costFunction.defaultCostFunction(cellSet.size(), curResolution);
        }

        if (cost <= minCost) {
            minCost = cost;
            minCostCellSet = cellSet;
        } else {
            if (minCostCellSet.size() == 0) {
                minCostCellSet = cellSet;
            }
            // Once the cost starts rising, we won't be able to do better, so abort.
            break;
        }
    }
    logger.log(Level.INFO, "Calculate cells " + StringUtils.join(minCostCellSet, ", ") + " in box ("
            + bbox.getSouth() + "," + bbox.getWest() + ") (" + bbox.getNorth() + "," + bbox.getEast() + ")");
    return minCostCellSet;
}

From source file:com.ricemap.spateDB.core.GridRecordWriter.java

/**
 * Creates a new GridRecordWriter that will write all data files to the
 * given directory/*from w ww .j av a  2  s.com*/
 * @param outDir - The directory in which all files will be stored
 * @param job - The MapReduce job associated with this output
 * @param prefix - A unique prefix to be associated with files of this writer
 * @param cells - Cells to partition the file
 * @param pack - After writing each cell, pack its MBR around contents
 * @throws IOException
 */
public GridRecordWriter(Path outDir, JobConf job, String prefix, CellInfo[] cells, boolean pack, boolean expand)
        throws IOException {
    this.pack = pack;
    this.expand = expand;
    this.prefix = prefix;
    this.fileSystem = outDir == null ? FileOutputFormat.getOutputPath(job).getFileSystem(job)
            : outDir.getFileSystem(job != null ? job : new Configuration());
    this.outDir = outDir;
    this.jobConf = job;

    if (cells != null) {
        // Make sure cellIndex maps to array index. This is necessary for calls that
        // call directly write(int, Text)
        int highest_index = 0;

        for (CellInfo cell : cells) {
            if (cell.cellId > highest_index)
                highest_index = (int) cell.cellId;
        }

        // Create a master file that contains meta information about partitions
        masterFile = fileSystem.create(getMasterFilePath());

        this.cells = new CellInfo[highest_index + 1];
        for (CellInfo cell : cells)
            this.cells[(int) cell.cellId] = cell;

        // Prepare arrays that hold cells information
        intermediateCellStreams = new OutputStream[this.cells.length];
        intermediateCellPath = new Path[this.cells.length];
        cellsMbr = new Prism[this.cells.length];
    } else {
        intermediateCellStreams = new OutputStream[1];
        intermediateCellPath = new Path[1];
        cellsMbr = new Prism[1];
    }
    for (int i = 0; i < cellsMbr.length; i++) {
        cellsMbr[i] = new Prism(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE,
                -Double.MAX_VALUE, -Double.MAX_VALUE);
    }

    this.blockSize = job == null ? fileSystem.getDefaultBlockSize(this.outDir)
            : job.getLong(SpatialSite.LOCAL_INDEX_BLOCK_SIZE, fileSystem.getDefaultBlockSize(this.outDir));

    closingThreads = new ArrayList<Thread>();
    text = new Text();
}

From source file:edu.sjsu.pokemonclassifier.classification.UserPreferenceInfo.java

public Map<String, Integer> getRecommendPokemon() {
    // API for downard module
    //  Put all strongerCandidates to GMM model
    List<Pair<Integer, Double>> weightPairList = new ArrayList<>();
    GaussianMixtureModel model = gmmTrainer.getModel();
    for (int j = 0; j < model.getK(); j++) {
        weightPairList.add(Pair.of(j, model.weights()[j]));
    }/*from  w w w .  j a v  a  2  s .com*/

    Collections.sort(weightPairList, new Comparator<Pair<Integer, Double>>() {
        @Override
        public int compare(Pair<Integer, Double> o1, Pair<Integer, Double> o2) {
            if (o1.getValue() < o2.getKey())
                return -1;
            else if (o1.getValue().equals(o2.getValue()))
                return 0;
            else
                return 1;
        }
    });

    // Get top-5
    // 5 is temp number
    // <String, Interger> -> <PokemonName, Rank#>
    HashMap<String, Integer> rankedPokemon = new HashMap<String, Integer>();
    HashMap<Integer, String> strongerCandidatesMap = new HashMap<Integer, String>();

    for (String strongerCandidate : strongerCandidates) {

        strongerCandidatesMap.put(strongerCandidates.indexOf(strongerCandidate), strongerCandidate);
    }

    //        for (int i = 0; i < strongerCandidates.size(); i++) {
    //
    //           strongerCandidatesMap.put(i, strongerCandidates.get(i).toLowerCase());
    //        }

    // modified by sidmishraw for getting top 10 pokemons rather than 5
    int totalClusters = Math.min(model.getK(), 10);

    int rank = 1;

    for (int i = totalClusters - 1; i >= 0; i--) {
        int modelIdx = weightPairList.get(i).getKey();
        double[] meanVector = model.gaussians()[modelIdx].mean().toArray();

        double att = meanVector[0];
        double def = meanVector[1];
        double hp = meanVector[2];

        double minDist = Double.MAX_VALUE;
        int minIdx = 0;
        String bestFitName = null;

        for (int j = 0; j < strongerCandidatesMap.size(); j++) {

            String name = strongerCandidatesMap.get(j);

            if (name == null) {

                continue;
            }

            //name = name.toLowerCase();
            System.out.println("HARMLESS:::: name = " + name);
            System.out.println("HARMLESS:::: att2 = " + PokemonDict.getInstance().getAttack(name));
            System.out.println("HARMLESS:::: def2 = " + PokemonDict.getInstance().getDefense(name));
            System.out.println("HARMLESS:::: hp2 = " + PokemonDict.getInstance().getHP(name));

            int att2 = PokemonDict.getInstance().getAttack(name);
            int def2 = PokemonDict.getInstance().getDefense(name);
            int hp2 = PokemonDict.getInstance().getHP(name);

            double dist = Math
                    .sqrt((att - att2) * (att - att2) + (def - def2) * (def - def2) + (hp - hp2) * (hp - hp2));
            if (dist < minDist) {
                minDist = dist;
                minIdx = j;
                bestFitName = name;
            }
        }

        strongerCandidatesMap.remove(minIdx);
        rankedPokemon.put(bestFitName, rank);
        rank++;
    }

    return rankedPokemon;
}

From source file:edu.scripps.fl.curves.plot.CurvePlot.java

public void addCurveMeanAndStdDev(Curve curve, FitFunction fitFunction, String description) {
    double min = Double.MAX_VALUE, max = Double.MIN_VALUE;
    MultiValueMap validMap = new MultiValueMap();
    MultiValueMap invalidMap = new MultiValueMap();
    // group each concentration in a hash, average, then add point
    for (int ii = 0; ii < curve.getConcentrations().size(); ii++) {
        Double c = curve.getConcentrations().get(ii);
        Double r = curve.getResponses().get(ii);
        if (curve.getMask().get(ii))
            validMap.put(c, r);/*from w  w w  .j  a va  2 s.c o  m*/
        else
            invalidMap.put(c, r);
        min = Math.min(min, c);
        max = Math.max(max, c);
    }
    addCurve(curve, getSeries(validMap, description), getSeries(invalidMap, ""), fitFunction, min, max);
}

From source file:com.yahoo.labs.yamall.local.Yamall.java

public static void main(String[] args) {
    String[] remainingArgs = null;
    String inputFile = null;//from   ww w.j  a  v a2  s  .co m
    String predsFile = null;
    String saveModelFile = null;
    String initialModelFile = null;
    String lossName = null;
    String parserName = null;
    String linkName = null;
    String invertHashName = null;
    double learningRate = 1;
    String minPredictionString = null;
    String maxPredictionString = null;
    String fmNumberFactorsString = null;
    int bitsHash;
    int numberPasses;
    int holdoutPeriod = 10;

    boolean testOnly = false;
    boolean exponentialProgress;
    double progressInterval;

    options.addOption("h", "help", false, "displays this help");
    options.addOption("t", false, "ignore label information and just test");
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("binary")
            .desc("reports loss as binary classification with -1,1 labels").build());
    options.addOption(
            Option.builder().hasArg(false).required(false).longOpt("solo").desc("uses SOLO optimizer").build());
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("pcsolo")
            .desc("uses Per Coordinate SOLO optimizer").build());
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("pistol")
            .desc("uses PiSTOL optimizer").build());
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("kt")
            .desc("(EXPERIMENTAL) uses KT optimizer").build());
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("pckt")
            .desc("(EXPERIMENTAL) uses Per Coordinate KT optimizer").build());
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("pccocob")
            .desc("(EXPERIMENTAL) uses Per Coordinate COCOB optimizer").build());
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("cocob")
            .desc("(EXPERIMENTAL) uses COCOB optimizer").build());
    options.addOption(
            Option.builder().hasArg(false).required(false).longOpt("fm").desc("Factorization Machine").build());
    options.addOption(Option.builder("f").hasArg(true).required(false).desc("final regressor to save")
            .type(String.class).longOpt("final_regressor").build());
    options.addOption(Option.builder("p").hasArg(true).required(false).desc("file to output predictions to")
            .longOpt("predictions").type(String.class).build());
    options.addOption(
            Option.builder("i").hasArg(true).required(false).desc("initial regressor(s) to load into memory")
                    .longOpt("initial_regressor").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false).desc(
            "specify the loss function to be used. Currently available ones are: absolute, squared (default), hinge, logistic")
            .longOpt("loss_function").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false).desc(
            "specify the link function used in the output of the predictions. Currently available ones are: identity (default), logistic")
            .longOpt("link").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false)
            .desc("output human-readable final regressor with feature names").longOpt("invert_hash")
            .type(String.class).build());
    options.addOption(
            Option.builder("l").hasArg(true).required(false).desc("set (initial) learning Rate, default = 1.0")
                    .longOpt("learning_rate").type(String.class).build());
    options.addOption(Option.builder("b").hasArg(true).required(false)
            .desc("number of bits in the feature table, default = 18").longOpt("bit_precision")
            .type(String.class).build());
    options.addOption(Option.builder("P").hasArg(true).required(false)
            .desc("progress update frequency, integer: additive; float: multiplicative, default = 2.0")
            .longOpt("progress").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false)
            .desc("smallest prediction to output, before the link function, default = -50")
            .longOpt("min_prediction").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false)
            .desc("smallest prediction to output, before the link function, default = 50")
            .longOpt("max_prediction").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false)
            .desc("ignore namespaces beginning with the characters in <arg>").longOpt("ignore")
            .type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false).desc("number of training passes")
            .longOpt("passes").type(String.class).build());
    options.addOption(
            Option.builder().hasArg(true).required(false).desc("holdout period for test only, default = 10")
                    .longOpt("holdout_period").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false)
            .desc("number of factors for Factorization Machines default = 8").longOpt("fmNumberFactors")
            .type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false)
            .desc("specify the parser to use. Currently available ones are: vw (default), libsvm, tsv")
            .longOpt("parser").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false).desc("schema file for the TSV input")
            .longOpt("schema").type(String.class).build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("Unrecognized option");
        help();
    }
    if (cmd.hasOption("h"))
        help();
    if (cmd.hasOption("t"))
        testOnly = true;
    if (cmd.hasOption("binary")) {
        binary = true;
        System.out.println("Reporting binary loss");
    }
    initialModelFile = cmd.getOptionValue("i");
    predsFile = cmd.getOptionValue("p");
    lossName = cmd.getOptionValue("loss_function", "squared");
    linkName = cmd.getOptionValue("link", "identity");
    saveModelFile = cmd.getOptionValue("f");
    learningRate = Double.parseDouble(cmd.getOptionValue("l", "1.0"));
    bitsHash = Integer.parseInt(cmd.getOptionValue("b", "18"));
    invertHashName = cmd.getOptionValue("invert_hash");
    minPredictionString = cmd.getOptionValue("min_prediction", "-50");
    maxPredictionString = cmd.getOptionValue("max_prediction", "50");
    fmNumberFactorsString = cmd.getOptionValue("fmNumberFactors", "8");
    parserName = cmd.getOptionValue("parser", "vw");

    numberPasses = Integer.parseInt(cmd.getOptionValue("passes", "1"));
    System.out.println("Number of passes = " + numberPasses);
    if (numberPasses > 1) {
        holdoutPeriod = Integer.parseInt(cmd.getOptionValue("holdout_period", "10"));
        System.out.println("Holdout period = " + holdoutPeriod);
    }

    remainingArgs = cmd.getArgs();
    if (remainingArgs.length == 1)
        inputFile = remainingArgs[0];

    InstanceParser instanceParser = null;
    if (parserName.equals("vw"))
        instanceParser = new VWParser(bitsHash, cmd.getOptionValue("ignore"), (invertHashName != null));
    else if (parserName.equals("libsvm"))
        instanceParser = new LIBSVMParser(bitsHash, (invertHashName != null));
    else if (parserName.equals("tsv")) {
        String schema = cmd.getOptionValue("schema");
        if (schema == null) {
            System.out.println("TSV parser requires a schema file.");
            System.exit(0);
        } else {
            String spec = null;
            try {
                spec = new String(Files.readAllBytes(Paths.get(schema)));
            } catch (IOException e) {
                System.out.println("Error reading the TSV schema file.");
                e.printStackTrace();
                System.exit(0);
            }
            instanceParser = new TSVParser(bitsHash, cmd.getOptionValue("ignore"), (invertHashName != null),
                    spec);
        }
    } else {
        System.out.println("Unknown parser.");
        System.exit(0);
    }
    System.out.println("Num weight bits = " + bitsHash);

    // setup progress
    String progress = cmd.getOptionValue("P", "2.0");
    if (progress.indexOf('.') >= 0) {
        exponentialProgress = true;
        progressInterval = (double) Double.parseDouble(progress);
    } else {
        exponentialProgress = false;
        progressInterval = (double) Integer.parseInt(progress);
    }

    // min and max predictions
    minPrediction = (double) Double.parseDouble(minPredictionString);
    maxPrediction = (double) Double.parseDouble(maxPredictionString);

    // number of factors for Factorization Machines
    fmNumberFactors = (int) Integer.parseInt(fmNumberFactorsString);

    // configure the learner
    Loss lossFnc = null;
    LinkFunction link = null;
    if (initialModelFile == null) {
        if (cmd.hasOption("kt")) {
            learner = new KT(bitsHash);
        } else if (cmd.hasOption("pckt")) {
            learner = new PerCoordinateKT(bitsHash);
        } else if (cmd.hasOption("pcsolo")) {
            learner = new PerCoordinateSOLO(bitsHash);
        } else if (cmd.hasOption("solo")) {
            learner = new SOLO(bitsHash);
        } else if (cmd.hasOption("pccocob")) {
            learner = new PerCoordinateCOCOB(bitsHash);
        } else if (cmd.hasOption("cocob")) {
            learner = new COCOB(bitsHash);
        } else if (cmd.hasOption("pistol")) {
            learner = new PerCoordinatePiSTOL(bitsHash);
        } else if (cmd.hasOption("fm")) {
            learner = new SGD_FM(bitsHash, fmNumberFactors);
        } else
            learner = new SGD_VW(bitsHash);
    } else {
        learner = IOLearner.loadLearner(initialModelFile);
    }

    // setup link function
    if (linkName.equals("identity")) {
        link = new IdentityLinkFunction();
    } else if (linkName.equals("logistic")) {
        link = new LogisticLinkFunction();
    } else {
        System.out.println("Unknown link function.");
        System.exit(0);
    }

    // setup loss function
    if (lossName.equals("squared")) {
        lossFnc = new SquareLoss();
    } else if (lossName.equals("hinge")) {
        lossFnc = new HingeLoss();
    } else if (lossName.equals("logistic")) {
        lossFnc = new LogisticLoss();
    } else if (lossName.equals("absolute")) {
        lossFnc = new AbsLoss();
    } else {
        System.out.println("Unknown loss function.");
        System.exit(0);
    }

    learner.setLoss(lossFnc);
    learner.setLearningRate(learningRate);

    // maximum range predictions
    System.out.println("Max prediction = " + maxPrediction + ", Min Prediction = " + minPrediction);
    // print information about the learner
    System.out.println(learner.toString());
    // print information about the link function
    System.out.println(link.toString());
    // print information about the parser
    System.out.println(instanceParser.toString());
    // print information about ignored namespaces
    System.out.println("Ignored namespaces = " + cmd.getOptionValue("ignore", ""));

    long start = System.nanoTime();
    FileInputStream fstream;
    try {
        BufferedReader br = null;
        if (inputFile != null) {
            fstream = new FileInputStream(inputFile);
            System.out.println("Reading datafile = " + inputFile);
            br = new BufferedReader(new InputStreamReader(fstream));
        } else {
            System.out.println("Reading from console");
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        File fout = null;
        FileOutputStream fos = null;
        BufferedWriter bw = null;
        if (predsFile != null) {
            fout = new File(predsFile);
            fos = new FileOutputStream(fout);
            bw = new BufferedWriter(new OutputStreamWriter(fos));
        }

        try {
            System.out.println("average       example  current  current  current");
            System.out.println("loss          counter    label  predict  features");
            int iter = 0;
            double cumLoss = 0;
            double weightedSampleSum = 0;
            double sPlus = 0;
            double sMinus = 0;
            Instance sample = null;
            boolean justPrinted = false;
            int pass = 0;
            ObjectOutputStream ooutTr = null;
            ObjectOutputStream ooutHO = null;
            ObjectInputStream oinTr = null;
            double pred = 0;
            int limit = 1;
            double hError = Double.MAX_VALUE;
            double lastHError = Double.MAX_VALUE;
            int numTestSample = 0;
            int numTrainingSample = 0;
            int idx = 0;

            if (numberPasses > 1) {
                ooutTr = new ObjectOutputStream(new FileOutputStream("cache_training.bin"));
                ooutHO = new ObjectOutputStream(new FileOutputStream("cache_holdout.bin"));
                oinTr = new ObjectInputStream(new FileInputStream("cache_training.bin"));
            }

            do {
                while (true) {
                    double score;

                    if (pass > 0 && numberPasses > 1) {
                        Instance tmp = (Instance) oinTr.readObject();
                        if (tmp != null)
                            sample = tmp;
                        else
                            break;
                    } else {
                        String strLine = br.readLine();
                        if (strLine != null)
                            sample = instanceParser.parse(strLine);
                        else
                            break;
                    }

                    justPrinted = false;
                    idx++;

                    if (numberPasses > 1 && pass == 0 && idx % holdoutPeriod == 0) {
                        // store the current sample for the holdout set
                        ooutHO.writeObject(sample);
                        ooutHO.reset();
                        numTestSample++;
                    } else {
                        if (numberPasses > 1 && pass == 0) {
                            ooutTr.writeObject(sample);
                            ooutTr.reset();
                            numTrainingSample++;
                        }

                        iter++;
                        if (testOnly) {
                            // predict the sample
                            score = learner.predict(sample);
                        } else {
                            // predict the sample and update the classifier using the sample
                            score = learner.update(sample);
                        }
                        score = Math.min(Math.max(score, minPrediction), maxPrediction);
                        pred = link.apply(score);
                        if (!binary)
                            cumLoss += learner.getLoss().lossValue(score, sample.getLabel())
                                    * sample.getWeight();
                        else if (Math.signum(score) != sample.getLabel())
                            cumLoss += sample.getWeight();

                        weightedSampleSum += sample.getWeight();
                        if (sample.getLabel() > 0)
                            sPlus = sPlus + sample.getWeight();
                        else
                            sMinus = sMinus + sample.getWeight();

                        // output predictions to file
                        if (predsFile != null) {
                            bw.write(String.format("%.6f %s", pred, sample.getTag()));
                            bw.newLine();
                        }

                        // print statistics to screen
                        if (iter == limit) {
                            justPrinted = true;
                            System.out.printf("%.6f %12d  % .4f  % .4f  %d\n", cumLoss / weightedSampleSum,
                                    iter, sample.getLabel(), pred, sample.getVector().size());
                            if (exponentialProgress)
                                limit *= progressInterval;
                            else
                                limit += progressInterval;
                        }
                    }
                }
                if (numberPasses > 1) {
                    if (pass == 0) { // finished first pass of many
                        // write a null at the end of the files
                        ooutTr.writeObject(null);
                        ooutHO.writeObject(null);
                        ooutTr.flush();
                        ooutHO.flush();
                        ooutTr.close();
                        ooutHO.close();

                        System.out.println("finished first epoch");
                        System.out.println(numTrainingSample + " training samples");
                        System.out.println(numTestSample + " holdout samples saved");
                    }
                    lastHError = hError;
                    hError = evalHoldoutError();
                }
                if (numberPasses > 1) {
                    System.out.printf("Weighted loss on holdout on epoch %d = %.6f\n", pass + 1, hError);

                    oinTr.close();
                    oinTr = new ObjectInputStream(new FileInputStream("cache_training.bin"));

                    if (hError > lastHError) {
                        System.out.println("Early stopping");
                        break;
                    }
                }
                pass++;
            } while (pass < numberPasses);

            if (justPrinted == false) {
                System.out.printf("%.6f %12d  % .4f  % .4f  %d\n", cumLoss / weightedSampleSum, iter,
                        sample.getLabel(), pred, sample.getVector().size());
            }
            System.out.println("finished run");

            System.out.println(String.format("average loss best constant predictor: %.6f",
                    lossFnc.lossConstantBinaryLabels(sPlus, sMinus)));

            if (saveModelFile != null)
                IOLearner.saveLearner(learner, saveModelFile);
            if (invertHashName != null)
                IOLearner.saveInvertHash(learner.getWeights(), instanceParser.getInvertHashMap(),
                        invertHashName);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // close the input stream
        try {
            br.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // close the output stream
        if (predsFile != null) {
            try {
                bw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        long millis = System.nanoTime() - start;
        System.out.printf("Elapsed time: %d min, %d sec\n", TimeUnit.NANOSECONDS.toMinutes(millis),
                TimeUnit.NANOSECONDS.toSeconds(millis) - 60 * TimeUnit.NANOSECONDS.toMinutes(millis));
    } catch (

    FileNotFoundException e) {
        System.out.println("Error opening the input file");
        e.printStackTrace();
    }

}

From source file:cc.mallet.types.PolyaUrnDirichlet.java

protected double nextStandardExponential() {
    for (;;) {// ww w .ja  v  a  2  s  .co  m
        double u = ThreadLocalRandom.current().nextDouble();
        double e = -FastMath.log(u);
        if (e > 0 && e < Double.MAX_VALUE && e == e) { // check for zero, positive infinity, and NaN
            return e;
        }
    }
}