Example usage for java.lang Math signum

List of usage examples for java.lang Math signum

Introduction

In this page you can find the example usage for java.lang Math signum.

Prototype

public static float signum(float f) 

Source Link

Document

Returns the signum function of the argument; zero if the argument is zero, 1.0f if the argument is greater than zero, -1.0f if the argument is less than zero.

Usage

From source file:com.google.android.apps.santatracker.doodles.tilt.SwimmerActor.java

@Override
public void update(float deltaMs) {
    super.update(deltaMs);

    ProcessChain.updateChains(processChains, deltaMs);

    // Update x position based on tilt.
    float frameVelocityX = TILT_VELOCITY * deltaMs / 1000;
    float positionDeltaX = targetX - position.x;
    if (Math.abs(positionDeltaX) < frameVelocityX) {
        // We will overshoot if we apply the frame velocity. Just go straight to the target position.
        moveTo(targetX, position.y);// w  w  w. j a  va 2  s  .  c om
    } else {
        moveTo(position.x + Math.signum(positionDeltaX) * frameVelocityX, position.y);
    }

    // Update acceleration and frame rate if necessary.
    if (velocity.getLength() > 1) {
        velocity.y = Math.max(-maxSpeed, velocity.y + ACCELERATION_Y * deltaMs / 1000);
        if (velocity.y == -maxSpeed) {
            multiSpriteActor.sprites.get(SWIM_LOOP_SPRITE).setFPS(24);
        } else {
            multiSpriteActor.sprites.get(SWIM_LOOP_SPRITE).setFPS(48);
        }
        currentSpeedStepTime += deltaMs;
        if (currentSpeedStepTime > SPEED_STEP_DURATION_MS) {
            maxSpeed += 500;
            currentSpeedStepTime = 0;
        }
    }

    ringsSprite.update(deltaMs);
    ringsSprite.setPosition(spriteActor.position.x + ringsSpriteOffset.x,
            spriteActor.position.y + ringsSpriteOffset.y);
}

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

/**
 * Estimate first derivatives at endpoints
 * @param ints1 First (last) interval/*from   w  w w  .  j a v a 2s  . c om*/
 * @param ints2 Second (second last) Interval
 * @param grads1 First (last) slope
 * @param grads2 Second (second last) slope
 * @return Slope at the first (last) data point
 */
private double endpointFirst(final double ints1, final double ints2, final double grads1, final double grads2) {
    final double val = (2. * ints1 + ints2) * grads1 / (ints1 + ints2) - ints1 * grads2 / (ints1 + ints2);

    if (Math.signum(val) != Math.signum(grads1)) {
        return 0.;
    }
    if (Math.signum(grads1) != Math.signum(grads2) && Math.abs(val) > 3. * Math.abs(grads1)) {
        return 3. * grads1;
    }
    return val;
}

From source file:com.opengamma.analytics.financial.interestrate.ParRateCalculator.java

/**
 * Computes the swap convention-modified par rate for a fixed coupon swap with a PVBP externally provided.
 * <P>Reference: Swaption pricing - v 1.3, OpenGamma Quantitative Research, June 2012.
 * @param swap The swap./* w ww  .  ja v  a 2 s.  co m*/
 * @param pvbp The present value of a basis point.
 * @param curves The curves.
 * @return The modified rate.
 */
public Double visitFixedCouponSwap(final SwapFixedCoupon<?> swap, final double pvbp,
        final YieldCurveBundle curves) {
    final double pvSecond = -PVC.visit(swap.getSecondLeg(), curves)
            * Math.signum(swap.getSecondLeg().getNthPayment(0).getNotional());
    return -pvSecond / pvbp;
}

From source file:ssc.SnowPressure.java

/**
 * Compares this object with the specified object to determine the order. 
 * Returns a negative integer, zero, or a positive integer as this 
 * object is less than, equal to, or greater than the specified 
 * object. /*  w  ww  .  java2  s  . c om*/
 * 
 * Note: this class has a natural ordering that is inconsistent 
 * with equals. Two readings is equal if timestamp and sensor 
 * is the same while comparing is done on timestamp only. 
 * 
 * @param obj The reading to be compared
 * 
 * @return A negative integer, zero, or a positive integer as this 
 * object is less than, equal to, or greater than the specified 
 * object. 
 * 
 * @throws NullPointerException if specified reading is null
 */
