Example usage for java.lang Math toDegrees

List of usage examples for java.lang Math toDegrees

Introduction

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

Prototype

public static double toDegrees(double angrad) 

Source Link

Document

Converts an angle measured in radians to an approximately equivalent angle measured in degrees.

Usage

From source file:ffx.xray.parsers.MTZWriter.java

/**
 * <p>//  w  w w .j  a v a2  s  .c o  m
 * write</p>
 */
public void write() {
    ByteOrder byteOrder = ByteOrder.nativeOrder();
    FileOutputStream fileOutputStream;
    DataOutputStream dataOutputStream;

    try {
        if (logger.isLoggable(Level.INFO)) {
            StringBuilder sb = new StringBuilder();
            sb.append(format("\n Writing MTZ HKL file: \"%s\"\n", fileName));
            logger.info(sb.toString());
        }

        fileOutputStream = new FileOutputStream(fileName);
        dataOutputStream = new DataOutputStream(fileOutputStream);

        byte bytes[] = new byte[80];
        int offset = 0;
        int writeLen = 0;

        int iMapData;
        float fMapData;

        // Header.
        StringBuilder sb = new StringBuilder();
        sb.append("MTZ ");
        dataOutputStream.writeBytes(sb.toString());

        // Header offset.
        int headerOffset = n * nCol + 21;
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        byteBuffer.order(byteOrder).putInt(headerOffset);

        // Machine code: double, float, int, uchar
        // 0x4441 for LE, 0x1111 for BE
        if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
            iMapData = 0x4441;
        } else {
            iMapData = 0x1111;
        }
        byteBuffer.order(byteOrder).putInt(iMapData);
        dataOutputStream.write(bytes, offset, 8);

        sb = new StringBuilder();
        sb.append(" ");
        sb.setLength(68);
        dataOutputStream.writeBytes(sb.toString());

        // Data.
        Vector<String> colname = new Vector<>(nCol);
        char colType[] = new char[nCol];
        double res[] = new double[2];
        res[0] = Double.POSITIVE_INFINITY;
        res[1] = Double.NEGATIVE_INFINITY;
        float colMinMax[][] = new float[nCol][2];
        for (int i = 0; i < nCol; i++) {
            colMinMax[i][0] = Float.POSITIVE_INFINITY;
            colMinMax[i][1] = Float.NEGATIVE_INFINITY;
        }
        ReflectionSpline sigmaASpline = new ReflectionSpline(reflectionList, refinementData.sigmaa.length);
        int col = 0;

        colname.add("H");
        colType[col++] = 'H';
        colname.add("K");
        colType[col++] = 'H';
        colname.add("L");
        colType[col++] = 'H';
        writeLen += 12;

        if (mtzType != MTZType.FCONLY) {
            colname.add("FO");
            colType[col++] = 'F';
            colname.add("SIGFO");
            colType[col++] = 'Q';
            colname.add("FreeR");
            colType[col++] = 'I';
            writeLen += 12;
        }

        if (mtzType != MTZType.DATAONLY) {
            colname.add("Fs");
            colType[col++] = 'F';
            colname.add("PHIFs");
            colType[col++] = 'P';
            colname.add("Fc");
            colType[col++] = 'F';
            colname.add("PHIFc");
            colType[col++] = 'P';
            writeLen += 16;
        }

        if (mtzType == MTZType.ALL) {
            colname.add("FOM");
            colType[col++] = 'W';
            colname.add("PHIW");
            colType[col++] = 'P';
            colname.add("SigmaAs");
            colType[col++] = 'F';
            colname.add("SigmaAw");
            colType[col++] = 'Q';
            colname.add("FWT");
            colType[col++] = 'F';
            colname.add("PHWT");
            colType[col++] = 'P';
            colname.add("DELFWT");
            colType[col++] = 'F';
            colname.add("PHDELWT");
            colType[col++] = 'P';
            writeLen += 32;
        }

        for (HKL ih : reflectionList.hkllist) {
            col = 0;
            int i = ih.index();

            // Skip the 0 0 0 reflection.
            if (ih.h() == 0 && ih.k() == 0 && ih.l() == 0) {
                continue;
            }

            double ss = Crystal.invressq(crystal, ih);
            res[0] = min(ss, res[0]);
            res[1] = max(ss, res[1]);

            // HKL first (3)
            fMapData = ih.h();
            colMinMax[col][0] = min(fMapData, colMinMax[0][0]);
            colMinMax[col][1] = max(fMapData, colMinMax[0][1]);
            byteBuffer.rewind();
            byteBuffer.order(byteOrder).putFloat(fMapData);
            col++;

            fMapData = ih.k();
            colMinMax[col][0] = min(fMapData, colMinMax[1][0]);
            colMinMax[col][1] = max(fMapData, colMinMax[1][1]);
            byteBuffer.order(byteOrder).putFloat(fMapData);
            col++;

            fMapData = ih.l();
            colMinMax[col][0] = min(fMapData, colMinMax[2][0]);
            colMinMax[col][1] = max(fMapData, colMinMax[2][1]);
            byteBuffer.order(byteOrder).putFloat(fMapData);
            col++;

            if (mtzType != MTZType.FCONLY) {
                // F/sigF (2)
                fMapData = (float) refinementData.getF(i);
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) refinementData.getSigF(i);
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;

                // Free R (1)
                fMapData = (float) refinementData.getFreeR(i);
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
            }

            if (mtzType == MTZType.FCONLY) {
                // Fs (2)
                fMapData = (float) refinementData.fsF(i);
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) toDegrees(refinementData.fsPhi(i));
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;

                // Fc (unscaled!) (2)
                fMapData = (float) refinementData.fcF(i);
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) Math.toDegrees(refinementData.fcPhi(i));
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
            }

            if (mtzType == MTZType.ALL) {
                // Fs (2)
                fMapData = (float) refinementData.fsF(i);
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) toDegrees(refinementData.fsPhi(i));
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;

                // Fctot (2)
                fMapData = (float) refinementData.fcTotF(i);
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) toDegrees(refinementData.fcTotPhi(i));
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = Math.min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = Math.max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;

                // FOM/phase (2)
                fMapData = (float) refinementData.fomphi[i][0];
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = Math.min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = Math.max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) toDegrees(refinementData.fomphi[i][1]);
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;

                // Spline setup.
                double fh = spline.f(ss, refinementData.spline);
                double sa = sigmaASpline.f(ss, refinementData.sigmaa);
                double wa = sigmaASpline.f(ss, refinementData.sigmaw);

                // sigmaA/w (2)
                fMapData = (float) sa;
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) wa;
                if (!isNaN(fMapData)) {
                    colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                    colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                }
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;

                // Map coeffs (4).
                fMapData = (float) refinementData.FoFc2F(i);
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) toDegrees(refinementData.FoFc2Phi(i));
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) refinementData.foFc1F(i);
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
                fMapData = (float) toDegrees(refinementData.foFc1Phi(i));
                colMinMax[col][0] = min(fMapData, colMinMax[col][0]);
                colMinMax[col][1] = max(fMapData, colMinMax[col][1]);
                byteBuffer.order(byteOrder).putFloat(fMapData);
                col++;
            }

            dataOutputStream.write(bytes, offset, writeLen);
        }

        // Header.
        sb = new StringBuilder();
        sb.append("VERS MTZ:V1.1 ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss ");
        sb = new StringBuilder();
        sb.append("TITLE FFX output: " + sdf.format(now));
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append(String.format("NCOL %8d %12d %8d", nCol, n, 0));
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("SORT    0    0    0    0    0 ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        char cdata = spaceGroup.shortName.charAt(0);
        if (cdata == 'H') {
            cdata = 'R';
        }
        sb.append(String.format("SYMINF %3d %2d %c %5d %22s %5s", spaceGroup.getNumberOfSymOps(),
                spaceGroup.numPrimitiveSymEquiv, cdata, spaceGroup.number, "'" + spaceGroup.shortName + "'",
                spaceGroup.pointGroupName));
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        for (int i = 0; i < spaceGroup.symOps.size(); i++) {
            sb = new StringBuilder();
            sb.append("SYMM ");
            SymOp symop = spaceGroup.symOps.get(i);
            sb.append(symop.toXYZString());
            while (sb.length() < 80) {
                sb.append(" ");
            }
            dataOutputStream.writeBytes(sb.toString());
        }

        sb = new StringBuilder();
        sb.append(String.format("RESO %8.6f%13s%8.6f", res[0], " ", res[1]));
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("VALM NAN ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("NDIF        1 ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("PROJECT       1 project ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("CRYSTAL       1 crystal ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("DATASET       1 dataset ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        for (int j = 0; j < nCol; j++) {
            sb = new StringBuilder();
            sb.append(String.format("COLUMN %-30s %c %17.4f %17.4f    1", colname.get(j), colType[j],
                    colMinMax[j][0], colMinMax[j][1]));
            dataOutputStream.writeBytes(sb.toString());
        }

        sb = new StringBuilder();
        sb.append(String.format("CELL %10.4f %9.4f %9.4f %9.4f %9.4f %9.4f ", crystal.a, crystal.b, crystal.c,
                crystal.alpha, crystal.beta, crystal.gamma));
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append(String.format("DCELL %9d %10.4f %9.4f %9.4f %9.4f %9.4f %9.4f ", 1, crystal.a, crystal.b,
                crystal.c, crystal.alpha, crystal.beta, crystal.gamma));
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("DWAVEL        1    1.00000 ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("END ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        sb = new StringBuilder();
        sb.append("MTZENDOFHEADERS ");
        while (sb.length() < 80) {
            sb.append(" ");
        }
        dataOutputStream.writeBytes(sb.toString());

        dataOutputStream.close();
    } catch (Exception e) {
        String message = "Fatal exception evaluating structure factors.\n";
        logger.log(Level.SEVERE, message, e);
    }
}

From source file:convcao.com.agent.ConvcaoNeptusInteraction.java

private double[] getBeamMeasurement(EstimatedState state, Distance d) {
    double[] ret = new double[4];

    // H = Ca + Cb
    double varH = d.getValue();
    double varCa = Math.cos(DVL_ANGLE) * varH;
    double varCb = Math.sin(DVL_ANGLE) * varH;

    String beamId = d.getEntityName();

    if (beamId == null)
        beamId = "DVL Filtered";

    double tide = 0;

    if (subtractTide) {
        try {/*from  w w  w .  j a va 2  s . c o  m*/
            tide = TidePredictionFactory.getTideLevel(state.getDate());
        } catch (Exception e) {
            NeptusLog.pub().warn(e);
        }
    }

    double depth = state.getDepth();
    double heading = state.getPsi();

    /* DVL Beams       
     *   (0) | 
     *       |
     *(3) ---+--- (1)
     *       |
     *       | (2)         
     */

    switch (beamId) {
    // pointing down
    case "DVL Filtered":
        varCb = 0;
        varCa = varH;
        break;
    case "DVL Beam 1":
        heading += Math.toRadians(90);
        break;
    case "DVL Beam 2":
        heading += Math.toRadians(180);
        break;
    case "DVL Beam 3":
        heading += Math.toRadians(270);
        break;
    default:
        break;
    }

    LocationType ground = IMCUtils.getLocation(state);
    ground.setOffsetDistance(varCb);
    ground.setAzimuth(Math.toDegrees(heading));
    ground.convertToAbsoluteLatLonDepth();

    double c[] = coords.convert(ground);
    ret[0] = c[0];
    ret[1] = c[1];
    ret[2] = state.getDepth();
    ret[3] = varCa + depth - tide;

    return ret;
}

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

public static void main(String[] args) {
    try {/*from  w  w w.j  av  a  2s. com*/
        LsfLogSource source = new LsfLogSource(new File(
                // "/home/lsts/Desktop/to_upload_20130715/lauv-noptilus-1/20130715/122455_out_survey/Data.lsf"
                "D:\\LSTS-Logs\\2014-11-09-Madeira\\2014-11-12-Madeira_115528_rows_maneuver_cais2_day3\\Data.lsf.gz"),
                null);
        File fxB = source.getFile("mra/bathy.info");
        if (fxB != null && fxB.exists())
            fxB.delete();
        fxB = source.getFile("mra/deltaT-process.txt");
        if (fxB != null && fxB.exists())
            fxB.delete();
        MRAProperties.generateDeltaTProcessReport = true;
        MRAProperties.soundSpeedCorrection = true;
        DeltaTParser p = new DeltaTParser(source);

        int c = 0;
        BathymetrySwath s;
        while ((s = p.nextSwath()) != null) {
            // // for(BathymetryPoint bp : bs.getData()) {
            // // double r[] = CoordinateUtil.latLonAddNE2(bp.lat, bp.lon, bp.north, bp.east);
            // // float f[] = new float[2];
            // //
            // // f[0] = (float) (r[0] * 1000000f);
            // // f[1] = new Double(r[1]).floatValue();
            // //
            // // NeptusLog.pub().info("<###> "+r[0]);
            // // NeptusLog.pub().info("<###> " + f[0]);
            // // }
            // c++;
            // // kryo.writeObject(output, bs);

            System.out.println(Math.toDegrees(s.getPose().getYaw()));
            c++;
        }
        System.out.println(c);

        long fTs = p.getFirstTimestamp();
        long lTs = p.getLastTimestamp();
        long sTs = lTs - fTs;
        Random rand = new Random();
        for (int i = 0; i < 4; i++) {
            double perc = rand.nextDouble();
            long searchTs = (long) (sTs * perc + fTs);
            long markStart = System.nanoTime();
            BathymetrySwath swath = p.getSwathAt(searchTs);
            long markEnd = System.nanoTime();
            System.out.printf("Search swath at '%s' and got one for time '%s' and took %.3fms\n",
                    DateTimeUtil.dateTimeFormatterUTC.format(new Date(searchTs)),
                    (swath != null ? DateTimeUtil.dateTimeFormatterUTC.format(new Date(swath.getTimestamp()))
                            : "NONE"),
                    (markEnd - markStart) / 1E6);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

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 {/*from  w  ww . j a v a  2s. co  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:net.bsrc.cbod.opencv.OpenCV.java

/**
 * @param p1 source/*  w w w.  j  a  v  a  2s.  co m*/
 * @param p2 target
 * @return
 */
public static double getAngle(Point p1, Point p2) {

    double angle = Math.toDegrees(Math.atan2((p2.y - p1.y), (p2.x - p1.x)));

    if (p2.y < p1.y) {
        angle = angle * (-1);
    } else {
        angle = 360 - angle;
    }

    return angle;
}

From source file:com.jiahuan.svgmapview.core.helper.map.SVGParser.java

private static float angle(float x1, float y1, float x2, float y2) {

    return (float) Math.toDegrees(Math.atan2(x1, y1) - Math.atan2(x2, y2)) % 360;
}

From source file:uk.ac.diamond.scisoft.xpdf.views.XPDFPhase.java

/**
 * Changes the present unit cell from hexagonal to rhombohedral.
 * <p> //w w w  .  j  a v  a 2  s  .co  m
 * Changes the unit cell parameters from a hexagonal basis
 * (aac 90,90,120)to a rhombohedral basis (aaa, ), and sets the space
 * group to the rhombohedral equivalent.
 */
private void unitCelltoRhombohedral() {
    setSpaceGroup(spaceGroup.asRhombohedral());

    double ah = unitCellLengths[0], c = unitCellLengths[2];
    // Convert them to the squared lengths
    ah *= ah;
    c *= c;
    // Squared rhombohedral unit cell edge length 
    double ar = ah / 3 + c / 9;
    double alpha = Math.toDegrees(Math.acos((-ah / 6 + c / 9) / ar));
    // Make ar the length
    ar = Math.sqrt(ar);
    unitCellLengths[0] = unitCellLengths[1] = unitCellLengths[2] = ar;
    unitCellDegrees[0] = unitCellDegrees[1] = unitCellDegrees[2] = alpha;
}

From source file:com.udojava.evalex.Expression.java

/**
 * Creates a new expression instance from an expression string with a given
 * default match context.//from   w  w  w.j  a  va  2  s.  c o m
 *
 * @param expression The expression. E.g. <code>"2.4*sin(3)/(2-4)"</code> or
 *                   <code>"sin(y)>0 & max(z, 3)>3"</code>
 */
public Expression(String expression, LinkedList<String> hist, Variables vars) {
    this.history = hist;
    this.expression = expression;

    mainVars = vars;

    addOperator(new Operator("+", 20, true, "Addition") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.ARRAY) {
                MyComplex vo = new MyComplex(v1.list);
                vo.list.add(v2);
                return vo;
            }
            return v1.add(v2);
        }
    });

    addOperator(new Operator("-", 20, true, "Subtraction") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.ARRAY) {
                MyComplex vo = new MyComplex(v1.list);
                vo.list.removeIf(o -> o.equals(v2));
                return vo;
            }
            return v1.subtract(v2);
        }
    });
    addOperator(new Operator("*", 30, true, "Real number multiplication") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            return v1.multiply(v2);
        }
    });
    addOperator(new Operator("/", 30, true, "Real number division") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            return v1.divide(v2);
        }
    });
    addOperator(new Operator("%", 30, true, "Remainder of integer division") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            double r = v1.real % v2.real;
            return new MyComplex(r);
        }
    });
    addOperator(
            new Operator("^", 40, false, "Exponentation. See: https://en.wikipedia.org/wiki/Exponentiation") {
                @Override
                public MyComplex eval(MyComplex v1, MyComplex v2) {
                    return v1.pow(v2);
                }
            });
    addOperator(new Operator("&&", 4, false, "Logical AND. Evaluates to 1 if both operands are not 0") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            boolean b1 = (v1.real == 0.0 && v2.real == 0.0);
            return new MyComplex(b1 ? 1 : 0);
        }
    });

    addOperator(new Operator("||", 2, false, "Logical OR. Evaluates to 0 if both operands are 0") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            boolean b1 = (v1.real == 0.0 && v2.real == 0.0);
            return new MyComplex(b1 ? 0 : 1);
        }
    });

    addOperator(new Operator(">", 10, false,
            "Greater than. See: See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) {
                return new MyComplex(v1.real > v2.real ? 1 : 0);
            } else {
                return new MyComplex(v1.abs() > v2.abs() ? 1 : 0);
            }
        }
    });

    addOperator(new Operator(">=", 10, false, "Greater or equal") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) {
                return new MyComplex(v1.real >= v2.real ? 1 : 0);
            } else {
                return new MyComplex(v1.abs() >= v2.abs() ? 1 : 0);
            }
        }
    });

    addOperator(new Operator("<", 10, false,
            "Less than. See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) {
                return new MyComplex(v1.real < v2.real ? 1 : 0);
            } else {
                return new MyComplex(v1.abs() < v2.abs() ? 1 : 0);
            }
        }
    });

    addOperator(new Operator("<=", 10, false, "less or equal") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) {
                return new MyComplex(v1.real <= v2.real ? 1 : 0);
            } else {
                return new MyComplex(v1.abs() <= v2.abs() ? 1 : 0);
            }
        }
    });

    addOperator(new Operator("->", 7, false, "Set variable v to new value ") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1 instanceof PitDecimal) {
                PitDecimal target = (PitDecimal) v1;
                String s = target.getVarToken();
                setVariable(s, v2);
                return v2;
            }
            throw new ExpressionException("LHS not variable");
        }
    });

    addOperator(new Operator("=", 7, false, "Equality") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) {
                return new MyComplex(v1.real == v2.real ? 1 : 0);
            } else {
                return new MyComplex(v1.abs() == v2.abs() ? 1 : 0);
            }
        }
    });

    addOperator(new Operator("!=", 7, false,
            "Inequality. See: https://en.wikipedia.org/wiki/Inequality_(mathematics)") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            if (v1.type == ValueType.REAL && v2.type == ValueType.REAL) {
                return new MyComplex(v1.real != v2.real ? 1 : 0);
            } else {
                return new MyComplex(v1.abs() != v2.abs() ? 1 : 0);
            }
        }
    });
    addOperator(
            new Operator("or", 7, false, "Bitwise OR. See: https://en.wikipedia.org/wiki/Logical_disjunction") {
                @Override
                public MyComplex eval(MyComplex v1, MyComplex v2) {
                    return new MyComplex((long) v1.real | (long) v2.real);
                }
            });
    addOperator(new Operator("and", 7, false,
            "Bitwise AND. See: https://en.wikipedia.org/wiki/Logical_conjunction") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            return new MyComplex((long) v1.real & (long) v2.real);
        }
    });
    addOperator(new Operator("xor", 7, false, "Bitwise XOR, See: https://en.wikipedia.org/wiki/Exclusive_or") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            return new MyComplex((long) v1.real ^ (long) v2.real);
        }
    });

    addOperator(new Operator("!", 50, true, "Factorial. See https://en.wikipedia.org/wiki/Factorial") {
        public BigInteger factorial(long n) {
            BigInteger factorial = BigInteger.ONE;
            for (long i = 1; i <= n; i++) {
                factorial = factorial.multiply(BigInteger.valueOf(i));
            }
            return factorial;
        }

        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            BigInteger fact = factorial((long) v1.real);
            return new MyComplex(fact, BigInteger.ZERO);
        }
    });

    addOperator(new Operator("~", 8, false, "Bitwise negation") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            BigInteger bi = v2.toBigIntegerReal();
            int c = bi.bitLength();
            if (c == 0) {
                return new MyComplex(1);
            }
            for (int s = 0; s < c; s++) {
                bi = bi.flipBit(s);
            }
            return new MyComplex(bi);
        }
    });

    addOperator(new Operator("shl", 8, false, "Left Bit shift") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            return new MyComplex((long) v1.real << (long) v2.real);
        }
    });

    addOperator(new Operator("shr", 8, false, "Right bit shift") {
        @Override
        public MyComplex eval(MyComplex v1, MyComplex v2) {
            return new MyComplex((long) v1.real >>> (long) v2.real);
        }
    });

    addFunction(new Function("NOT", 1, "evaluates to 0 if argument != 0") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            boolean zero = parameters.get(0).abs() == 0;
            return new MyComplex(zero ? 1 : 0);
        }
    });

    addFunction(new Function("RND", 2, "Give random number in the range between first and second argument") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double low = parameters.get(0).real;
            double high = parameters.get(1).real;
            return new MyComplex(low + Math.random() * (high - low));
        }
    });

    MersenneTwister mers = new MersenneTwister(System.nanoTime());

    addFunction(new Function("MRS", 0, "Mersenne twister random generator") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return new MyComplex(mers.nextDouble());
        }
    });

    addFunction(new Function("BIN", 2, "Binomial Coefficient 'n choose k'") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            int n = (int) parameters.get(0).real;
            int k = (int) parameters.get(1).real;
            double d = CombinatoricsUtils.binomialCoefficientDouble(n, k);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("STIR", 2,
            "Stirling number of 2nd kind: http://mathworld.wolfram.com/StirlingNumberoftheSecondKind.html") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            int n = (int) parameters.get(0).real;
            int k = (int) parameters.get(1).real;
            double d = CombinatoricsUtils.stirlingS2(n, k);
            return new MyComplex(d);
        }
    });

    addFunction(new Function("SIN", 1, "Sine function") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).sin();
        }
    });
    addFunction(new Function("COS", 1, "Cosine function") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).cos();
        }
    });
    addFunction(new Function("TAN", 1, "Tangent") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).tan();
        }
    });
    addFunction(new Function("ASIN", 1, "Reverse Sine") { // added by av
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).asin();
        }
    });
    addFunction(new Function("ACOS", 1, "Reverse Cosine") { // added by av
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).acos();
        }
    });
    addFunction(new Function("ATAN", 1, "Reverse Tangent") { // added by av
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).atan();
        }
    });
    addFunction(new Function("SINH", 1, "Hyperbolic Sine") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).sinh();
        }
    });
    addFunction(new Function("COSH", 1, "Hyperbolic Cosine") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).cosh();
        }
    });
    addFunction(new Function("TANH", 1, "Hyperbolic Tangent") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).tanh();
        }
    });
    addFunction(new Function("RAD", 1, "Transform degree to radian") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double d = Math.toRadians(parameters.get(0).real);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("DEG", 1, "Transform radian to degree") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double d = Math.toDegrees(parameters.get(0).real);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("MAX", -1, "Find the biggest value in a list") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            MyComplex save = new MyComplex(Double.MIN_VALUE);
            if (parameters.size() == 0) {
                throw new ExpressionException("MAX requires at least one parameter");
            }
            //                if (parameters.get(0).type == ValueType.ARRAY)
            //                    parameters = parameters.get(0).list;
            if (parameters.get(0).type == ValueType.COMPLEX) {
                for (MyComplex parameter : parameters) {
                    if (parameter.abs() > save.abs()) {
                        save = parameter;
                    }
                }
                save.type = ValueType.COMPLEX;
            } else {
                for (MyComplex parameter : parameters) {
                    if (parameter.real > save.real) {
                        save = parameter;
                    }
                }
                save.type = ValueType.REAL;
            }
            return save;
        }
    });
    ///////////////////////////////////////////////////////
    addFunction(new Function("IF", 3, "Conditional: give param3 if param1 is 0, otherwise param2") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.get(0).real == 0.0) {
                return parameters.get(2);
            }
            return parameters.get(1);
        }
    });

    addFunction(new Function("PERC", 2, "Get param1 percent of param2") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).divide(new MyComplex(100)).multiply(parameters.get(1));
        }
    });

    addFunction(new Function("PER", 2, "How many percent is param1 of param2") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return parameters.get(0).multiply(new MyComplex(100)).divide(parameters.get(1));
        }
    });

    addFunction(new Function("H", 1, "Evaluate _history element") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            int i = (int) parameters.get(0).real;
            Expression ex = new Expression(history.get(i), history, mainVars);
            return ex.eval();
        }
    });

    addFunction(new Function("MERS", 1, "Calculate Mersenne Number") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            MyComplex p = parameters.get(0);
            return new MyComplex(2).pow(p).subtract(new MyComplex(1));
        }
    });

    addFunction(new Function("GCD", 2, "Find greatest common divisor of 2 values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double a = parameters.get(0).real;
            double b = parameters.get(1).real;
            long r = ArithmeticUtils.gcd((long) a, (long) b);
            return new MyComplex(r);
        }
    });
    addFunction(new Function("LCM", 2, "Find least common multiple of 2 values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double a = parameters.get(0).real;
            double b = parameters.get(1).real;
            long r = ArithmeticUtils.lcm((long) a, (long) b);
            return new MyComplex(r);
        }
    });
    addFunction(new Function("AMEAN", -1, "Arithmetic mean of a set of values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.size() == 0) {
                throw new ExpressionException("MEAN requires at least one parameter");
            }
            Mean m = new Mean();
            double[] d = MyComplex.getRealArray(parameters);
            double d2 = m.evaluate(d);
            return new MyComplex(d2);
        }
    });
    //        addFunction(new Function("BYT", -1,
    //                "Value from sequence of bytes")
    //        {
    //            @Override
    //            public MyComplex eval (List<MyComplex> parameters)
    //            {
    //                if (parameters.size() == 0)
    //                {
    //                    return MyComplex.ZERO;
    //                }
    //                BigInteger res = BigInteger.ZERO;
    //                for (MyComplex parameter : parameters)
    //                {
    //                    if (parameter.intValue() < 0 || parameter.intValue() > 255)
    //                    {
    //                        throw new ExpressionException("not a byte value");
    //                    }
    //                    res = res.shiftLeft(8);
    //                    res = res.or(parameter.toBigInteger());
    //                }
    //                return new MyComplex(res, BigInteger.ZERO);
    //            }
    //        });
    addFunction(new Function("SEQ", 3, "Generate Sequence p1=start, p2=step, p3=count") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double start = parameters.get(0).real;
            ArrayList<MyComplex> arr = new ArrayList<>();
            for (int s = 0; s < (int) (parameters.get(2).real); s++) {
                arr.add(new MyComplex(start));
                start += parameters.get(1).real;
            }
            return new MyComplex(arr);
        }
    });

    addFunction(new Function("PROD", -1, "Product of real values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            Product p = new Product();
            double[] d = MyComplex.getRealArray(parameters);
            return new MyComplex(p.evaluate(d));
        }
    });

    addFunction(new Function("SUM", -1, "Sum of values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            Sum p = new Sum();
            double[] d = MyComplex.getRealArray(parameters);
            return new MyComplex(p.evaluate(d));
        }
    });

    addFunction(new Function("ANG", 1, "Angle phi of complex number in radians") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double b = parameters.get(0).angle();
            return new MyComplex(b);
        }
    });

    addFunction(new Function("IM", 1, "Get imaginary part") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return new MyComplex(parameters.get(0).imaginary);
        }
    });

    addFunction(new Function("RE", 1, "Get real part") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return new MyComplex(parameters.get(0).real);
        }
    });

    addFunction(new Function("POL", 2, "Make complex number from polar coords. angle is first arg") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double angle = parameters.get(0).real;
            double len = parameters.get(1).real;
            Complex c = ComplexUtils.polar2Complex(len, angle);
            return new MyComplex(c);
        }
    });

    addFunction(new Function("GMEAN", -1, "Geometric mean of a set of values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.size() == 0) {
                throw new ExpressionException("MEAN requires at least one parameter");
            }
            GeometricMean m = new GeometricMean();
            double[] d = MyComplex.getRealArray(parameters);
            double d2 = m.evaluate(d);
            return new MyComplex(d2);
        }
    });

    addFunction(new Function("HMEAN", -1, "Harmonic mean of a set of values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.size() == 0) {
                throw new ExpressionException("MEAN requires at least one parameter");
            }
            MyComplex res = new MyComplex(0);
            int num = 0;
            for (MyComplex parameter : parameters) {
                res = res.add(new MyComplex(1).divide(parameter));
                num++;
            }
            res = new MyComplex(res.abs());
            return new MyComplex(num).divide(res);
        }
    });

    addFunction(new Function("VAR", -1, "Variance of a set of values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.size() == 0) {
                throw new ExpressionException("MEAN requires at least one parameter");
            }
            double[] arr = new double[parameters.size()];
            for (int s = 0; s < parameters.size(); s++) {
                arr[s] = parameters.get(s).real;
            }
            return new MyComplex(variance(arr));
        }
    });

    addFunction(new Function("NPR", 1, "Next prime number greater or equal the argument") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return new MyComplex(nextPrime((int) parameters.get(0).real));
        }
    });

    addFunction(new Function("NSWP", 1, "Swap nibbles") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            BigInteger bi = parameters.get(0).toBigIntegerReal();
            String s = bi.toString(16);
            s = new StringBuilder(s).reverse().toString();
            return new MyComplex(new BigInteger(s, 16), BigInteger.ZERO);
        }
    });

    addFunction(new Function("BSWP", 1, "Swap bytes") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            BigInteger bi = parameters.get(0).toBigIntegerReal();
            String s = bi.toString(16);
            while (s.length() % 4 != 0) {
                s = s + "0";
            }
            if (bi.intValue() < 256) {
                s = "00" + s;
            }
            s = Misc.reverseHex(s);
            return new MyComplex(new BigInteger(s, 16), BigInteger.ZERO);
        }
    });

    addFunction(new Function("PYT", 2,
            "Pythagoras's result = sqrt(param1^2+param2^2) https://en.wikipedia.org/wiki/Pythagorean_theorem") {
        @Override
        public MyComplex eval(List<MyComplex> par) {
            double a = par.get(0).real;
            double b = par.get(1).real;
            return new MyComplex(Math.sqrt(a * a + b * b));
        }
    });

    addFunction(new Function("FIB", 1, "Fibonacci number") {
        // --Commented out by Inspection (2/19/2017 7:46 PM):private final Operator exp = operators.get("^");

        @Override
        public MyComplex eval(List<MyComplex> par) {
            return Misc.iterativeFibonacci((int) par.get(0).real);
        }
    });

    ///////////////////////////////////////////////

    addFunction(new Function("MIN", -1, "Find the smallest in a list of values") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            MyComplex save = new MyComplex(Double.MAX_VALUE);
            if (parameters.size() == 0) {
                throw new ExpressionException("MAX requires at least one parameter");
            }
            if (parameters.get(0).type == ValueType.COMPLEX) {
                for (MyComplex parameter : parameters) {
                    if (parameter.abs() < save.abs()) {
                        save = parameter;
                    }
                }
                save.type = ValueType.COMPLEX;
            } else {
                for (MyComplex parameter : parameters) {
                    if (parameter.real < save.real) {
                        save = parameter;
                    }
                }
                save.type = ValueType.REAL;
            }
            return save;
        }
    });
    addFunction(new Function("ABS", 1, "Get absolute value of a number") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return new MyComplex(parameters.get(0).abs());
        }
    });
    addFunction(new Function("LN", 1, "Logarithm base e of the argument") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double d = Math.log(parameters.get(0).real);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("LOG", 1, "Logarithm base 10 of the argument") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double d = Math.log10(parameters.get(0).real);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("FLOOR", 1, "Rounds DOWN to nearest Integer") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double d = Math.floor(parameters.get(0).real);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("CEIL", 1, "Rounds UP to nearest Integer") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double d = Math.ceil(parameters.get(0).real);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("ROU", 1, "Rounds to nearest Integer") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            int d = (int) (parameters.get(0).real + 0.5);
            return new MyComplex(d);
        }
    });
    addFunction(new Function("SQRT", 1, "Square root") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            MyComplex p = parameters.get(0);
            if (p.type == ValueType.REAL) {
                return new MyComplex(Math.sqrt(p.real));
            }
            return p.sqrt();
        }
    });
    addFunction(new Function("ARR", -1, "Create array") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            return new MyComplex(parameters);
        }
    });
    addFunction(new Function("POLY", -1, "Treat array as Polynom") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            double[] d = MyComplex.getRealArray(parameters);
            PolynomialFunction p = new PolynomialFunction(d);
            return new MyComplex(p);
        }
    });
    addFunction(new Function("DRVE", -1, "Make derivative of polynomial") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            PolynomialFunction p;
            if (parameters.get(0).isPoly()) {
                p = new PolynomialFunction(parameters.get(0).getRealArray());
            } else {
                double[] d = MyComplex.getRealArray(parameters);
                p = new PolynomialFunction(d);
            }
            return new MyComplex(p.polynomialDerivative());
        }
    });
    addFunction(new Function("ADRVE", -1, "Make antiderivative of polynomial. Constant is always zero") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            PolynomialFunction p;
            if (parameters.get(0).isPoly()) {
                p = new PolynomialFunction(parameters.get(0).getRealArray());
            } else {
                double[] d = MyComplex.getRealArray(parameters);
                p = new PolynomialFunction(d);
            }
            return new MyComplex(Misc.antiDerive(p));
        }
    });

    addFunction(new Function("PVAL", 2, "Compute value of polynom for the given argument.") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.get(0).isPoly()) {
                PolynomialFunction p = new PolynomialFunction(parameters.get(0).getRealArray());
                double v = p.value(parameters.get(1).real);
                return new MyComplex(v);
            }
            throw new ExpressionException("first arg must be polynomial");
        }
    });

    addFunction(new Function("INTGR", 3, "Numerical integration") {
        @Override
        public MyComplex eval(List<MyComplex> parameters) {
            if (parameters.get(0).isPoly()) {
                PolynomialFunction p = new PolynomialFunction(parameters.get(0).getRealArray());
                double start = parameters.get(1).real;
                double end = parameters.get(2).real;
                SimpsonIntegrator si = new SimpsonIntegrator();
                double d = si.integrate(1000, p, start, end);
                return new MyComplex(d);
            }
            throw new ExpressionException("first arg must be polynomial");
        }
    });

}

