Example usage for com.google.common.util.concurrent AtomicDouble get

List of usage examples for com.google.common.util.concurrent AtomicDouble get

Introduction

In this page you can find the example usage for com.google.common.util.concurrent AtomicDouble get.

Prototype

public final double get() 

Source Link

Document

Gets the current value.

Usage

From source file:org.arbeitspferde.groningen.utility.Metric.java

public static MetricListener<Double> make(final AtomicDouble value) {
    return new MetricListener<Double>() {
        @Override//w w w  .  j a  v a2s.c  o m
        public Double value() {
            return value.get();
        }
    };
}

From source file:org.apache.druid.indexing.common.Counters.java

@Nullable
public Double getDoubleCounter(String key) {
    final AtomicDouble atomicDouble = doubleCounters.get(key);
    return atomicDouble == null ? null : atomicDouble.get();
}

From source file:com.srotya.tau.nucleus.metrics.MetricsSink.java

public double getDoubleMetric(String metricName) throws Exception {
    AtomicDouble val = floatMetrics.get(metricName);
    if (val != null) {
        return val.get();
    } else {/*from  w ww  .j a v  a  2 s  . c om*/
        throw new Exception("Metric '" + metricName + "' not found");
    }
}

From source file:org.loklak.susi.SusiTransfer.java

/**
 * A conclusion from choices is done by the application of a function on the choice set.
 * This may be done by i.e. counting the number of choices or extracting a maximum element.
 * @param choices the given set of json objects from the data object of a SusiThought
 * @returnan array of json objects which are the extraction of given choices according to the given mapping
 *//*from  w w  w .j av a  2  s.  c  om*/
public JSONArray conclude(JSONArray choices) {
    JSONArray a = new JSONArray();
    if (this.selectionMapping != null && this.selectionMapping.size() == 1) {
        // test if this has an aggregation key: AVG, COUNT, MAX, MIN, SUM
        final String aggregator = this.selectionMapping.keySet().iterator().next();
        final String aggregator_as = this.selectionMapping.get(aggregator);
        if (aggregator.startsWith("COUNT(") && aggregator.endsWith(")")) { // TODO: there should be a special pattern for this to make it more efficient
            return a.put(new JSONObject().put(aggregator_as, choices.length()));
        }
        if (aggregator.startsWith("MAX(") && aggregator.endsWith(")")) {
            final AtomicDouble max = new AtomicDouble(Double.MIN_VALUE);
            String c = aggregator.substring(4, aggregator.length() - 1);
            choices.forEach(json -> max.set(Math.max(max.get(), ((JSONObject) json).getDouble(c))));
            return a.put(new JSONObject().put(aggregator_as, max.get()));
        }
        if (aggregator.startsWith("MIN(") && aggregator.endsWith(")")) {
            final AtomicDouble min = new AtomicDouble(Double.MAX_VALUE);
            String c = aggregator.substring(4, aggregator.length() - 1);
            choices.forEach(json -> min.set(Math.min(min.get(), ((JSONObject) json).getDouble(c))));
            return a.put(new JSONObject().put(aggregator_as, min.get()));
        }
        if (aggregator.startsWith("SUM(") && aggregator.endsWith(")")) {
            final AtomicDouble sum = new AtomicDouble(0.0d);
            String c = aggregator.substring(4, aggregator.length() - 1);
            choices.forEach(json -> sum.addAndGet(((JSONObject) json).getDouble(c)));
            return a.put(new JSONObject().put(aggregator_as, sum.get()));
        }
        if (aggregator.startsWith("AVG(") && aggregator.endsWith(")")) {
            final AtomicDouble sum = new AtomicDouble(0.0d);
            String c = aggregator.substring(4, aggregator.length() - 1);
            choices.forEach(json -> sum.addAndGet(((JSONObject) json).getDouble(c)));
            return a.put(new JSONObject().put(aggregator_as, sum.get() / choices.length()));
        }
    }
    if (this.selectionMapping != null && this.selectionMapping.size() == 2) {
        Iterator<String> ci = this.selectionMapping.keySet().iterator();
        String aggregator = ci.next();
        String column = ci.next();
        if (column.indexOf('(') >= 0) {
            String s = aggregator;
            aggregator = column;
            column = s;
        }
        final String aggregator_as = this.selectionMapping.get(aggregator);
        final String column_as = this.selectionMapping.get(column);
        final String column_final = column;
        if (aggregator.startsWith("PERCENT(") && aggregator.endsWith(")")) {
            final AtomicDouble sum = new AtomicDouble(0.0d);
            String c = aggregator.substring(8, aggregator.length() - 1);
            choices.forEach(json -> sum.addAndGet(((JSONObject) json).getDouble(c)));
            choices.forEach(json -> a.put(
                    new JSONObject().put(aggregator_as, 100.0d * ((JSONObject) json).getDouble(c) / sum.get())
                            .put(column_as, ((JSONObject) json).get(column_final))));
            return a;
        }
    }
    for (Object json : choices) {
        JSONObject extraction = this.extract((JSONObject) json);
        if (extraction.length() > 0)
            a.put(extraction);
    }
    return a;
}

