Example usage for java.lang Float NaN

List of usage examples for java.lang Float NaN

Introduction

In this page you can find the example usage for java.lang Float NaN.

Prototype

float NaN

To view the source code for java.lang Float NaN.

Click Source Link

Document

A constant holding a Not-a-Number (NaN) value of type float .

Usage

From source file:com.xqdev.jam.MLJAM.java

private static void sendXQueryResponse(HttpServletResponse res, Object o) throws IOException {
    // Make sure to leave the status code alone.  It defaults to 200, but sometimes
    // callers of this method will have set it to a custom code.
    res.setContentType("x-marklogic/xquery; charset=UTF-8");
    //res.setContentType("text/plain");
    Writer writer = res.getWriter(); // care to handle errors later?

    if (o == null) {
        writer.write("()");
    }//from   w ww  .  j  ava2 s. c  o m

    else if (o instanceof byte[]) {
        writer.write("binary {'");
        writer.write(hexEncode((byte[]) o));
        writer.write("'}");
    }

    else if (o instanceof Object[]) {
        Object[] arr = (Object[]) o;
        writer.write("(");
        for (int i = 0; i < arr.length; i++) {
            sendXQueryResponse(res, arr[i]);
            if (i + 1 < arr.length)
                writer.write(", ");
        }
        writer.write(")");
    }

    else if (o instanceof String) {
        writer.write("'");
        writer.write(escapeSingleQuotes(o.toString()));
        writer.write("'");
    } else if (o instanceof Integer) {
        writer.write("xs:int(");
        writer.write(o.toString());
        writer.write(")");
    } else if (o instanceof Long) {
        writer.write("xs:integer(");
        writer.write(o.toString());
        writer.write(")");
    } else if (o instanceof Float) {
        Float flt = (Float) o;
        writer.write("xs:float(");
        if (flt.equals(Float.POSITIVE_INFINITY)) {
            writer.write("'INF'");
        } else if (flt.equals(Float.NEGATIVE_INFINITY)) {
            writer.write("'-INF'");
        } else if (flt.equals(Float.NaN)) {
            writer.write("fn:number(())"); // poor man's way to write NaN
        } else {
            writer.write(o.toString());
        }
        writer.write(")");
    } else if (o instanceof Double) {
        Double dbl = (Double) o;
        writer.write("xs:double(");
        if (dbl.equals(Double.POSITIVE_INFINITY)) {
            writer.write("'INF'");
        } else if (dbl.equals(Double.NEGATIVE_INFINITY)) {
            writer.write("'-INF'");
        } else if (dbl.equals(Double.NaN)) {
            writer.write("fn:number(())"); // poor man's way to write NaN
        } else {
            writer.write(o.toString());
        }
        writer.write(")");
    } else if (o instanceof Boolean) {
        writer.write("xs:boolean('");
        writer.write(o.toString());
        writer.write("')");
    } else if (o instanceof BigDecimal) {
        writer.write("xs:decimal(");
        writer.write(o.toString());
        writer.write(")");
    } else if (o instanceof Date) {
        // We want something like: 2006-04-30T01:28:30.499-07:00
        // We format to get:       2006-04-30T01:28:30.499-0700
        // Then we add in the colon
        writer.write("xs:dateTime('");
        String d = dateFormat.format((Date) o);
        writer.write(d.substring(0, d.length() - 2));
        writer.write(":");
        writer.write(d.substring(d.length() - 2));
        writer.write("')");
    } else if (o instanceof XMLGregorianCalendar) {
        XMLGregorianCalendar greg = (XMLGregorianCalendar) o;
        QName type = greg.getXMLSchemaType();
        if (type.equals(DatatypeConstants.DATETIME)) {
            writer.write("xs:dateTime('");
        } else if (type.equals(DatatypeConstants.DATE)) {
            writer.write("xs:date('");
        } else if (type.equals(DatatypeConstants.TIME)) {
            writer.write("xs:time('");
        } else if (type.equals(DatatypeConstants.GYEARMONTH)) {
            writer.write("xs:gYearMonth('");
        } else if (type.equals(DatatypeConstants.GMONTHDAY)) {
            writer.write("xs:gMonthDay('");
        } else if (type.equals(DatatypeConstants.GYEAR)) {
            writer.write("xs:gYear('");
        } else if (type.equals(DatatypeConstants.GMONTH)) {
            writer.write("xs:gMonth('");
        } else if (type.equals(DatatypeConstants.GDAY)) {
            writer.write("xs:gDay('");
        }
        writer.write(greg.toXMLFormat());
        writer.write("')");
    } else if (o instanceof Duration) {
        Duration dur = (Duration) o;
        /*
        // The following fails on Xerces
        QName type = dur.getXMLSchemaType();
        if (type.equals(DatatypeConstants.DURATION)) {
          writer.write("xs:duration('");
        }
        else if (type.equals(DatatypeConstants.DURATION_DAYTIME)) {
          writer.write("xdt:dayTimeDuration('");
        }
        else if (type.equals(DatatypeConstants.DURATION_YEARMONTH)) {
          writer.write("xdt:yearMonthDuration('");
        }
        */
        // If no years or months, must be DURATION_DAYTIME
        if (dur.getYears() == 0 && dur.getMonths() == 0) {
            writer.write("xdt:dayTimeDuration('");
        }
        // If has years or months but nothing else, must be DURATION_YEARMONTH
        else if (dur.getDays() == 0 && dur.getHours() == 0 && dur.getMinutes() == 0 && dur.getSeconds() == 0) {
            writer.write("xdt:yearMonthDuration('");
        } else {
            writer.write("xs:duration('");
        }
        writer.write(dur.toString());
        writer.write("')");
    }

    else if (o instanceof org.jdom.Element) {
        org.jdom.Element elt = (org.jdom.Element) o;
        writer.write("xdmp:unquote('");
        // Because "&lt;" in XQuery is the same as "<" I need to double escape any ampersands
        writer.write(new org.jdom.output.XMLOutputter().outputString(elt).replaceAll("&", "&amp;")
                .replaceAll("'", "''"));
        writer.write("')/*"); // make sure to return the root elt
    } else if (o instanceof org.jdom.Document) {
        org.jdom.Document doc = (org.jdom.Document) o;
        writer.write("xdmp:unquote('");
        writer.write(new org.jdom.output.XMLOutputter().outputString(doc).replaceAll("&", "&amp;")
                .replaceAll("'", "''"));
        writer.write("')");
    } else if (o instanceof org.jdom.Text) {
        org.jdom.Text text = (org.jdom.Text) o;
        writer.write("text {'");
        writer.write(escapeSingleQuotes(text.getText()));
        writer.write("'}");
    } else if (o instanceof org.jdom.Attribute) {
        // <fake xmlns:pref="http://uri.com" pref:attrname="attrvalue"/>/@*:attrname
        // <fake xmlns="http://uri.com" attrname="attrvalue"/>/@*:attrname
        org.jdom.Attribute attr = (org.jdom.Attribute) o;
        writer.write("<fake xmlns");
        if ("".equals(attr.getNamespacePrefix())) {
            writer.write("=\"");
        } else {
            writer.write(":" + attr.getNamespacePrefix() + "=\"");
        }
        writer.write(attr.getNamespaceURI());
        writer.write("\" ");
        writer.write(attr.getQualifiedName());
        writer.write("=\"");
        writer.write(escapeSingleQuotes(attr.getValue()));
        writer.write("\"/>/@*:");
        writer.write(attr.getName());
    } else if (o instanceof org.jdom.Comment) {
        org.jdom.Comment com = (org.jdom.Comment) o;
        writer.write("comment {'");
        writer.write(escapeSingleQuotes(com.getText()));
        writer.write("'}");
    } else if (o instanceof org.jdom.ProcessingInstruction) {
        org.jdom.ProcessingInstruction pi = (org.jdom.ProcessingInstruction) o;
        writer.write("processing-instruction ");
        writer.write(pi.getTarget());
        writer.write(" {'");
        writer.write(escapeSingleQuotes(pi.getData()));
        writer.write("'}");
    }

    else if (o instanceof QName) {
        QName q = (QName) o;
        writer.write("fn:expanded-QName('");
        writer.write(escapeSingleQuotes(q.getNamespaceURI()));
        writer.write("','");
        writer.write(q.getLocalPart());
        writer.write("')");
    }

    else {
        writer.write("error('XQuery tried to retrieve unsupported type: " + o.getClass().getName() + "')");
    }

    writer.flush();
}