From source file:org.kalypsodeegree_impl.graphics.displayelements.RasterDisplayElement_Impl.java

private double calculateSlope(final int i, final int j, final double[][] values, final double xres,
        final double yres, final double z) {
    final double scale = 1.0;
    final double az = 315.0;
    final double alt = 75.0;

    if (i == 0 || i > values.length - 2)
        return Double.NaN;

    if (j == 0 || j > values[0].length - 2)
        return Double.NaN;

    // First Slope ...
    final double x = z * //
            (values[i - 1][j - 1] + values[i - 1][j] + values[i - 1][j] + values[i - 1][j + 1]
                    - values[i + 1][j - 1] - values[i + 1][j] - values[i + 1][j] - values[i + 1][j + 1]) //
            / (8.0 * xres * scale);//from w ww .  j av a  2s .  c  o  m

    final double y = z * //
            (values[i - 1][j + 1] + values[i][j + 1] + values[i][j + 1] + values[i + 1][j + 1]
                    - values[i - 1][j - 1] - values[i][j - 1] - values[i][j - 1] - values[i + 1][j - 1]) //
            / (8.0 * yres * scale);

    final double slope = 90.0 - Math.toDegrees(Math.atan(Math.sqrt(x * x + y * y)));

    // ... then aspect...
    final double aspect = Math.atan2(x, y);

    // ... then the shade value
    final double cang = Math.sin(Math.toRadians(alt)) * Math.sin(Math.toRadians(slope)) + //
            Math.cos(Math.toRadians(alt)) * Math.cos(Math.toRadians(slope)) //
                    * Math.cos(Math.toRadians(az - 90.0) - aspect);

    if (cang <= 0.0)
        return 1.0;

    return cang;
}

From source file:com.skumar.flexibleciruclarseekbar.CircularSeekBar.java

/**
 * Convert from cartesian to polar//from w w  w  .j a  v  a2  s .c om
 *
 * @param xPos current x point
 * @param yPos current y point
 * @return angle of the Thumb w.r.t the arc.
 */
private double getTouchDegrees(float xPos, float yPos) {
    float x = xPos - mTranslateX;
    float y = yPos - mTranslateY;
    //invert the x-coord if we are rotating anti-clockwise
    x = (mClockwise) ? x : -x;
    // convert to arc Angle
    double angle = Math.toDegrees(Math.atan2(y, x) + (Math.PI / 2) - Math.toRadians(mRotation));
    if (angle < 0) {
        angle = 360 + angle;
    }
    angle -= mStartAngle;
    return angle;
}