From source file:ai.susi.mind.SusiTransfer.java

/**
 * A conclusion from choices is done by the application of a function on the choice set.
 * This may be done by i.e. counting the number of choices or extracting a maximum element.
 * @param choices the given set of json objects from the data object of a SusiThought
 * @returnan array of json objects which are the extraction of given choices according to the given mapping
 *//*w w w  . j av a2s.  co m*/
public JSONArray conclude(JSONArray choices) {
    JSONArray a = new JSONArray();
    if (this.selectionMapping != null && this.selectionMapping.size() == 1) {
        // test if this has an aggregation key: AVG, COUNT, MAX, MIN, SUM
        final String aggregator = this.selectionMapping.keySet().iterator().next();
        final String aggregator_as = this.selectionMapping.get(aggregator);
        if (aggregator.startsWith("COUNT(") && aggregator.endsWith(")")) { // TODO: there should be a special pattern for this to make it more efficient
            return a.put(new JSONObject().put(aggregator_as, choices.length()));
        }
        if (aggregator.startsWith("MAX(") && aggregator.endsWith(")")) {
            final AtomicDouble max = new AtomicDouble(Double.MIN_VALUE);
            String c = aggregator.substring(4, aggregator.length() - 1);
            choices.forEach(json -> max.set(Math.max(max.get(), ((JSONObject) json).getDouble(c))));
            return a.put(new JSONObject().put(aggregator_as, max.get()));
        }
        if (aggregator.startsWith("MIN(") && aggregator.endsWith(")")) {
            final AtomicDouble min = new AtomicDouble(Double.MAX_VALUE);
            String c = aggregator.substring(4, aggregator.length() - 1);
            choices.forEach(json -> min.set(Math.min(min.get(), ((JSONObject) json).getDouble(c))));
            return a.put(new JSONObject().put(aggregator_as, min.get()));
        }
        if (aggregator.startsWith("SUM(") && aggregator.endsWith(")")) {
            final AtomicDouble sum = new AtomicDouble(0.0d);
            String c = aggregator.substring(4, aggregator.length() - 1);
            choices.forEach(json -> sum.addAndGet(((JSONObject) json).getDouble(c)));
            return a.put(new JSONObject().put(aggregator_as, sum.get()));
        }
        if (aggregator.startsWith("AVG(") && aggregator.endsWith(")")) {
            final AtomicDouble sum = new AtomicDouble(0.0d);
            String c = aggregator.substring(4, aggregator.length() - 1);
            choices.forEach(json -> sum.addAndGet(((JSONObject) json).getDouble(c)));
            return a.put(new JSONObject().put(aggregator_as, sum.get() / choices.length()));
        }
    }
    if (this.selectionMapping != null && this.selectionMapping.size() == 2) {
        Iterator<String> ci = this.selectionMapping.keySet().iterator();
        String aggregator = ci.next();
        String column = ci.next();
        if (column.indexOf('(') >= 0) {
            String s = aggregator;
            aggregator = column;
            column = s;
        }
        final String aggregator_as = this.selectionMapping.get(aggregator);
        final String column_as = this.selectionMapping.get(column);
        final String column_final = column;
        if (aggregator.startsWith("PERCENT(") && aggregator.endsWith(")")) {
            final AtomicDouble sum = new AtomicDouble(0.0d);
            String c = aggregator.substring(8, aggregator.length() - 1);
            choices.forEach(json -> sum.addAndGet(((JSONObject) json).getDouble(c)));
            choices.forEach(json -> a.put(
                    new JSONObject().put(aggregator_as, 100.0d * ((JSONObject) json).getDouble(c) / sum.get())
                            .put(column_as, ((JSONObject) json).get(column_final))));
            return a;
        }
    }
    // this.selectionMapping == null -> extract everything
    for (Object json : choices) {
        JSONObject extraction = this.extract((JSONObject) json);
        if (extraction.length() > 0)
            a.put(extraction);
    }
    return a;
}

