Example usage for java.lang Double MAX_VALUE

List of usage examples for java.lang Double MAX_VALUE

Introduction

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

Prototype

double MAX_VALUE

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

Click Source Link

Document

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

Usage

From source file:com.janrain.backplane2.server.dao.redis.RedisBackplaneMessageDAO.java

@Override
public void retrieveMessagesPerScope(@NotNull MessagesResponse bpResponse, @NotNull Token token)
        throws BackplaneServerException {
    final Scope scope = token.getScope();
    final boolean isAnonymous = token.getType() == GrantType.ANONYMOUS;
    Jedis jedis = null;//from  w  ww.j  a v  a  2s  .  c  om
    try {
        jedis = Redis.getInstance().getReadJedis();
        Transaction t = jedis.multi();
        List<String> unions = new ArrayList<String>();

        Set<String> channelScopes = scope.getScopeFieldValues(BackplaneMessage.Field.CHANNEL);
        if (channelScopes != null) {
            String channelUnion = "scope_req_" + ChannelUtil.randomString(10);
            unions.add(channelUnion);
            for (String channel : channelScopes) {
                t.zunionstore(channelUnion.getBytes(), new ZParams() {
                    {
                        aggregate(Aggregate.MAX);
                    }
                }, channelUnion.getBytes(), getChannelKey(channel));
            }
        }
        Set<String> busScopes = scope.getScopeFieldValues(BackplaneMessage.Field.BUS);
        // don't try to get bus messages for anonymous tokens (since it's supposed to be only for a specific channel)
        if (busScopes != null && !isAnonymous) {
            String busUnion = "scope_req_" + ChannelUtil.randomString(10);
            unions.add(busUnion);
            for (String bus : busScopes) {
                t.zunionstore(busUnion.getBytes(), new ZParams() {
                    {
                        aggregate(Aggregate.MAX);
                    }
                }, busUnion.getBytes(), getBusKey(bus));
            }
        }
        String channelBusIntersection = null;
        for (String union : unions) {
            if (channelBusIntersection == null) {
                channelBusIntersection = union;
            } else {
                t.zinterstore(channelBusIntersection.getBytes(), new ZParams() {
                    {
                        aggregate(Aggregate.MAX);
                    }
                }, channelBusIntersection.getBytes(), union.getBytes());
            }
        }

        Response<Set<byte[]>> lastResponse = t.zrange(V2_MESSAGES.getBytes(), -1, -1);
        List<BackplaneMessage> messages = new ArrayList<BackplaneMessage>();

        if (channelBusIntersection != null) {
            Date lastMessageDate = BackplaneMessage.getDateFromId(bpResponse.getLastMessageId());
            long lastMessageTime = lastMessageDate == null ? 0 : lastMessageDate.getTime();
            Response<Set<String>> busChannelMessageIds = t.zrangeByScore(channelBusIntersection,
                    lastMessageTime + 1, Double.MAX_VALUE);
            for (String union : unions)
                t.del(union);
            t.exec();
            if (!busChannelMessageIds.get().isEmpty()) {
                List<byte[]> idBytes = new ArrayList<byte[]>();
                for (String msgId : busChannelMessageIds.get()) {
                    idBytes.add(getKey(msgId));
                }
                for (byte[] messageBytes : jedis.mget(idBytes.toArray(new byte[idBytes.size()][]))) {
                    if (messageBytes != null)
                        messages.add((BackplaneMessage) SerializationUtils.deserialize(messageBytes));
                }

            }
        } else {
            t.exec();
        }

        if (!messages.isEmpty()) {
            filterMessagesPerScope(messages, scope, bpResponse);
        } else {
            Set<byte[]> lastBytes = lastResponse.get();
            if (lastBytes.isEmpty()) {
                bpResponse.setLastMessageId("");
            } else {
                String lastMessageId = new String(lastBytes.iterator().next()).split(" ")[2];
                bpResponse.setLastMessageId(lastMessageId);
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new BackplaneServerException(e.getMessage(), e);
    } finally {
        Redis.getInstance().releaseToPool(jedis);
    }
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.table.AllTypesIT.java

private static void populateRecords() {
    Record record = RecordCreator.create();
    LinkedHashMap<String, Field> fields;
    AtomicInteger id_field = new AtomicInteger(0);

    //CHAR_AND_BINARY
    fields = new LinkedHashMap<>();
    createIdField(fields, id_field);/*from   w w  w  . j  av a  2  s . c  o m*/
    fields.put("char1", Field.create("abcdefghij"));
    fields.put("varchar1", Field.create(UUID.randomUUID().toString()));
    fields.put("clob1", Field.create(UUID.randomUUID().toString()));
    fields.put("varbinary1", Field.create(UUID.randomUUID().toString().getBytes()));
    fields.put("blob1", Field.create(UUID.randomUUID().toString().getBytes()));
    record.set(Field.createListMap(fields));

    TABLE_TO_TEMPLATE_AND_RECORDS_MAP.get("CHAR_AND_BINARY").getRight().add(record);

    //Date and time
    record = RecordCreator.create();
    fields = new LinkedHashMap<>();
    createIdField(fields, id_field);
    Calendar calendar = Calendar.getInstance();

    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    fields.put("date1", Field.create(Field.Type.DATE, calendar.getTime()));
    calendar.setTimeInMillis(System.currentTimeMillis());

    calendar.set(Calendar.MILLISECOND, 0);
    fields.put("timestamp1", Field.create(Field.Type.DATETIME, calendar.getTime()));
    fields.put("datetime1", Field.create(Field.Type.DATETIME, calendar.getTime()));
    calendar.setTimeInMillis(System.currentTimeMillis());

    calendar.set(Calendar.YEAR, 1970);
    calendar.set(Calendar.MONTH, Calendar.JANUARY);
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.set(Calendar.MILLISECOND, 0);
    fields.put("time1", Field.create(Field.Type.TIME, calendar.getTime()));
    calendar.setTimeInMillis(System.currentTimeMillis());

    record.set(Field.createListMap(fields));
    TABLE_TO_TEMPLATE_AND_RECORDS_MAP.get("DATE_AND_TIME").getRight().add(record);

    //DIFFERENT_INTS
    record = RecordCreator.create();
    fields = new LinkedHashMap<>();
    createIdField(fields, id_field);
    fields.put("int1", Field.create(Field.Type.INTEGER, Integer.MIN_VALUE));
    fields.put("int2", Field.create(Field.Type.INTEGER, Integer.MIN_VALUE));
    fields.put("mediumint1", Field.create(Field.Type.INTEGER, Integer.MIN_VALUE));
    fields.put("tinyint1", Field.create(Field.Type.SHORT, -128));
    fields.put("smallint1", Field.create(Field.Type.SHORT, Short.MIN_VALUE));
    fields.put("bigint1", Field.create(Field.Type.LONG, Long.MIN_VALUE));
    record.set(Field.createListMap(fields));
    TABLE_TO_TEMPLATE_AND_RECORDS_MAP.get("DIFFERENT_INTS").getRight().add(record);

    record = RecordCreator.create();
    fields = new LinkedHashMap<>();
    createIdField(fields, id_field);
    fields.put("int1", Field.create(Field.Type.INTEGER, Integer.MAX_VALUE));
    fields.put("int2", Field.create(Field.Type.INTEGER, Integer.MAX_VALUE));
    fields.put("mediumint1", Field.create(Field.Type.INTEGER, Integer.MAX_VALUE));
    fields.put("tinyint1", Field.create(Field.Type.SHORT, 127));
    fields.put("smallint1", Field.create(Field.Type.SHORT, Short.MAX_VALUE));
    fields.put("bigint1", Field.create(Field.Type.LONG, Long.MAX_VALUE));
    record.set(Field.createListMap(fields));
    TABLE_TO_TEMPLATE_AND_RECORDS_MAP.get("DIFFERENT_INTS").getRight().add(record);

    //FLOATING_PT_INTS
    record = RecordCreator.create();
    fields = new LinkedHashMap<>();
    createIdField(fields, id_field);
    fields.put("decimal1", Field.create(Field.Type.DECIMAL, new BigDecimal("12.345")));
    fields.put("number1", Field.create(Field.Type.DECIMAL, new BigDecimal("0.12345")));
    fields.put("double1", Field.create(Field.Type.DOUBLE, 123.456));
    fields.put("real1", Field.create(Field.Type.FLOAT, 12.34));
    fields.put("floatdouble1", Field.create(Field.Type.DOUBLE, Double.MAX_VALUE));
    record.set(Field.createListMap(fields));
    TABLE_TO_TEMPLATE_AND_RECORDS_MAP.get("FLOATING_PT_INTS").getRight().add(record);

    record = RecordCreator.create();
    fields = new LinkedHashMap<>();
    createIdField(fields, id_field);
    fields.put("decimal1", Field.create(Field.Type.DECIMAL, new BigDecimal("-12.345")));
    fields.put("number1", Field.create(Field.Type.DECIMAL, new BigDecimal("-0.12345")));
    fields.put("double1", Field.create(Field.Type.DOUBLE, -123.456));
    fields.put("real1", Field.create(Field.Type.FLOAT, -12.34));
    fields.put("floatdouble1", Field.create(Field.Type.DOUBLE, Double.MIN_VALUE));
    record.set(Field.createListMap(fields));
    TABLE_TO_TEMPLATE_AND_RECORDS_MAP.get("FLOATING_PT_INTS").getRight().add(record);

    //OTHER_TYPES
    record = RecordCreator.create();
    fields = new LinkedHashMap<>();
    createIdField(fields, id_field);
    fields.put("boolean1", Field.create(Field.Type.BOOLEAN, true));
    record.set(Field.createListMap(fields));
    TABLE_TO_TEMPLATE_AND_RECORDS_MAP.get("OTHER_TYPES").getRight().add(record);

    record = RecordCreator.create();
    fields = new LinkedHashMap<>();
    createIdField(fields, id_field);
    fields.put("boolean1", Field.create(Field.Type.BOOLEAN, false));
    record.set(Field.createListMap(fields));
    TABLE_TO_TEMPLATE_AND_RECORDS_MAP.get("OTHER_TYPES").getRight().add(record);
}

From source file:ddf.catalog.data.dynamic.impl.DynamicMetacardImplTest.java

@Test
public void testSetAttributeWithValues() throws Exception {
    metacard.setAttribute(STRING, "abc");
    assertEquals("abc", baseBean.get(STRING));

    metacard.setAttribute(BOOLEAN, true);
    assertEquals(true, baseBean.get(BOOLEAN));

    Date d = new Date(System.currentTimeMillis());
    metacard.setAttribute(DATE, d);/*w w w.  java  2s  .  c  om*/
    assertEquals(d, baseBean.get(DATE));

    metacard.setAttribute(SHORT, Short.MAX_VALUE);
    assertEquals(Short.MAX_VALUE, baseBean.get(SHORT));

    metacard.setAttribute(INTEGER, Integer.MAX_VALUE);
    assertEquals(Integer.MAX_VALUE, baseBean.get(INTEGER));

    metacard.setAttribute(LONG, Long.MAX_VALUE);
    assertEquals(Long.MAX_VALUE, baseBean.get(LONG));

    metacard.setAttribute(FLOAT, Float.MAX_VALUE);
    assertEquals(Float.MAX_VALUE, baseBean.get(FLOAT));

    metacard.setAttribute(DOUBLE, Double.MAX_VALUE);
    assertEquals(Double.MAX_VALUE, baseBean.get(DOUBLE));

    Byte[] bytes = new Byte[] { 0x00, 0x01, 0x02, 0x03 };
    metacard.setAttribute(BINARY, bytes);
    assertEquals(bytes, baseBean.get(BINARY));

    metacard.setAttribute(XML, XML_STRING);
    assertEquals(XML_STRING, baseBean.get(XML));

    metacard.setAttribute(OBJECT, XML_STRING);
    assertEquals(XML_STRING, baseBean.get(OBJECT));

    List<Serializable> list = new ArrayList<>();
    list.add("123");
    list.add("234");
    list.add("345");
    metacard.setAttribute(STRING_LIST, list);
    assertEquals(list, baseBean.get(STRING_LIST));

    metacard.setAttribute(STRING_LIST, "456");
    Collection c = (Collection) baseBean.get(STRING_LIST);
    assertEquals(4, c.size());
    assertTrue(c.contains("456"));

    list.remove("123");
    metacard.setAttribute(STRING_LIST, list);
    c = (Collection) baseBean.get(STRING_LIST);
    assertEquals(3, c.size());
    assertTrue(c.contains("456"));
    assertFalse(c.contains("123"));

    metacard.setAttribute(SHORT, Short.MIN_VALUE);
    // this should take no action since auto-conversion fails - handled ConversionException
    metacard.setAttribute(SHORT, Long.MAX_VALUE);
    assertEquals(Short.MIN_VALUE, baseBean.get(SHORT));
}

From source file:edu.umich.robot.gp.Gamepad.java

public void initializeGamepad(final Controller controller) {
    if (gpji == null)
        return;// ww w .  j  a  va 2  s . c om
    gpji.addListener("0", new GamepadListener() {
        public void stateChanged(String id, float value) {
            if (logger.isTraceEnabled())
                logger.trace(id + ": " + value);
            if (Float.compare(value, 0) != 0)
                controller.toggleGamepadOverride();
        }
    });

    gpji.addListener("1", new GamepadListener() {
        public void stateChanged(String id, float value) {
            if (logger.isTraceEnabled())
                logger.trace(id + ": " + value);
            if (Float.compare(value, 0) != 0)
                controller.toggleSoarRunState();
        }
    });

    gpji.addListener("6", new GamepadListener() {
        public void stateChanged(String id, float value) {
            if (logger.isTraceEnabled())
                logger.trace(id + ": " + value);
            if (Float.compare(value, 0) != 0)
                controller.toggleRate();
        }
    });

    gpji.addListener("3", new GamepadListener() {
        public void stateChanged(String id, float value) {
            if (logger.isTraceEnabled())
                logger.trace(id + ": " + value);
            if (Float.compare(value, 0) != 0)
                slow = !slow;
        }
    });

    gpji.addListener("2", new GamepadListener() {
        public void stateChanged(String id, float value) {
            if (logger.isTraceEnabled())
                logger.trace(id + ": " + value);
            if (Float.compare(value, 0) != 0) {
                int index = gpInputScheme.ordinal() + 1;
                index %= GamepadInputScheme.values().length;
                gpInputScheme = GamepadInputScheme.values()[index];
                logger.info("Input changed to " + gpInputScheme);
            }
        }
    });

    gpji.addListener("5", new GamepadListener() {
        public void stateChanged(String id, float value) {
            if (Float.compare(value, 0) != 0) {
                if (output == null) {
                    logger.info("Get/Drop object called: no robot output");
                    return;
                }

                if (output.getCarriedObject() != null)
                    controller.fireGamepadControlEvent(new EffectorDropObjectEvent());
                else {
                    VirtualObject target = null;
                    double targetDistance = Double.MAX_VALUE;

                    for (VirtualObject vo : output.getVisibleObjects()) {
                        pose_t me = output.getPose().asLcmType();
                        pose_t targetPose = vo.getPose().asLcmType();
                        double distance = LinAlg.squaredDistance(me.pos, targetPose.pos);

                        if (target == null || distance < targetDistance) {
                            target = vo;
                            targetDistance = distance;
                        }
                    }
                    if (target == null)
                        logger.warn("No objects to get.");
                    else
                        controller.fireGamepadControlEvent(new EffectorGetObjectEvent(target.getId()));
                }
            }
        }
    });

    gpji.addListener("4", new GamepadListener() {
        public void stateChanged(String id, float value) {
            if (Float.compare(value, 0) != 0) {
                if (output == null) {
                    logger.info("Open/close/unlock door called: no robot output");
                    return;
                }

                Gateway target = null;
                double targetDistance = Double.MAX_VALUE;

                for (Gateway g : output.getAreaDescription().getGateways()) {
                    pose_t me = output.getPose().asLcmType();
                    pose_t targetPose = g.getPose().asLcmType();
                    double distance = LinAlg.squaredDistance(me.pos, targetPose.pos);

                    if (target == null || distance < targetDistance) {
                        target = g;
                        targetDistance = distance;
                    }
                }

                if (target == null)
                    logger.warn("No door to manipulate.");
                else {
                    Door door = target.getDoor();
                    switch (door.getState()) {
                    case CLOSED:
                        controller.fireGamepadControlEvent(new DoorOpenEvent(door.getId()));
                        break;

                    case LOCKED:
                        controller.fireGamepadControlEvent(new DoorUnlockEvent(door.getId(), door.getCode()));
                        break;

                    case OPEN:
                        controller.fireGamepadControlEvent(new DoorCloseEvent(door.getId()));
                        break;
                    }
                    controller.fireGamepadControlEvent(new EffectorGetObjectEvent(target.getId()));
                }
            }
        }
    });

    gpji.addListener("LY", new GamepadListener() {
        public void stateChanged(String id, float value) {
            if (logger.isTraceEnabled())
                logger.trace(id + ": " + value);
            ly = value;
            update(controller);
        }
    });
    gpji.addListener("RX", new GamepadListener() {
        public void stateChanged(String id, float value) {
            if (logger.isTraceEnabled())
                logger.trace(id + ": " + value);
            rx = value;
            update(controller);
        }
    });
    gpji.addListener("RY", new GamepadListener() {
        public void stateChanged(String id, float value) {
            if (logger.isTraceEnabled())
                logger.trace(id + ": " + value);
            ry = value;
            update(controller);
        }
    });
}

From source file:com.manydesigns.elements.pdf.TableFormPdfExporter.java

/**
 * <p>Returns an array of column sizes (in characters) for the search export.<br />
 * By default, sizes are computed comparing the relative sizes of each column,
 * consisting of the header and the values produced by the search.</p>
 * <p>Users can override this method to compute the sizes using a different algorithm,
 * or hard-coding them for a particular CRUD instance.</p>
 *//*w  ww  .ja v a  2s . co  m*/
protected double[] setupColumnSizes() {
    double[] headerSizes = new double[form.getColumns().length];
    for (int i = 0; i < headerSizes.length; i++) {
        TableForm.Column col = form.getColumns()[i];
        int length = StringUtils.length(col.getLabel());
        headerSizes[i] = length;
    }

    double[] columnSizes = new double[form.getColumns().length];
    for (TableForm.Row row : form.getRows()) {
        int i = 0;
        for (Field field : row) {
            int size = StringUtils.length(field.getStringValue());
            double relativeSize = ((double) size) / form.getRows().length;
            columnSizes[i++] += relativeSize;
        }
    }

    double totalSize = 0;
    for (int i = 0; i < columnSizes.length; i++) {
        double effectiveSize = Math.max(columnSizes[i], headerSizes[i]);
        columnSizes[i] = effectiveSize;
        totalSize += effectiveSize;
    }
    while (totalSize > 75) {
        int maxIndex = 0;
        double max = 0;
        for (int i = 0; i < columnSizes.length; i++) {
            if (columnSizes[i] > max) {
                max = columnSizes[i];
                maxIndex = i;
            }
        }
        columnSizes[maxIndex] -= 1;
        totalSize -= 1;
    }
    while (totalSize < 70) {
        int minIndex = 0;
        double min = Double.MAX_VALUE;
        for (int i = 0; i < columnSizes.length; i++) {
            if (columnSizes[i] < min) {
                min = columnSizes[i];
                minIndex = i;
            }
        }
        columnSizes[minIndex] += 1;
        totalSize += 1;
    }
    return columnSizes;
}

From source file:org.uma.jmetal.util.point.impl.ArrayPointTest.java

@Test
public void shouldEqualsReturnTrueIfThePointsAreIdentical() {
    int dimension = 5;
    Point point = new ArrayPoint(dimension);
    point.setDimensionValue(0, 1.0);/* w  w w.  j  ava 2s .c om*/
    point.setDimensionValue(1, -2.0);
    point.setDimensionValue(2, 45.5);
    point.setDimensionValue(3, -323.234);
    point.setDimensionValue(4, Double.MAX_VALUE);

    Point newPoint = new ArrayPoint(point);

    assertTrue(point.equals(newPoint));
}

From source file:com.diona.videoplugin.CameraUtil.java

/**
 * Iterate over supported camera preview sizes to see which one best fits the dimensions of the given view while
 * maintaining the aspect ratio. If none can, be lenient with the aspect ratio.
 *
 * @param sizes/*from w  w w.jav  a 2  s.  co m*/
 *          Supported camera preview sizes.
 * @param w
 *          The width of the view.
 * @param h
 *          The height of the view.
 * @return Best match camera preview size to fit in the view.
 */
public static Camera.Size getOptimalPreviewSize(final List<Camera.Size> sizes, final int w, final int h) {
    // Use a very small tolerance because we want an exact match.
    final double aspectTolerance = 0.1;
    final double targetRatio = (double) w / h;
    if (sizes == null) {
        return null;
    }
    LogUtil.error(TAG, "the width height" + w + "::" + h);
    Camera.Size optimalSize = null;

    // Start with max value and refine as we iterate over available preview sizes. This is the
    // minimum difference between view and camera height.
    double minDiff = Double.MAX_VALUE;

    // Target view height
    final int targetHeight = h;

    // Try to find a preview size that matches aspect ratio and the target view size.
    // Iterate over all available sizes and pick the largest size that can fit in the view and
    // still maintain the aspect ratio.
    for (final Camera.Size size : sizes) {
        final double ratio = (double) size.width / size.height;
        if (Math.abs(ratio - targetRatio) > aspectTolerance) {
            continue;
        }
        if (Math.abs(size.height - targetHeight) < minDiff) {
            optimalSize = size;
            minDiff = Math.abs(size.height - targetHeight);
        }
    }

    // Cannot find preview size that matches the aspect ratio, ignore the requirement
    if (optimalSize == null) {
        minDiff = Double.MAX_VALUE;
        for (final Camera.Size size : sizes) {
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }
    }
    return optimalSize;
}

From source file:de.tudarmstadt.lt.ltbot.postprocessor.DecesiveValuePrioritizer.java

double getValueFromCurrentURI(CrawlURI uri) throws IllegalStateException {
    try {/*from ww  w .  j a v a 2 s .c om*/
        JSONObject info = uri.getExtraInfo();
        if (info.length() == 0 || !info.has(SharedConstants.EXTRA_INFO_PERPLEXITY_VIA))
            return Double.MAX_VALUE;
        double value = Double.valueOf(info.getString(SharedConstants.EXTRA_INFO_PERPLEXITY_VIA));
        return value;
    } catch (Throwable t) {
        throw new IllegalStateException(String.format("Failed to get value from field %s (%s).",
                SharedConstants.EXTRA_INFO_PERPLEXITY_VIA, uri.toString()));
    }
}

From source file:edu.stanford.cfuller.imageanalysistools.fitting.GaussianImageObjectWithCovariance.java

/**
 * Fits this object to a 3-dimensional gaussian, and estimates error and goodness of fit.
 * @param p     The parameters for the current analysis.
 *///w  w  w  .  j  a  va  2 s  .c o m
public void fitPosition(ParameterDictionary p) {

    if (this.sizeInPixels == 0) {
        this.nullifyImages();
        return;
    }

    this.fitParametersByChannel = new java.util.ArrayList<FitParameters>();
    this.fitR2ByChannel = new java.util.ArrayList<Double>();
    this.fitErrorByChannel = new java.util.ArrayList<Double>();
    this.nPhotonsByChannel = new java.util.ArrayList<Double>();

    GaussianFitter3DWithCovariance gf = new GaussianFitter3DWithCovariance();

    //System.out.println(this.parent.getDimensionSizes().getZ());

    int numChannels = 0;

    if (p.hasKey("num_wavelengths")) {
        numChannels = p.getIntValueForKey("num_wavelengths");
    } else {
        numChannels = this.parent.getDimensionSizes().get(ImageCoordinate.C);
    }

    //for (int channelIndex = 0; channelIndex < this.parent.getDimensionSizes().getC(); channelIndex++) {
    for (int channelIndex = 0; channelIndex < numChannels; channelIndex++) {

        RealVector fitParameters = new ArrayRealVector(11, 0.0);

        double ppg = p.getDoubleValueForKey("photons_per_greylevel");

        this.parentBoxMin.set(ImageCoordinate.C, channelIndex);
        this.parentBoxMax.set(ImageCoordinate.C, channelIndex + 1);

        this.boxImages();

        List<Double> x = new java.util.ArrayList<Double>();
        List<Double> y = new java.util.ArrayList<Double>();
        List<Double> z = new java.util.ArrayList<Double>();
        List<Double> f = new java.util.ArrayList<Double>();

        for (ImageCoordinate ic : this.parent) {
            x.add((double) ic.get(ImageCoordinate.X));
            y.add((double) ic.get(ImageCoordinate.Y));
            z.add((double) ic.get(ImageCoordinate.Z));
            f.add((double) parent.getValue(ic));
        }

        xValues = new double[x.size()];
        yValues = new double[y.size()];
        zValues = new double[z.size()];
        functionValues = new double[f.size()];

        double xCentroid = 0;
        double yCentroid = 0;
        double zCentroid = 0;
        double totalCounts = 0;

        for (int i = 0; i < x.size(); i++) {

            xValues[i] = x.get(i);
            yValues[i] = y.get(i);
            zValues[i] = z.get(i);
            functionValues[i] = f.get(i) * ppg;
            xCentroid += xValues[i] * functionValues[i];
            yCentroid += yValues[i] * functionValues[i];
            zCentroid += zValues[i] * functionValues[i];
            totalCounts += functionValues[i];
        }

        xCentroid /= totalCounts;
        yCentroid /= totalCounts;
        zCentroid /= totalCounts;

        //z sometimes seems to be a bit off... trying (20110415) to go back to max value pixel at x,y centroid

        int xRound = (int) Math.round(xCentroid);
        int yRound = (int) Math.round(yCentroid);

        double maxVal = 0;
        int maxInd = 0;

        double minZ = Double.MAX_VALUE;
        double maxZ = 0;

        for (int i = 0; i < x.size(); i++) {

            if (zValues[i] < minZ)
                minZ = zValues[i];
            if (zValues[i] > maxZ)
                maxZ = zValues[i];

            if (xValues[i] == xRound && yValues[i] == yRound) {
                if (functionValues[i] > maxVal) {
                    maxVal = functionValues[i];
                    maxInd = (int) zValues[i];
                }
            }
        }

        zCentroid = maxInd;

        //parameter ordering: amplitude, var x-y, var z, x/y/z coords, background

        //amplitude: find the max value; background: find the min value

        double maxValue = 0;

        double minValue = Double.MAX_VALUE;

        for (ImageCoordinate ic : this.parent) {

            if (parent.getValue(ic) > maxValue)
                maxValue = parent.getValue(ic);
            if (parent.getValue(ic) < minValue)
                minValue = parent.getValue(ic);

        }

        fitParameters.setEntry(0, (maxValue - minValue) * 0.95);
        fitParameters.setEntry(10, minValue + 0.05 * (maxValue - minValue));

        //positions

        fitParameters.setEntry(7, xCentroid);
        fitParameters.setEntry(8, yCentroid);
        fitParameters.setEntry(9, zCentroid);

        //variances

        final double limitedWidthxy = 200;
        final double limitedWidthz = 500;

        double sizex = limitedWidthxy / p.getDoubleValueForKey("pixelsize_nm");
        double sizey = limitedWidthxy / p.getDoubleValueForKey("pixelsize_nm");
        double sizez = limitedWidthz / p.getDoubleValueForKey("z_sectionsize_nm");

        if (p.hasKey(Z_WIDTH_PARAM)) {
            sizez = p.getDoubleValueForKey(Z_WIDTH_PARAM);
        }

        if (p.hasKey(XY_WIDTH_PARAM)) {
            sizex = p.getDoubleValueForKey(XY_WIDTH_PARAM);
            sizey = p.getDoubleValueForKey(XY_WIDTH_PARAM);
        }

        fitParameters.setEntry(1, sizex / 2);
        fitParameters.setEntry(2, sizey / 2);
        fitParameters.setEntry(3, sizez / 2);

        //covariances -- guess zero to start

        fitParameters.setEntry(4, 0.0);
        fitParameters.setEntry(5, 0.0);
        fitParameters.setEntry(6, 0.0);

        //amplitude and background are in arbitrary intensity units; convert to photon counts

        fitParameters.setEntry(0, fitParameters.getEntry(0) * ppg);
        fitParameters.setEntry(10, fitParameters.getEntry(10) * ppg);

        //System.out.println("guess: " + fitParameters);

        //do the fit

        //System.out.println("Initial for object " + this.label + ": " + fitParameters.toString());

        fitParameters = gf.fit(this, fitParameters, ppg);

        //System.out.println("Parameters for object " + this.label + ": " + fitParameters.toString());

        //System.out.println("fit: " + fitParameters);

        FitParameters fp = new FitParameters();

        fp.setPosition(ImageCoordinate.X, fitParameters.getEntry(7));
        fp.setPosition(ImageCoordinate.Y, fitParameters.getEntry(8));
        fp.setPosition(ImageCoordinate.Z, fitParameters.getEntry(9));

        fp.setSize(ImageCoordinate.X, fitParameters.getEntry(1));
        fp.setSize(ImageCoordinate.Y, fitParameters.getEntry(2));
        fp.setSize(ImageCoordinate.Z, fitParameters.getEntry(3));

        fp.setAmplitude(fitParameters.getEntry(0));
        fp.setBackground(fitParameters.getEntry(10));

        fp.setOtherParameter("corr_xy", fitParameters.getEntry(4));
        fp.setOtherParameter("corr_xz", fitParameters.getEntry(5));
        fp.setOtherParameter("corr_yz", fitParameters.getEntry(6));

        fitParametersByChannel.add(fp);

        //            System.out.println(fitParameters);

        //calculate R2

        double residualSumSquared = 0;
        double mean = 0;
        double variance = 0;
        double R2 = 0;

        double n_photons = 0;

        for (int i = 0; i < this.xValues.length; i++) {

            residualSumSquared += Math.pow(GaussianFitter3DWithCovariance.fitResidual(functionValues[i],
                    xValues[i], yValues[i], zValues[i], fitParameters), 2);

            mean += functionValues[i];

            n_photons += functionValues[i] - fitParameters.getEntry(10);

        }

        mean /= functionValues.length;

        for (int i = 0; i < this.xValues.length; i++) {
            variance += Math.pow(functionValues[i] - mean, 2);
        }

        R2 = 1 - (residualSumSquared / variance);

        this.fitR2ByChannel.add(R2);

        this.unboxImages();

        //calculate fit error -- these are wrong for the case with unequal x-y variances and covariance allowed, but leave them for now.

        double s_xy = fitParameters.getEntry(1) * fitParameters.getEntry(1)
                * Math.pow(p.getDoubleValueForKey("pixelsize_nm"), 2);
        double s_z = fitParameters.getEntry(3) * fitParameters.getEntry(3)
                * Math.pow(p.getDoubleValueForKey("z_sectionsize_nm"), 2);

        //s_z = 0; //remove!!

        double error = (2 * s_xy + s_z) / (n_photons - 1);// + 4*Math.sqrt(Math.PI) * Math.pow(2*s_xy,1.5)*Math.pow(fitParameters.getEntry(6),2)/(p.getDoubleValueForKey("pixelsize_nm")*n_photons*n_photons);

        double b = fitParameters.getEntry(10);
        double a = p.getDoubleValueForKey("pixelsize_nm");
        double alpha = p.getDoubleValueForKey("z_sectionsize_nm");
        double sa_x = s_xy + Math.pow(a, 2) / 12;
        double sa_z = s_z + Math.pow(alpha, 2) / 12;
        double error_x = sa_x / n_photons * (16.0 / 9.0 + 8 * Math.PI * sa_x * b * b
                / (n_photons * Math.pow(p.getDoubleValueForKey("pixelsize_nm"), 2)));
        double error_z = sa_z / n_photons * (16.0 / 9.0 + 8 * Math.PI * sa_z * b * b
                / (n_photons * Math.pow(p.getDoubleValueForKey("z_sectionsize_nm"), 2)));

        double A = 1.0 / (2 * Math.sqrt(2) * Math.pow(Math.PI, 1.5) * Math.sqrt(sa_z) * sa_x);

        ErrIntFunc eif = new ErrIntFunc();

        eif.setParams(b, n_photons, A, sa_z, sa_x, a, alpha);

        //LegendreGaussIntegrator lgi = new LegendreGaussIntegrator(5, 10, 1000);

        //integrate over 10*width of PSF in z 

        //double size = 10*Math.sqrt(sa_z);

        //double intpart = 0;
        //            try {
        //               
        //               if (b < 0) throw new ConvergenceException(new DummyLocalizable("negative background!")); // a negative value for b seems to cause the integration to hang, preventing the program from progressing
        //               
        //               intpart = lgi.integrate(10000, eif, -size, size);
        //               
        //               double fullIntPart = intpart + Math.pow(2*Math.PI, 1.5)*sa_x*A/Math.sqrt(sa_z);
        //               
        //               error_x = Math.sqrt(2/(n_photons*sa_z/(2*sa_z + sa_x)*fullIntPart));
        //               error_z = Math.sqrt(2/(n_photons*sa_x/(2*sa_z + sa_x)*fullIntPart));
        //               
        //            } catch (ConvergenceException e) {
        //               LoggingUtilities.getLogger().severe("Integration error: " + e.getMessage());
        //               error_x = -1;
        //               error_z = -1;
        //            }
        //            

        if (error_x > 0 && error_z > 0) {

            error = Math.sqrt(2 * error_x * error_x + error_z * error_z);

        } else {
            error = Double.NaN;
        }

        error = 0; // until a better error calculation

        this.fitErrorByChannel.add(error);

        this.positionsByChannel.add(fitParameters.getSubVector(7, 3));

        this.nPhotonsByChannel.add(n_photons);

    }

    this.hadFittingError = false;
    this.nullifyImages();
}

From source file:userinterface.graph.PrismErrorRenderer.java

/**
 * This method is needed for displaying the graph in the correct range (not too zoomed out or in)
 * @param dataset the dataset which needs to be plotted
 * @author Muhammad Omer Saeed/*from   ww  w .  ja  v  a2 s. c  o  m*/
 */

public Range findRangeBounds(XYDataset dataset) {

    if (dataset != null) {

        XYSeriesCollection collection = (XYSeriesCollection) dataset;
        List<XYSeries> series = collection.getSeries();
        double max = Double.MIN_VALUE, min = Double.MAX_VALUE;

        for (XYSeries s : series) {
            for (int i = 0; i < s.getItemCount(); i++) {
                PrismXYDataItem item = (PrismXYDataItem) s.getDataItem(i);

                if ((item.getYValue() - item.getError()) < min) {
                    min = (item.getYValue() - item.getError());
                }

                if ((item.getYValue() + item.getError()) > max) {
                    max = (item.getYValue() + item.getError());
                }
            }
        }

        if (max == Double.MIN_VALUE && min == Double.MAX_VALUE) {
            return null;
        } else
            return new Range(min, max);
    } else {
        return null;
    }
}