public int compareTo(SnowPressure obj) {

    if (obj == null) {

        throw new java.lang.NullPointerException("SnowPressure: Can't compare with null");
    }

    return (int) Math.signum(this.data_time.diffSeconds(obj.getDataTime()));

}

From source file:org.jcurl.zui.piccolo.BroomPromptSimple.java

public BroomPromptSimple() {
    final boolean stickUp = false;
    final boolean bothSides = true;
    final int pieAngle = 150;
    final Color sp = Color.BLACK;
    final Color bgc = new Color(1, 1, 1, 0.5f);
    final Stroke fine = new BasicStroke(0.01f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
    final Stroke bold = new BasicStroke(0.03f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
    // final Font fo = new Font("SansSerif", Font.BOLD, 1);
    final float halo = RockProps.DEFAULT.getRadius();
    final float outer = 0.8f * RockProps.DEFAULT.getRadius();
    stickLength = (stickUp ? 1 : -1) * 5 * outer;
    final float inner = 0.5F * outer;
    setPickable(false);//  w w  w.  j  a v  a 2s . co m
    final BroomPromptSimple self = this;
    handle = new PNode() {
        private static final long serialVersionUID = -7641452321842902940L;

        /**
         * Return true if this node or any pickable descendends are picked.
         * If a pick occurs the pickPath is modified so that this node is
         * always returned as the picked node, event if it was a decendent
         * node that initialy reported the pick.
         * 
         * @see PComposite
         */
        @Override
        public boolean fullPick(final PPickPath pickPath) {
            if (super.fullPick(pickPath)) {
                PNode picked = pickPath.getPickedNode();
                // this code won't work with internal cameras, because
                // it doesn't pop
                // the cameras view transform.
                while (picked != self) {
                    pickPath.popTransform(picked.getTransformReference(false));
                    pickPath.popNode(picked);
                    picked = pickPath.getPickedNode();
                }
                return true;
            }
            return false;
        }
    };
    { // opaque Background
        final PNode bg = node(new Arc2D.Float(-halo, -halo, 2 * halo, 2 * halo, 0, 360, Arc2D.OPEN), null, null,
                scale0);
        bg.setPaint(bgc);
        bg.setPickable(true);
        handle.addChild(bg);
    }
    { // Cross-hair circles and pie
        final int off = 90;
        final int pieOff = 180;
        final int arrowLengthDegrees = 7;
        // colored pie:
        pie = node(new Arc2D.Float(-outer, -outer, 2 * outer, 2 * outer, off - pieOff, pieAngle, Arc2D.PIE),
                null, null, scale0);
        handle.addChild(pie);
        // inner circle:
        handle.addChild(
                node(new Arc2D.Float(-inner, -inner, 2 * inner, 2 * inner, off, pieOff + pieAngle, Arc2D.OPEN),
                        fine, sp, scale50));
        // outer circle:
        handle.addChild(node(new Arc2D.Float(-outer, -outer, 2 * outer, 2 * outer, off,
                pieOff + pieAngle - (14 + arrowLengthDegrees), Arc2D.OPEN), fine, sp, scale50));
        handle.addChild(
                node(new Arc2D.Float(-outer, -outer, 2 * outer, 2 * outer, off, pieOff + pieAngle, Arc2D.OPEN),
                        fine, sp, -scale50));
        final double ar = Math.PI * (off + pieAngle) / 180.0;
        // radius
        // if (pieAngle % 90 != 0)
        handle.addChild(
                node(new Line2D.Double(0, 0, -outer * Math.cos(ar), outer * Math.sin(ar)), bold, sp, scale0));

        // arrow:
        final float f = outer / 10;
        final PPath s = node(IceShapes.createArrowHead(f, 3 * f, 0.5f * f), null, null, scale50);
        s.setPaint(sp);
        final double a = Math.PI * (off + pieAngle - arrowLengthDegrees) / 180.0;
        s.translate(-outer * Math.cos(a), outer * Math.sin(a));
        s.rotate(Math.PI * (90 - (off + pieAngle) + 8 + arrowLengthDegrees) / 180.0);
        handle.addChild(s);

        this.addChild(handle);
    }
    { // y-axis:
        handle.addChild(
                node(new Line2D.Float(0, -Math.signum(stickLength) * halo, 0, stickLength), fine, sp, scale0));
        // x-axis:
        handle.addChild(node(new Line2D.Float(-halo, 0, halo, 0), fine, sp, scale0));
    }
    { // slider
        slider = new PPath(IceShapes.createSlider(0.4f * outer, bothSides), fine);
        slider.setStrokePaint(sp);
        slider.setPickable(true);
        this.addChild(slider);
    }
    // Set up Event handling
    addInputEventListener(new PDragEventHandler() {

        /** double-click: flip handle */
        @Override
        public void mouseClicked(final PInputEvent arg0) {
            super.mouseClicked(arg0);
            if (arg0.getClickCount() > 1) {
                arg0.setHandled(true);
                first = new HandleMemento(getModel(), getModel().getOutTurn());
                last = new HandleMemento(getModel(), !getModel().getOutTurn());
                ChangeManager.getTrivial(changer).undoable(first, last);
                first = last = null;
            }
        }

        /** drag/move */
        @Override
        public void mouseDragged(final PInputEvent arg0) {
            arg0.setHandled(true);
            getModel().setValueIsAdjusting(true);
            if (false) {
                final Point2D p = arg0.getPositionRelativeTo(self.getParent());
                getModel().setBroom(p);
            } else
                view2model(new XYMemento(getModel(), arg0.getPositionRelativeTo(self.getParent())));
        }

        @Override
        public void mouseEntered(final PInputEvent arg0) {
            super.mouseEntered(arg0);
            arg0.pushCursor(MOVE_CURSOR);
        }

        @Override
        public void mouseExited(final PInputEvent arg0) {
            super.mouseExited(arg0);
            arg0.popCursor();
        }

        @Override
        public void mousePressed(final PInputEvent arg0) {
            arg0.setHandled(true);
            first = new XYMemento(getModel(), getModel().getBroom());
        }

        @Override
        public void mouseReleased(final PInputEvent pinputevent) {
            getModel().setValueIsAdjusting(false);
            if (first != null && last != null && first != last)
                ChangeManager.getTrivial(changer).undoable(first, last);
            first = last = null;
        }
    });
    slider.addInputEventListener(new PDragEventHandler() {
        @Override
        protected void endDrag(final PInputEvent pinputevent) {
            log.debug("speed");
        }

        /** adjust the slider */
        @Override
        public void mouseDragged(final PInputEvent arg0) {
            arg0.setHandled(true);
            final Point2D p = arg0.getPositionRelativeTo(self);
            final BoundedRangeModel r = self.getModel().getSplitTimeMillis();
            if (r == null)
                return;
            r.setValueIsAdjusting(true);
            view2model(new SplitMemento(getModel(), ratio2value(p.getY() / stickLength, r)));
        }

        @Override
        public void mouseEntered(final PInputEvent arg0) {
            super.mouseEntered(arg0);
            arg0.pushCursor(UPDN_CURSOR);
        }

        @Override
        public void mouseExited(final PInputEvent arg0) {
            super.mouseExited(arg0);
            arg0.popCursor();
        }

        @Override
        public void mousePressed(final PInputEvent arg0) {
            arg0.setHandled(true);
            first = new SplitMemento(getModel(), getModel().getSplitTimeMillis().getValue());
        }

        @Override
        public void mouseReleased(final PInputEvent pinputevent) {
            log.debug("speed");
            final BoundedRangeModel r = self.getModel().getSplitTimeMillis();
            if (r == null)
                return;
            r.setValueIsAdjusting(false);
            if (first != null && last != null && first != last)
                ChangeManager.getTrivial(changer).undoable(first, last);
            first = last = null;
        }
    });
}

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

public static void main(String[] args) {
    String[] remainingArgs = null;
    String inputFile = null;/*from w  ww  .ja  v  a 2  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:com.opengamma.analytics.math.interpolation.ShapePreservingCubicSplineInterpolator.java

/**
 * @param slopes/*from  w  ww .jav a2 s  .  co  m*/
 * @return sign(slopes_{i + 1} - slopes_i)
 */
private double[] betaCalculator(final double[] slopes) {
    final int nSlopes = slopes.length;
    final double[] res = new double[nSlopes + 1];

    for (int i = 0; i < nSlopes - 1; ++i) {
        res[i + 1] = Math.signum(slopes[i + 1] - slopes[i]);
    }
    res[0] = res[1];
    res[nSlopes] = res[nSlopes - 1];

    return res;
}

From source file:eu.amidst.core.utils.Utils.java

/**
 * Returns the Inverse digamma of a given {@code double} value.
 * <p> The digamma function is the derivative of the log gamma function.
 * It calculates the value Y &gt; 0 for a value X such that digamma(Y) = X.
 * This algorithm is from Paul Fackler and Harvard Univesity:
 * http://www4.ncsu.edu/~pfackler//*  w  ww .j a  va2 s .  c  o  m*/
 * http://hips.seas.harvard.edu/content/inverse-digamma-function-matlab </p>
 * @param X a {@code double} value.
 * @return a {@code double} value Y, such as Digamma(Y) = X.
 */
public static double invDigamma(double X) {
    double L = 1;
    double Y = Math.exp(X);
    while (L > 10e-8) {
        Y = Y + L * Math.signum(X - org.apache.commons.math3.special.Gamma.digamma(Y));
        L = L / 2;
    }
    return Y;
}

From source file:com.intellectualcrafters.plot.commands.list.java

@Override
public boolean execute(final PlotPlayer plr, final String... args) {
    if (args.length < 1) {
        noArgs(plr);//from w w  w  . j a va2  s . c  o  m
        return false;
    }
    int page = 0;
    if (args.length > 1) {
        try {
            page = Integer.parseInt(args[1]);
            --page;
            if (page < 0) {
                page = 0;
            }
        } catch (final Exception e) {
            page = 0;
        }
    }

    List<Plot> plots = null;

    String world;
    if (plr != null) {
        world = plr.getLocation().getWorld();
    } else {
        Set<String> worlds = PS.get().getPlotWorlds();
        if (worlds.size() == 0) {
            world = "world";
        } else {
            world = worlds.iterator().next();
        }
    }
    String arg = args[0].toLowerCase();
    boolean sort = true;
    switch (arg) {
    case "mine": {
        if (plr == null) {
            break;
        }
        if (!Permissions.hasPermission(plr, "plots.list.mine")) {
            MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.mine");
            return false;
        }
        plots = new ArrayList<>(PS.get().getPlots(plr));
        break;
    }
    case "shared": {
        if (plr == null) {
            break;
        }
        if (!Permissions.hasPermission(plr, "plots.list.shared")) {
            MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.shared");
            return false;
        }
        plots = new ArrayList<Plot>();
        for (Plot plot : PS.get().getPlots()) {
            if (plot.trusted.contains(plr.getUUID()) || plot.members.contains(plr.getUUID())) {
                plots.add(plot);
            }
        }
        break;
    }
    case "world": {
        if (!Permissions.hasPermission(plr, "plots.list.world")) {
            MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.world");
            return false;
        }
        if (!Permissions.hasPermission(plr, "plots.list.world." + world)) {
            MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.world." + world);
            return false;
        }
        plots = new ArrayList<>(PS.get().getPlots(world).values());
        break;
    }
    case "all": {
        if (!Permissions.hasPermission(plr, "plots.list.all")) {
            MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.all");
            return false;
        }
        plots = new ArrayList<>(PS.get().getPlots());
        break;
    }
    case "top": {
        if (!Permissions.hasPermission(plr, "plots.list.top")) {
            MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.top");
            return false;
        }
        plots = new ArrayList<>(PS.get().getPlots());
        Collections.sort(plots, new Comparator<Plot>() {
            @Override
            public int compare(Plot p1, Plot p2) {
                double v1 = 0;
                double v2 = 0;
                if (p1.settings.ratings != null && p1.settings.ratings.size() > 0) {
                    for (Entry<UUID, Integer> entry : p1.settings.ratings.entrySet()) {
                        v1 += entry.getValue() * entry.getValue();
                    }
                    v1 /= p1.settings.ratings.size();
                    v2 += p2.settings.ratings.size();
                }
                if (p2.settings.ratings != null && p2.settings.ratings.size() > 0) {
                    for (Entry<UUID, Integer> entry : p2.settings.ratings.entrySet()) {
                        v2 += entry.getValue() * entry.getValue();
                    }
                    v2 /= p2.settings.ratings.size();
                    v2 += p2.settings.ratings.size();
                }
                if (v2 == v1 && v2 != 0) {
                    return p2.settings.ratings.size() - p1.settings.ratings.size();
                }
                return (int) Math.signum(v2 - v1);
            }
        });
        sort = false;
        break;
    }
    case "forsale": {
        if (!Permissions.hasPermission(plr, "plots.list.forsale")) {
            MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.forsale");
            return false;
        }
        if (EconHandler.manager == null) {
            break;
        }
        plots = new ArrayList<>();
        for (Plot plot : PS.get().getPlots()) {
            final Flag price = FlagManager.getPlotFlag(plot, "price");
            if (price != null) {
                plots.add(plot);
            }
        }
        break;
    }
    case "unowned": {
        if (!Permissions.hasPermission(plr, "plots.list.unowned")) {
            MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.unowned");
            return false;
        }
        plots = new ArrayList<>();
        for (Plot plot : PS.get().getPlots()) {
            if (plot.owner == null) {
                plots.add(plot);
            }
        }
        break;
    }
    case "unknown": {
        if (!Permissions.hasPermission(plr, "plots.list.unknown")) {
            MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.unknown");
            return false;
        }
        plots = new ArrayList<>();
        for (Plot plot : PS.get().getPlots()) {
            if (plot.owner == null) {
                continue;
            }
            if (UUIDHandler.getName(plot.owner) == null) {
                plots.add(plot);
            }
        }
        break;
    }
    default: {
        if (PS.get().isPlotWorld(args[0])) {
            if (!Permissions.hasPermission(plr, "plots.list.world")) {
                MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.world");
                return false;
            }
            if (!Permissions.hasPermission(plr, "plots.list.world." + args[0])) {
                MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.world." + args[0]);
                return false;
            }
            plots = new ArrayList<>(PS.get().getPlots(args[0]).values());
            break;
        }
        UUID uuid = UUIDHandler.getUUID(args[0]);
        if (uuid != null) {
            if (!Permissions.hasPermission(plr, "plots.list.player")) {
                MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.list.player");
                return false;
            }
            plots = new ArrayList<>(PS.get().getPlots(uuid));
            break;
        }
    }
    }

    if (plots == null) {
        sendMessage(plr, C.DID_YOU_MEAN,
                new StringComparison(args[0], new String[] { "mine", "shared", "world", "all" })
                        .getBestMatch());
        return false;
    }

    if (plots.size() == 0) {
        MainUtil.sendMessage(plr, C.FOUND_NO_PLOTS);
        return false;
    }
    displayPlots(plr, plots, 12, page, world, args, sort);
    return true;
}

From source file:org.apache.pdfbox.rendering.TilingPaint.java

/**
 * Returns the anchor rectangle, which includes the XStep/YStep and scaling.
 *//* ww w.jav  a2s  .com*/
private Rectangle2D getAnchorRect(PDTilingPattern pattern) {
    float xStep = pattern.getXStep();
    if (xStep == 0) {
        xStep = pattern.getBBox().getWidth();
    }

    float yStep = pattern.getYStep();
    if (yStep == 0) {
        yStep = pattern.getBBox().getHeight();
    }

    float xScale = patternMatrix.getScalingFactorX();
    float yScale = patternMatrix.getScalingFactorY();
    float width = xStep * xScale;
    float height = yStep * yScale;

    if (Math.abs(width * height) > MAXEDGE * MAXEDGE) {
        // PDFBOX-3653: prevent huge sizes
        LOG.info("Pattern surface is too large, will be clipped");
        LOG.info("width: " + width + ", height: " + height);
        LOG.info("XStep: " + xStep + ", YStep: " + yStep);
        LOG.info("bbox: " + pattern.getBBox());
        LOG.info("pattern matrix: " + pattern.getMatrix());
        LOG.info("concatenated matrix: " + patternMatrix);
        width = Math.min(MAXEDGE, Math.abs(width)) * Math.signum(width);
        height = Math.min(MAXEDGE, Math.abs(height)) * Math.signum(height);
        //TODO better solution needed
    }

    // returns the anchor rect with scaling applied
    PDRectangle anchor = pattern.getBBox();
    return new Rectangle2D.Float(anchor.getLowerLeftX() * xScale, anchor.getLowerLeftY() * yScale, width,
            height);
}