From source file:syncleus.gremlann.train.Backprop.java

public void backpropagate(final Vertex neuron) {

    //1. calculate deltaTrain based on all the destination synapses
    if (!isTrue(neuron, "output")) {

        final AtomicDouble newDeltaTrain = new AtomicDouble(0);

        neuron.outE("synapse").sideEffect(et -> {
            Edge synapse = et.get();//from   w  w w  .j  a v a  2  s . c om
            Vertex target = synapse.outV().next();

            newDeltaTrain.addAndGet(Synapse.weight(synapse) * deltaTrain(target));
        }).iterate();

        double ndt = newDeltaTrain.get() * getActivationFunction().activateDerivative(activity(neuron));
        set(neuron, "deltaTrain", ndt);

        //System.out.println(" delta=" + ndt + " " + newDeltaTrain.get());
    }

    //System.out.println("bp " + neuron.label() + " " + neuron.inE("synapse").toSet().size() + "|" +neuron.outE("synapse").toSet().size() + " d=" + real(neuron,"deltaTrain"));        

    //2. Back-propagates the training data to all the incoming synapses
    neuron.inE("synapse").sideEffect(et -> {
        Edge synapse = et.get();
        Vertex source = synapse.outV().next();

        double curWeight = Synapse.weight(synapse);
        double sourceDelta = deltaTrain(neuron);

        double newWeight = curWeight + (sourceDelta * learningRate(source) * signal(neuron));
        set(synapse, "weight", newWeight);

        //System.out.println("  " + synapse + " " + curWeight + " -> " + newWeight + " "+ sourceDelta + " " + deltaTrain(neuron));
    }).iterate();

}

From source file:com.globocom.grou.report.ts.opentsdb.OpenTSDBClient.java

@SuppressWarnings("unchecked")
@Override/*w  w w. jav  a  2  s . co  m*/
public Map<String, Double> makeReport(Test test) {
    final TreeMap<String, Double> mapOfResult = new TreeMap<>();
    ArrayList<HashMap<String, Object>> metrics = Optional.ofNullable(metrics(test)).orElse(new ArrayList<>());
    metrics.stream().filter(metric -> Objects.nonNull(metric.get("metric"))).forEach(metric -> {
        String key = (String) metric.get("metric");
        String aggr = (String) metric.get("aggr");
        int durationTimeMillis = test.getDurationTimeMillis();
        Map<String, Double> dps = Optional.ofNullable((Map<String, Double>) metric.get("dps"))
                .orElse(Collections.emptyMap());
        final AtomicDouble reduceSum = new AtomicDouble(0.0);
        final AtomicDouble reduceMax = new AtomicDouble(0.0);
        dps.entrySet().stream().mapToDouble(Map.Entry::getValue).forEach(delta -> {
            reduceSum.addAndGet(delta);
            if (reduceMax.get() < delta)
                reduceMax.set(delta);
        });
        double value = reduceSum.get();
        double max = reduceMax.get();
        if (!Double.isNaN(value)) {
            if ("sum".equals(aggr)) {
                int durationTimeSecs = durationTimeMillis / 1000;
                double avg = value / (double) durationTimeSecs;
                mapOfResult.put(key + " (total)", formatValue(value));
                mapOfResult.put(key + " (avg tps)", formatValue(avg));
                mapOfResult.put(key + " (max tps)",
                        formatValue(max / Math.max(1.0, (double) durationTimeSecs / (double) NUM_SAMPLES)));
            } else {
                value = value / (double) dps.size();
                mapOfResult.put(key, formatValue(value));
            }
        }
    });
    if (mapOfResult.isEmpty())
        LOGGER.error("Test {}.{}: makeReport return NULL", test.getProject(), test.getName());
    return mapOfResult;
}

From source file:com.facebook.stats.QuantileDigest.java