From source file:au.org.ala.layers.intersect.Grid.java

public float[] getGrid() {
    int maxArrayLength = Integer.MAX_VALUE - 10;

    if (grid_data != null) {
        return grid_data;
    }//from   w w  w  . ja v a2  s.  c  om

    Grid loadedAlready = getLoadedGrid(filename);
    if (loadedAlready != null && loadedAlready.grid_data != null) {
        return loadedAlready.grid_data;
    }

    int length = nrows * ncols;

    float[] ret = new float[length];

    RandomAccessFile afile = null;
    File f2 = new File(filename + ".GRI");

    try { //read of random access file can throw an exception
        if (!f2.exists()) {
            afile = new RandomAccessFile(filename + ".gri", "r");
        } else {
            afile = new RandomAccessFile(filename + ".GRI", "r");
        }

        byte[] b = new byte[(int) Math.min(afile.length(), maxArrayLength)];

        int i = 0;
        int max = 0;
        int len;
        while ((len = afile.read(b)) > 0) {
            ByteBuffer bb = ByteBuffer.wrap(b);

            if (byteorderLSB) {
                bb.order(ByteOrder.LITTLE_ENDIAN);
            }

            if (datatype.equalsIgnoreCase("UBYTE")) {
                max += len;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.get();
                    if (ret[i] < 0) {
                        ret[i] += 256;
                    }
                }
            } else if (datatype.equalsIgnoreCase("BYTE")) {
                max += len;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.get();
                }
            } else if (datatype.equalsIgnoreCase("SHORT")) {
                max += len / 2;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getShort();
                }
            } else if (datatype.equalsIgnoreCase("INT")) {
                max += len / 4;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getInt();
                }
            } else if (datatype.equalsIgnoreCase("LONG")) {
                max += len / 8;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getLong();
                }
            } else if (datatype.equalsIgnoreCase("FLOAT")) {
                max += len / 4;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = bb.getFloat();
                }
            } else if (datatype.equalsIgnoreCase("DOUBLE")) {
                max += len / 8;
                max = Math.min(max, ret.length);
                for (; i < max; i++) {
                    ret[i] = (float) bb.getDouble();
                }
            } else {
                // / should not happen; catch anyway...
                max += len / 4;
                for (; i < max; i++) {
                    ret[i] = Float.NaN;
                }
            }
        }

        //replace not a number
        for (i = 0; i < length; i++) {
            if ((float) ret[i] == (float) nodatavalue) {
                ret[i] = Float.NaN;
            } else {
                ret[i] *= rescale;
            }
        }
    } catch (Exception e) {
        logger.error("An error has occurred - probably a file error", e);
    } finally {
        if (afile != null) {
            try {
                afile.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    grid_data = ret;
    return ret;
}

From source file:papaya.Rank.java

/**
 * Set <code>ranks[i] = Float.NaN</code> for each i in <code>nanPositions.</code>
 *
 * @param ranks array to modify/* ww  w  . ja  v  a2  s  .  c om*/
 * @param nanPositions list of index values to set to <code>Float.NaN</code>
 */
private static void restoreNaNs(float[] ranks, List<Integer> nanPositions) {
    if (nanPositions.size() == 0) {
        return;
    }
    Iterator<Integer> iterator = nanPositions.iterator();
    while (iterator.hasNext()) {
        ranks[iterator.next().intValue()] = Float.NaN;
    }

}

From source file:pt.lsts.neptus.mra.importers.deltat.DeltaTParser.java

@Override
public BathymetrySwath nextSwath(double prob) {

    if (position == null)
        position = new CorrectedPosition(source);

    try {/*  ww  w .j  a v a 2 s .  c  o  m*/
        if (curPos >= channel.size()) {
            //                cleanupResultOutputFile();
            return null;
        }

        BathymetryPoint data[];
        realNumberOfBeams = 0;

        buf = channel.map(MapMode.READ_ONLY, curPos, 256);
        header = new DeltaTHeader();
        header.parse(buf);

        hasIntensity = header.hasIntensity;
        //            if (hasIntensity)
        //                NeptusLog.pub().info("LOG has intensity");
        //            else
        //                NeptusLog.pub().info("Log doesn't have intensity");

        // Parse and process data ( no need to create another structure for this )
        if (header.hasIntensity)
            buf = channel.map(MapMode.READ_ONLY, curPos + 256, header.numBeams * 4);
        else
            buf = channel.map(MapMode.READ_ONLY, curPos + 256, header.numBeams * 2);

        data = new BathymetryPoint[header.numBeams];

        long timestamp = header.timestamp + MRAProperties.timestampMultibeamIncrement;

        boolean poseFromCorrected = true;
        SystemPositionAndAttitude pose = position.getPosition(timestamp / 1000.0);
        if (pose == null) {

            poseFromCorrected = false;
            pose = new SystemPositionAndAttitude();
            LocationType loc = new LocationType();
            loc.setLatitudeDegs(CoordinateUtil.latFrom83PFormatWorker(header.gnssShipPosLat));
            loc.setLongitudeDegs(CoordinateUtil.lonFrom83PFormatWorker(header.gnssShipPosLon));
            loc.setAbsoluteDepth(-1);
            pose.setPosition(loc);

            pose.setTime(timestamp);
            pose.setAltitude(header.altitude);

            pose.setRoll(Math.toRadians(header.rollAngleDegreesOrientModule));
            pose.setPitch(Math.toRadians(header.pitchAngleDegreesOrientModule));
            pose.setYaw(Math.toRadians(header.headingAngleDegreesOrientModule));

            NeptusLog.pub().warn("No position found on navigation, using partial data from Sonar");
        }

        boolean doSpeedCorrection = MRAProperties.soundSpeedCorrection;

        if (generateProcessReport) {
            recordMsgln();
            recordMsgln("% Swath type & version : " + header.fileType + ", " + header.fileVersion);
            recordMsgln("% Swath time           : "
                    + DateTimeUtil.dateTimeFileNameFormatterMillis.format(new Date(timestamp)));
            recordMsgln("% Swath position       : " + pose.getPosition().toString().replaceAll("\n", " ")
                    + "m depth  :: " + MathMiscUtils.round(pose.getAltitude(), 2) + "m altitude"
                    + (poseFromCorrected ? " from corrected position" : " from data"));
            recordMsgln("% Swath attitude       : R" + MathMiscUtils.round(Math.toDegrees(pose.getRoll()), 1)
                    + "\u00B0 P" + MathMiscUtils.round(Math.toDegrees(pose.getPitch()), 1) + "\u00B0 Y"
                    + MathMiscUtils.round(Math.toDegrees(pose.getYaw()), 1) + "\u00B0");
            recordMsgln("% Orient. module       : R"
                    + MathMiscUtils.round(Math.toDegrees(header.rollAngleDegreesOrientModule), 1) + "\u00B0 P"
                    + MathMiscUtils.round(Math.toDegrees(header.pitchAngleDegreesOrientModule), 1) + "\u00B0 H"
                    + MathMiscUtils.round(Math.toDegrees(header.headingAngleDegreesOrientModule), 1)
                    + "\u00B0");

            recordMsgln("% Ship Course          : " + header.gnssShipCourse + "\u00B0");
            recordMsgln("% Ship Lat/Lon         : " + header.gnssShipPosLat + "  " + header.gnssShipPosLon);
            recordMsgln("% Sonar XYZ offsets    : " + header.sonarXOffset + "m, " + header.sonarYOffset + "m, "
                    + header.sonarZOffset + "m");

            recordMsgln("% Angle start/increment: " + header.startAngle + "\u00B0" + ", "
                    + header.angleIncrement + "\u00B0");
            recordMsgln("% Beams                : " + header.numBeams);
            recordMsgln("% Samples per beam     : " + header.samplesPerBeam);
            recordMsgln("% Number of pings avg  : " + header.numberOfPingsAveraged);
            recordMsgln("% Sample rate high/std : " + (header.sampleRateHigh ? "high" : "std")
                    + " [std(1 in 500)/high (1 in 5000)]");
            recordMsgln("% Range                : " + header.range + "m");
            recordMsgln("% Range resolution     : " + header.rangeResolution + "mm");
            recordMsgln("% Sonar Freq.          : " + header.sonarFreqKHz + "kHz");
            recordMsgln("% Pulse length         : " + header.pulseLength + "\u03BCs");
            recordMsg("% 1/PRF                : " + header.pulseRepetingRate + "ms");
            recordMsgln(
                    " (" + MathMiscUtils.parseToEngineeringNotation(1. / (header.pulseRepetingRate / 1E3), 1)
                            + "Hz)");
            recordMsgln("% Ping number          : " + header.pingNumber);
            recordMsgln("% Sector size          : " + header.sectorSize + "\u00B0 :: "
                    + (header.angleIncrement * header.numBeams) + "\u00B0 calculated");
            recordMsgln("% Speed                : " + MathMiscUtils.round(header.speed, 1) + "m/s");
            recordMsgln("% Sound speed          : " + header.soundVelocity + "m/s"
                    + (doSpeedCorrection ? "" : " (1500m/s used for calculation)"));
            recordMsgln("% Roll correction      : " + (header.dataIsCorrectedForRoll ? "yes" : "no"));
            recordMsgln("% RayBending correction: " + (header.dataIsCorrectedForRayBending ? "yes" : "no"));
            recordMsgln("% Op overlap mode      : " + (header.sonarIsOperatingInOverlappedMode ? "yes" : "no"));
            recordMsgln("% Altitude             : " + header.altitude + "m");
            recordMsgln("% ---------------------");
        }

        StringBuilder rangesStr = new StringBuilder();
        StringBuilder heightStr = new StringBuilder();
        StringBuilder intensityStr = new StringBuilder();
        StringBuilder oxStr = new StringBuilder();
        StringBuilder oyStr = new StringBuilder();
        StringBuilder deltasStr = new StringBuilder();
        float prevX = Float.NaN;
        float prevY = Float.NaN;

        for (int c = 0; c < header.numBeams; c++) {
            double range = buf.getShort(c * 2) * (header.rangeResolution / 1000.0); // rangeResolution in mm 

            if (range == 0.0 || Math.random() > prob) {
                if (generateProcessReport) {
                    if (range != 0) {
                        recordMsgln("% Skip swath beam " + c + " range=" + range);
                    } else {
                        rangesStr.append(" " + MathMiscUtils.round(range, 3));
                        heightStr.append(" " + Double.NaN);
                        intensityStr.append(" " + Double.NaN);
                        oxStr.append(" " + Double.NaN);
                        oyStr.append(" " + Double.NaN);
                        deltasStr.append(" " + Float.NaN);
                        prevX = Float.NaN;
                        prevY = Float.NaN;
                    }
                }
                continue;
            }

            if (doSpeedCorrection && header.soundVelocity != 1500f) {
                range = range * header.soundVelocity / 1500f;
            }

            if (generateProcessReport) {
                rangesStr.append(" " + MathMiscUtils.round(range, 3));
            }

            double angle = header.startAngle + header.angleIncrement * c;
            float height = (float) (range * Math.cos(Math.toRadians(angle)) + pose.getPosition().getDepth());

            double x = range * Math.sin(Math.toRadians(angle));
            double yawAngle = -pose.getYaw();

            float ox = (float) (x * Math.sin(yawAngle));
            float oy = (float) (x * Math.cos(yawAngle));

            if (header.hasIntensity) {
                short intensity = buf.getShort(480 + (c * 2) - 1); // sometimes there's a return = 0
                int intensityInt = 0xffff & intensity;
                data[realNumberOfBeams] = new BathymetryPoint(ox, oy, height, intensityInt);
                data[realNumberOfBeams].intensityMaxValue = 65535;
                if (generateProcessReport)
                    intensityStr.append(" " + intensityInt);
            } else {
                data[realNumberOfBeams] = new BathymetryPoint(ox, oy, height);
                data[realNumberOfBeams].intensityMaxValue = 65535;
                if (generateProcessReport)
                    intensityStr.append(" " + Double.NaN);
            }
            realNumberOfBeams++;

            if (generateProcessReport) {
                heightStr.append(" " + MathMiscUtils.round(height, 3));
                oxStr.append(" " + MathMiscUtils.round(ox, 3));
                oyStr.append(" " + MathMiscUtils.round(oy, 3));
                if (!Float.isNaN(prevX) && !Float.isNaN(prevY)) {
                    float delta = (float) Math.sqrt((ox - prevX) * (ox - prevX) + (oy - prevY) * (oy - prevY));
                    deltasStr.append(" " + MathMiscUtils.round(delta, 3));
                } else {
                    deltasStr.append(" " + Float.NaN);
                }
                prevX = ox;
                prevY = oy;
            }
        }

        if (generateProcessReport) {
            recordMsgln("% Ranges:");
            recordMsgln(rangesStr.toString());
            recordMsgln("% Heights:");
            recordMsgln(heightStr.toString());
            recordMsgln("% Intensities:");
            recordMsgln(intensityStr.toString());
            recordMsgln("% Offsets X:");
            recordMsgln(oxStr.toString());
            recordMsgln("% Offsets Y:");
            recordMsgln(oyStr.toString());
            recordMsgln("% Deltas:");
            recordMsgln(deltasStr.toString());
            recordMsgln("% Number of beams vs read: " + header.numBeams + " vs " + realNumberOfBeams);
        }

        curPos += header.numBytes; // Advance current position

        BathymetrySwath swath = new BathymetrySwath(header.timestamp, pose, data);
        swath.setNumBeams(realNumberOfBeams);

        return swath;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.taobao.weex.dom.WXStyle.java

public float getBorderRadius() {
    float temp = WXUtils.getFloat(get(Constants.Name.BORDER_RADIUS));
    if (WXUtils.isUndefined(temp)) {
        return Float.NaN;
    }/* w w w.j av a2 s .  co m*/
    return temp;
}

From source file:com.palantir.opensource.sysmon.linux.LinuxIOStatJMXWrapper.java

private static float parseFloat(String s) {
    float result = Float.parseFloat(s);
    // deal with occasionally weird values coming out of iostat
    if (result > 1000000000000.0f) {
        result = Float.NaN;
    }/*from  w  ww  .j  av  a 2 s . c  o m*/
    return result;
}

From source file:uk.ac.diamond.scisoft.analysis.dataset.ComplexFloatDataset.java

@Override
public ComplexFloatDataset idivide(final Object b) {
    if (b instanceof AbstractDataset) {
        AbstractDataset bds = (AbstractDataset) b;
        checkCompatibility(bds);/*from  ww w.  java2  s. c  om*/

        IndexIterator it1 = getIterator();
        IndexIterator it2 = bds.getIterator();

        switch (bds.getDtype()) {
        case COMPLEX64:
        case COMPLEX128:
            while (it1.hasNext() && it2.hasNext()) {
                double r1 = data[it1.index];
                double r2 = bds.getElementDoubleAbs(it2.index);
                double i1 = data[it1.index + 1];
                double i2 = bds.getElementDoubleAbs(it2.index + 1);
                if (Math.abs(r2) < Math.abs(i2)) {
                    double q = r2 / i2;
                    double den = r2 * q + i2;
                    data[it1.index] = (float) ((r1 * q + i1) / den); // ADD_CAST
                    data[it1.index + 1] = (float) ((i1 * q - r1) / den); // ADD_CAST
                } else {
                    double q = i2 / r2;
                    double den = i2 * q + r2;
                    if (den == 0) {
                        data[it1.index] = Float.NaN; // CLASS_TYPE
                        data[it1.index + 1] = Float.NaN; // CLASS_TYPE
                    } else {
                        data[it1.index] = (float) ((i1 * q + r1) / den); // ADD_CAST
                        data[it1.index + 1] = (float) ((i1 - r1 * q) / den); // ADD_CAST
                    }
                }
            }
            break;
        default:
            while (it1.hasNext() && it2.hasNext()) {
                float r2 = (float) bds.getElementDoubleAbs(it2.index); // PRIM_TYPE // ADD_CAST
                if (r2 == 0) {
                    data[it1.index] = Float.NaN; // CLASS_TYPE
                    data[it1.index + 1] = Float.NaN; // CLASS_TYPE
                } else {
                    data[it1.index] /= r2;
                    data[it1.index + 1] /= r2;
                }
            }
            break;
        }
    } else {
        float vr = (float) toReal(b); // PRIM_TYPE // ADD_CAST
        float vi = (float) toImag(b); // PRIM_TYPE // ADD_CAST
        IndexIterator it1 = getIterator();

        if (vi == 0) {
            if (vr == 0) {
                while (it1.hasNext()) {
                    data[it1.index] = Float.NaN; // CLASS_TYPE
                    data[it1.index + 1] = Float.NaN; // CLASS_TYPE
                }
            } else {
                while (it1.hasNext()) {
                    data[it1.index] /= vr;
                    data[it1.index + 1] /= vr;
                }
            }
        } else {
            if (Math.abs(vr) < Math.abs(vi)) {
                double q = vr / vi;
                double den = vr * q + vi;
                while (it1.hasNext()) {
                    double r1 = data[it1.index];
                    double i1 = data[it1.index + 1];
                    data[it1.index] = (float) ((r1 * q + i1) / den); // ADD_CAST
                    data[it1.index + 1] = (float) ((i1 * q - r1) / den); // ADD_CAST
                }
            } else {
                double q = vi / vr;
                double den = vi * q + vr;
                while (it1.hasNext()) {
                    double r1 = data[it1.index];
                    double i1 = data[it1.index + 1];
                    data[it1.index] = (float) ((i1 * q + r1) / den); // ADD_CAST
                    data[it1.index + 1] = (float) ((i1 - r1 * q) / den); // ADD_CAST
                }
            }
        }
    }
    setDirty();
    return this;
}

From source file:eu.itesla_project.modules.histo.IIDM2DB.java

public static CimValuesMap extractCimValues(Network n, Config config) {

    CimValuesMap valuesMap = new CimValuesMap();

    for (Substation ss : n.getSubstations()) {

        if (config.getCountryFilter() != null && !config.getCountryFilter().contains(ss.getCountry())) {
            continue;
        }//from   www.j av a2  s.  c  om

        for (VoltageLevel vl : ss.getVoltageLevels()) {

            if (vl.getNominalV() < config.getMinBaseVoltageFilter()) {
                continue;
            }

            String horizon = n.getForecastDistance() > 0 ? "DACF" : "SN"; // for backward compatibility
            final LinkedHashMap<HistoDbAttributeId, Object> valueMap = valuesMap
                    .getValueMap(new HorizonKey(n.getForecastDistance(), horizon));

            if (config.getCimName() != null && !valueMap.containsKey(HistoDbMetaAttributeId.cimName))
                valueMap.put(HistoDbMetaAttributeId.cimName, config.getCimName());

            if (config.isExtractTemporalFields()) {
                if (!valueMap.containsKey(HistoDbMetaAttributeId.datetime))
                    valueMap.put(HistoDbMetaAttributeId.datetime, n.getCaseDate().toDate());
                if (!valueMap.containsKey(HistoDbMetaAttributeId.daytime))
                    valueMap.put(HistoDbMetaAttributeId.daytime, n.getCaseDate().getMillisOfDay());
                if (!valueMap.containsKey(HistoDbMetaAttributeId.month))
                    valueMap.put(HistoDbMetaAttributeId.month, n.getCaseDate().getMonthOfYear());
                if (!valueMap.containsKey(HistoDbMetaAttributeId.forecastTime))
                    valueMap.put(HistoDbMetaAttributeId.forecastTime, n.getForecastDistance());
                if (!valueMap.containsKey(HistoDbMetaAttributeId.horizon))
                    valueMap.put(HistoDbMetaAttributeId.horizon, horizon);
            }

            vl.visitEquipments(new AbstractTopologyVisitor() {

                private void visitInjection(SingleTerminalConnectable inj) {
                    visitInjection(inj, new TerminalContext());
                }

                private void visitInjection(SingleTerminalConnectable inj, TerminalContext context) {
                    Terminal t = inj.getTerminal();
                    context.update(t);

                    if (config.isReplaceMissingValues()) {
                        if (Float.isNaN(context.p)) {
                            context.p = 0f;
                        }
                        if (Float.isNaN(context.q)) {
                            context.q = 0f;
                        }
                        if (Float.isNaN(context.v)) {
                            // use connectable bus voltage, better than nothing...
                            context.v = t.getBusBreakerView().getConnectableBus().getV();
                        }
                        if (Float.isNaN(context.v)) {
                            context.v = 0f; // TODO is there a better value?
                        }
                        if (Float.isNaN(context.i)) {
                            context.i = 0f;
                        }
                    }
                    valueMap.put(new HistoDbNetworkAttributeId(inj.getId(), HistoDbAttr.P), context.p);
                    valueMap.put(new HistoDbNetworkAttributeId(inj.getId(), HistoDbAttr.Q), context.q);
                    valueMap.put(new HistoDbNetworkAttributeId(inj.getId(), HistoDbAttr.V), context.v);
                    valueMap.put(new HistoDbNetworkAttributeId(inj.getId(), HistoDbAttr.I), context.i);
                }

                private void visitBranch(TwoTerminalsConnectable branch, TwoTerminalsConnectable.Side side,
                        float r, float x, float g1, float b1, float g2, float b2, float ratio) {
                    Terminal t = side == TwoTerminalsConnectable.Side.ONE ? branch.getTerminal1()
                            : branch.getTerminal2();

                    TerminalContext context = TerminalContext.create(t);

                    if (config.isReplaceMissingValues()) {
                        if (Float.isNaN(context.p)) {
                            context.p = 0f;
                        }
                        if (Float.isNaN(context.q)) {
                            context.q = 0f;
                        }
                        if (Float.isNaN(context.v)) {
                            Terminal otherT = t == branch.getTerminal1() ? branch.getTerminal2()
                                    : branch.getTerminal1();
                            Bus otherBus = otherT.getBusView().getBus();
                            if (otherBus != null && !Float.isNaN(otherBus.getV())) {
                                // compute the voltage from the other side physical values
                                // TODO approx we do not consider voltage drop due to branch impedance
                                if (t == branch.getTerminal1()) {
                                    // we are on side 1 disconnected and side 2 is connected
                                    context.v = otherBus.getV() / ratio;
                                } else if (t == branch.getTerminal2()) {
                                    // we are on side 2 disconnected and side 1 is connected
                                    context.v = otherBus.getV() * ratio;
                                } else {
                                    throw new AssertionError();
                                }
                            } else {
                                // use connectable bus voltage, better than nothing...
                                context.v = t.getBusBreakerView().getConnectableBus().getV();
                            }
                        }
                        if (Float.isNaN(context.v)) {
                            context.v = 0; // TODO is there a better value?
                        }
                        if (Float.isNaN(context.i)) {
                            context.i = 0;
                        }
                    }
                    valueMap.put(new HistoDbNetworkAttributeId(branch.getId(), t.getVoltageLevel().getId(),
                            HistoDbAttr.P), context.p);
                    valueMap.put(new HistoDbNetworkAttributeId(branch.getId(), t.getVoltageLevel().getId(),
                            HistoDbAttr.Q), context.q);
                    valueMap.put(new HistoDbNetworkAttributeId(branch.getId(), t.getVoltageLevel().getId(),
                            HistoDbAttr.V), context.v);
                    valueMap.put(new HistoDbNetworkAttributeId(branch.getId(), t.getVoltageLevel().getId(),
                            HistoDbAttr.I), context.i);
                }

                @Override
                public void visitGenerator(Generator g) {
                    TerminalContext context = new TerminalContext();
                    visitInjection(g, context);
                    // reactive limit
                    float qmax = g.getReactiveLimits().getMaxQ(context.p);
                    valueMap.put(new HistoDbNetworkAttributeId(g.getId(), HistoDbAttr.QR),
                            Math.abs(qmax - context.q));
                }

                @Override
                public void visitLoad(Load l) {
                    if (l.getLoadType() != LoadType.FICTITIOUS) {
                        visitInjection(l);
                    }
                }

                @Override
                public void visitShuntCompensator(ShuntCompensator sc) {
                    visitInjection(sc);
                }

                @Override
                public void visitDanglingLine(DanglingLine dl) {
                    visitInjection(dl);
                    valueMap.put(new HistoDbNetworkAttributeId(dl.getId(), HistoDbAttr.P0), dl.getP0());
                    valueMap.put(new HistoDbNetworkAttributeId(dl.getId(), HistoDbAttr.Q0), dl.getQ0());
                }

                @Override
                public void visitLine(Line l, Line.Side side) {
                    visitBranch(l, side, l.getR(), l.getX(), l.getG1(), l.getB1(), l.getG2(), l.getB2(), 1);
                }

                @Override
                public void visitTwoWindingsTransformer(TwoWindingsTransformer twt,
                        TwoWindingsTransformer.Side side) {
                    visitBranch(twt, side, twt.getR(), twt.getX(), twt.getG(), twt.getB(), 0, 0,
                            SV.getRatio(twt));
                }

                @Override
                public void visitThreeWindingsTransformer(ThreeWindingsTransformer twt,
                        ThreeWindingsTransformer.Side side) {
                    Terminal t;
                    switch (side) {
                    case ONE:
                        t = twt.getLeg1().getTerminal();
                        break;
                    case TWO:
                        t = twt.getLeg2().getTerminal();
                        break;
                    case THREE:
                        t = twt.getLeg3().getTerminal();
                        break;
                    default:
                        throw new AssertionError();
                    }
                    TerminalContext context = TerminalContext.create(t);

                    if (config.isReplaceMissingValues()) {
                        if (Float.isNaN(context.p)) {
                            context.p = 0f;
                        }
                        if (Float.isNaN(context.q)) {
                            context.q = 0f;
                        }
                        if (Float.isNaN(context.v)) {
                            context.v = 0; // TODO is possible to find a better replacement value?
                        }
                        if (Float.isNaN(context.i)) {
                            context.i = 0f;
                        }
                    }
                    valueMap.put(new HistoDbNetworkAttributeId(twt.getId(), t.getVoltageLevel().getId(),
                            HistoDbAttr.V), context.v);
                    valueMap.put(new HistoDbNetworkAttributeId(twt.getId(), t.getVoltageLevel().getId(),
                            HistoDbAttr.I), context.i);
                    valueMap.put(new HistoDbNetworkAttributeId(twt.getId(), t.getVoltageLevel().getId(),
                            HistoDbAttr.P), context.p);
                    valueMap.put(new HistoDbNetworkAttributeId(twt.getId(), t.getVoltageLevel().getId(),
                            HistoDbAttr.Q), context.q);

                }
            });

            // taps
            for (TwoWindingsTransformer twt : ss.getTwoWindingsTransformers()) {
                if (twt.getPhaseTapChanger() != null) {
                    valueMap.put(new HistoDbNetworkAttributeId(twt.getId(), HistoDbAttr.PTC),
                            twt.getPhaseTapChanger().getTapPosition());
                }
                if (twt.getRatioTapChanger() != null) {
                    valueMap.put(new HistoDbNetworkAttributeId(twt.getId(), HistoDbAttr.RTC),
                            twt.getRatioTapChanger().getTapPosition());
                }
            }
            for (ThreeWindingsTransformer twt : ss.getThreeWindingsTransformers()) {
                valueMap.put(
                        new HistoDbNetworkAttributeId(twt.getId(),
                                twt.getLeg2().getTerminal().getVoltageLevel().getId(), HistoDbAttr.RTC),
                        twt.getLeg2().getRatioTapChanger().getTapPosition());
                valueMap.put(
                        new HistoDbNetworkAttributeId(twt.getId(),
                                twt.getLeg3().getTerminal().getVoltageLevel().getId(), HistoDbAttr.RTC),
                        twt.getLeg3().getRatioTapChanger().getTapPosition());
            }

            /**
             * Extract topologies and mean tension
             */
            try {
                JSONArray toposArray = toTopoSet(vl);
                String jsonRep = toposArray.toString();

                valueMap.put(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.TOPO), jsonRep);

                String base64hash = computeTopoHash(jsonRep);
                valuesMap.addTopology(vl.getId(), base64hash, toposArray);

                valueMap.put(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.TOPOHASH), base64hash);
            } catch (JSONException e) {
                throw new RuntimeException("Failed to gather topologies", e);
            }

            float pgen = 0;
            float qgen = 0;
            float pload = 0;
            float qload = 0;
            float qshunt = 0;

            for (Generator g : vl.getGenerators()) {
                Terminal t = g.getTerminal();
                if (t.getBusView().getBus() != null) {
                    if (!Float.isNaN(t.getP())) {
                        pgen += t.getP();
                    }
                    if (!Float.isNaN(t.getQ())) {
                        qgen += t.getQ();
                    }
                }
            }
            for (Load l : vl.getLoads()) {
                Terminal t = l.getTerminal();
                if (t.getBusView().getBus() != null) {
                    if (!Float.isNaN(t.getP())) {
                        pload += t.getP();
                    }
                    if (!Float.isNaN(t.getQ())) {
                        qload += t.getQ();
                    }
                }
            }
            for (ShuntCompensator s : vl.getShunts()) {
                Terminal t = s.getTerminal();
                if (t.getBusView().getBus() != null) {
                    if (!Float.isNaN(t.getQ())) {
                        qshunt += t.getQ();
                    }
                }
            }

            float vSum = 0;
            int validBusCount = 0;
            int busCount = 0;
            float vMin = Float.NaN;
            float vMax = Float.NaN;
            for (Bus b : vl.getBusView().getBuses()) {
                if (!Float.isNaN(b.getV())) {
                    vSum += b.getV();
                    validBusCount++;
                    vMin = Float.isNaN(vMin) ? b.getV() : Math.min(vMin, b.getV());
                    vMax = Float.isNaN(vMax) ? b.getV() : Math.max(vMax, b.getV());
                }
                busCount++;
            }
            float meanV = Float.NaN;
            if (validBusCount > 0) {
                meanV = vSum / validBusCount;
            }
            if (config.isReplaceMissingValues()) {
                if (Float.isNaN(meanV)) {
                    meanV = 0; // TODO is there a better value?
                }
                if (Float.isNaN(vMin)) {
                    vMin = 0; // TODO is there a better value?
                }
                if (Float.isNaN(vMax)) {
                    vMax = 0; // TODO is there a better value?
                }
            }

            valueMap.put(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.PGEN), pgen);
            valueMap.put(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.QGEN), qgen);
            valueMap.put(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.PLOAD), pload);
            valueMap.put(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.QLOAD), qload);
            valueMap.put(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.QSHUNT), qshunt);
            valueMap.put(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.V), meanV);
            valueMap.put(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.VMIN), vMin);
            valueMap.put(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.VMAX), vMax);
            valueMap.put(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.BC), busCount);
        }
    }

    return valuesMap;

}