public synchronized List<Bucket> getHistogram(List<Long> bucketUpperBounds) {
    checkArgument(Ordering.natural().isOrdered(bucketUpperBounds),
            "buckets must be sorted in increasing order");

    final ImmutableList.Builder<Bucket> builder = ImmutableList.builder();
    final PeekingIterator<Long> iterator = Iterators.peekingIterator(bucketUpperBounds.iterator());

    final AtomicDouble sum = new AtomicDouble();
    final AtomicDouble lastSum = new AtomicDouble();

    // for computing weighed average of values in bucket
    final AtomicDouble bucketWeightedSum = new AtomicDouble();

    final double normalizationFactor = weight(TimeUnit.MILLISECONDS.toSeconds(clock.getMillis()));

    postOrderTraversal(root, new Callback() {
        public boolean process(Node node) {

            while (iterator.hasNext() && iterator.peek() <= node.getUpperBound()) {
                double bucketCount = sum.get() - lastSum.get();

                Bucket bucket = new Bucket(bucketCount / normalizationFactor,
                        bucketWeightedSum.get() / bucketCount);

                builder.add(bucket);//from  www.  ja  v  a 2s  .c  o m
                lastSum.set(sum.get());
                bucketWeightedSum.set(0);
                iterator.next();
            }

            bucketWeightedSum.addAndGet(node.getMiddle() * node.weightedCount);
            sum.addAndGet(node.weightedCount);
            return iterator.hasNext();
        }
    });

    while (iterator.hasNext()) {
        double bucketCount = sum.get() - lastSum.get();
        Bucket bucket = new Bucket(bucketCount / normalizationFactor, bucketWeightedSum.get() / bucketCount);

        builder.add(bucket);

        iterator.next();
    }

    return builder.build();
}

From source file:blusunrize.immersiveengineering.api.ApiUtils.java

public static Connection raytraceWires(World world, Vec3d start, Vec3d end, @Nullable Connection ignored) {
    Map<BlockPos, ImmersiveNetHandler.BlockWireInfo> inDim = ImmersiveNetHandler.INSTANCE.blockWireMap
            .lookup(world.provider.getDimension());
    AtomicReference<Connection> ret = new AtomicReference<>();
    AtomicDouble minDistSq = new AtomicDouble(Double.POSITIVE_INFINITY);
    if (inDim != null) {
        Utils.rayTrace(start, end, world, (pos) -> {
            if (inDim.containsKey(pos)) {
                ImmersiveNetHandler.BlockWireInfo info = inDim.get(pos);
                for (int i = 0; i < 2; i++) {
                    Set<Triple<Connection, Vec3d, Vec3d>> conns = i == 0 ? info.in : info.near;
                    for (Triple<Connection, Vec3d, Vec3d> conn : conns) {
                        Connection c = conn.getLeft();
                        if (ignored == null || !c.hasSameConnectors(ignored)) {
                            Vec3d startRelative = start.add(-pos.getX(), -pos.getY(), -pos.getZ());
                            Vec3d across = conn.getRight().subtract(conn.getMiddle());
                            double t = Utils.getCoeffForMinDistance(startRelative, conn.getMiddle(), across);
                            t = MathHelper.clamp(0, t, 1);
                            Vec3d closest = conn.getMiddle().add(t * across.x, t * across.y, t * across.z);
                            double distSq = closest.squareDistanceTo(startRelative);
                            if (distSq < minDistSq.get()) {
                                ret.set(c);
                                minDistSq.set(distSq);
                            }//w w w  . jav  a  2  s.  c  om
                        }
                    }
                }
            }
        });
    }

    return ret.get();
}

From source file:com.facebook.stats.QuantileDigest.java

@VisibleForTesting
synchronized void validate() {
    final AtomicDouble sumOfWeights = new AtomicDouble();
    final AtomicInteger actualNodeCount = new AtomicInteger();
    final AtomicInteger actualNonZeroNodeCount = new AtomicInteger();

    if (root != null) {
        validateStructure(root);//from  w  w  w .ja va2 s  . co m

        postOrderTraversal(root, new Callback() {
            @Override
            public boolean process(Node node) {
                sumOfWeights.addAndGet(node.weightedCount);
                actualNodeCount.incrementAndGet();

                if (node.weightedCount > ZERO_WEIGHT_THRESHOLD) {
                    actualNonZeroNodeCount.incrementAndGet();
                }

                return true;
            }
        });
    }

    checkState(Math.abs(sumOfWeights.get() - weightedCount) < ZERO_WEIGHT_THRESHOLD,
            "Computed weight (%s) doesn't match summary (%s)", sumOfWeights.get(), weightedCount);

    checkState(actualNodeCount.get() == totalNodeCount, "Actual node count (%s) doesn't match summary (%s)",
            actualNodeCount.get(), totalNodeCount);

    checkState(actualNonZeroNodeCount.get() == nonZeroNodeCount,
            "Actual non-zero node count (%s) doesn't match summary (%s)", actualNonZeroNodeCount.get(),
            nonZeroNodeCount);
}