From source file:com.tmall.wireless.tangram3.dataparser.concrete.Card.java

public void storeAspectRatio() {
    if (style != null && !Float.isNaN(style.aspectRatio)) {
        mTmpAspectRatio = style.aspectRatio;
        style.aspectRatio = Float.NaN;
    }//www .java 2 s  .c  o m
}

From source file:eu.itesla_project.modules.validation.OfflineValidationTool.java

@Override
public void run(CommandLine line) throws Exception {
    OfflineConfig config = OfflineConfig.load();
    String rulesDbName = line.hasOption("rules-db-name") ? line.getOptionValue("rules-db-name")
            : OfflineConfig.DEFAULT_RULES_DB_NAME;
    String workflowId = line.getOptionValue("workflow");
    Path outputDir = Paths.get(line.getOptionValue("output-dir"));
    double purityThreshold = line.hasOption("purity-threshold")
            ? Double.parseDouble(line.getOptionValue("purity-threshold"))
            : DEFAULT_PURITY_THRESHOLD;//from w  w  w  .j ava  2s .c  o  m
    Set<Country> countries = Arrays.stream(line.getOptionValue("base-case-countries").split(","))
            .map(Country::valueOf).collect(Collectors.toSet());
    Interval histoInterval = Interval.parse(line.getOptionValue("history-interval"));
    boolean mergeOptimized = line.hasOption("merge-optimized");
    CaseType caseType = CaseType.valueOf(line.getOptionValue("case-type"));

    CaseRepositoryFactory caseRepositoryFactory = config.getCaseRepositoryFactoryClass().newInstance();
    RulesDbClientFactory rulesDbClientFactory = config.getRulesDbClientFactoryClass().newInstance();
    ContingenciesAndActionsDatabaseClient contingencyDb = config.getContingencyDbClientFactoryClass()
            .newInstance().create();
    SimulatorFactory simulatorFactory = config.getSimulatorFactoryClass().newInstance();
    LoadFlowFactory loadFlowFactory = config.getLoadFlowFactoryClass().newInstance();
    MergeOptimizerFactory mergeOptimizerFactory = config.getMergeOptimizerFactoryClass().newInstance();

    SimulationParameters simulationParameters = SimulationParameters.load();

    try (ComputationManager computationManager = new LocalComputationManager();
            RulesDbClient rulesDb = rulesDbClientFactory.create(rulesDbName);
            CsvMetricsDb metricsDb = new CsvMetricsDb(outputDir, true, "metrics")) {

        CaseRepository caseRepository = caseRepositoryFactory.create(computationManager);

        Queue<DateTime> dates = Queues.synchronizedDeque(
                new ArrayDeque<>(caseRepository.dataAvailable(caseType, countries, histoInterval)));

        Map<String, Map<RuleId, ValidationStatus>> statusPerRulePerCase = Collections
                .synchronizedMap(new TreeMap<>());
        Map<String, Map<RuleId, Map<HistoDbAttributeId, Object>>> valuesPerRulePerCase = Collections
                .synchronizedMap(new TreeMap<>());

        int cores = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(cores);
        try {
            List<Future<?>> tasks = new ArrayList<>(cores);
            for (int i = 0; i < cores; i++) {
                tasks.add(executorService.submit((Runnable) () -> {
                    while (dates.size() > 0) {
                        DateTime date = dates.poll();

                        try {
                            Network network = MergeUtil.merge(caseRepository, date, caseType, countries,
                                    loadFlowFactory, 0, mergeOptimizerFactory, computationManager,
                                    mergeOptimized);

                            System.out.println("case " + network.getId() + " loaded");

                            System.out.println("running simulation on " + network.getId() + "...");

                            network.getStateManager().allowStateMultiThreadAccess(true);
                            String baseStateId = network.getId();
                            network.getStateManager().cloneState(StateManager.INITIAL_STATE_ID, baseStateId);
                            network.getStateManager().setWorkingState(baseStateId);

                            Map<RuleId, ValidationStatus> statusPerRule = new HashMap<>();
                            Map<RuleId, Map<HistoDbAttributeId, Object>> valuesPerRule = new HashMap<>();

                            LoadFlow loadFlow = loadFlowFactory.create(network, computationManager, 0);
                            LoadFlowResult loadFlowResult = loadFlow.run();

                            System.err.println("load flow terminated (" + loadFlowResult.isOk() + ") on "
                                    + network.getId());

                            if (loadFlowResult.isOk()) {
                                Stabilization stabilization = simulatorFactory.createStabilization(network,
                                        computationManager, 0);
                                ImpactAnalysis impactAnalysis = simulatorFactory.createImpactAnalysis(network,
                                        computationManager, 0, contingencyDb);
                                Map<String, Object> context = new HashMap<>();
                                stabilization.init(simulationParameters, context);
                                impactAnalysis.init(simulationParameters, context);
                                StabilizationResult stabilizationResult = stabilization.run();

                                System.err.println("stabilization terminated ("
                                        + stabilizationResult.getStatus() + ") on " + network.getId());

                                metricsDb.store(workflowId, network.getId(), "STABILIZATION",
                                        stabilizationResult.getMetrics());

                                if (stabilizationResult.getStatus() == StabilizationStatus.COMPLETED) {
                                    ImpactAnalysisResult impactAnalysisResult = impactAnalysis
                                            .run(stabilizationResult.getState());

                                    System.err.println("impact analysis terminated on " + network.getId());

                                    metricsDb.store(workflowId, network.getId(), "IMPACT_ANALYSIS",
                                            impactAnalysisResult.getMetrics());

                                    System.out.println("checking rules on " + network.getId() + "...");

                                    for (SecurityIndex securityIndex : impactAnalysisResult
                                            .getSecurityIndexes()) {
                                        for (RuleAttributeSet attributeSet : RuleAttributeSet.values()) {
                                            statusPerRule.put(new RuleId(attributeSet, securityIndex.getId()),
                                                    new ValidationStatus(null, securityIndex.isOk()));
                                        }
                                    }
                                }
                            }

                            Map<HistoDbAttributeId, Object> values = IIDM2DB
                                    .extractCimValues(network, new IIDM2DB.Config(null, false))
                                    .getSingleValueMap();
                            for (RuleAttributeSet attributeSet : RuleAttributeSet.values()) {
                                for (Contingency contingency : contingencyDb.getContingencies(network)) {
                                    List<SecurityRule> securityRules = rulesDb.getRules(workflowId,
                                            attributeSet, contingency.getId(), null);
                                    for (SecurityRule securityRule : securityRules) {
                                        SecurityRuleExpression securityRuleExpression = securityRule
                                                .toExpression(purityThreshold);
                                        SecurityRuleCheckReport checkReport = securityRuleExpression
                                                .check(values);

                                        valuesPerRule.put(securityRule.getId(),
                                                ExpressionAttributeList
                                                        .list(securityRuleExpression.getCondition()).stream()
                                                        .collect(Collectors.toMap(attributeId -> attributeId,
                                                                new Function<HistoDbAttributeId, Object>() {
                                                                    @Override
                                                                    public Object apply(
                                                                            HistoDbAttributeId attributeId) {
                                                                        Object value = values.get(attributeId);
                                                                        return value != null ? value
                                                                                : Float.NaN;
                                                                    }
                                                                })));

                                        ValidationStatus status = statusPerRule.get(securityRule.getId());
                                        if (status == null) {
                                            status = new ValidationStatus(null, null);
                                            statusPerRule.put(securityRule.getId(), status);
                                        }
                                        if (checkReport.getMissingAttributes().isEmpty()) {
                                            status.setRuleOk(checkReport.isSafe());
                                        }
                                    }
                                }
                            }

                            statusPerRulePerCase.put(network.getId(), statusPerRule);
                            valuesPerRulePerCase.put(network.getId(), valuesPerRule);
                        } catch (Exception e) {
                            LOGGER.error(e.toString(), e);
                        }
                    }
                }));
            }
            for (Future<?> task : tasks) {
                task.get();
            }
        } finally {
            executorService.shutdown();
            executorService.awaitTermination(1, TimeUnit.MINUTES);
        }

        writeCsv(statusPerRulePerCase, valuesPerRulePerCase, outputDir);
    }
}