示例#1
0
  /**
   * Uses the Haversine formula to calculate the distnace between to lat-long coordinates
   *
   * @param latitude1 The first point's latitude
   * @param longitude1 The first point's longitude
   * @param latitude2 The second point's latitude
   * @param longitude2 The second point's longitude
   * @return The distance between the two points in meters
   */
  public static double CalculateDistance(
      double latitude1, double longitude1, double latitude2, double longitude2) {
    /*
    Haversine formula:
    A = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
    C = 2.atan2(√a, √(1−a))
    D = R.c
    R = radius of earth, 6371 km.
    All angles are in radians
    */

    double deltaLatitude = Math.toRadians(Math.abs(latitude1 - latitude2));
    double deltaLongitude = Math.toRadians(Math.abs(longitude1 - longitude2));
    double latitude1Rad = Math.toRadians(latitude1);
    double latitude2Rad = Math.toRadians(latitude2);

    double a =
        Math.pow(Math.sin(deltaLatitude / 2), 2)
            + (Math.cos(latitude1Rad)
                * Math.cos(latitude2Rad)
                * Math.pow(Math.sin(deltaLongitude / 2), 2));

    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    return 6371 * c * 1000; // Distance in meters
  }
  public static double calAlpha(double theta, double dec) {
    if (Math.abs(dec) + theta > 89.9) return 180;

    return (double)
        Math.toDegrees(
            Math.abs(
                Math.atan(
                    Math.sin(Math.toRadians(theta))
                        / Math.sqrt(
                            Math.cos(Math.toRadians(dec - theta))
                                * Math.cos(Math.toRadians(dec + theta))))));
  }
 /**
  * @author Bogdan Sliptsov
  *     <p>Calculates the distance in km between two lat/long points using the haversine formula
  */
 public double distanceGPS(double lat1, double lng1, double lat2, double lng2) {
   int r = 6371; // average radius of the Earth in km
   double dLat = Math.toRadians(lat2 - lat1);
   double dLon = Math.toRadians(lng2 - lng1);
   double a =
       Math.sin(dLat / 2) * Math.sin(dLat / 2)
           + Math.cos(Math.toRadians(lat1))
               * Math.cos(Math.toRadians(lat2))
               * Math.sin(dLon / 2)
               * Math.sin(dLon / 2);
   double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
   double d = r * c;
   return d;
 }
  /* CALCULATE COORDINATES: Determine new x-y coords given a start x-y and
  a distance and direction */
  public static void calcCoords(int index, int x, int y, double dist, double dirn) {
    while (dirn < 0.0) dirn = 360.0 + dirn;
    while (dirn > 360.0) dirn = dirn - 360.0;
    // System.out.println("dirn = " + dirn);

    // North-East
    if (dirn <= 90.0) {
      xValues[index] = x + (int) (Math.sin(Math.toRadians(dirn)) * dist);
      yValues[index] = y - (int) (Math.cos(Math.toRadians(dirn)) * dist);
      return;
    }
    // South-East
    if (dirn <= 180.0) {
      xValues[index] = x + (int) (Math.cos(Math.toRadians(dirn - 90)) * dist);
      yValues[index] = y + (int) (Math.sin(Math.toRadians(dirn - 90)) * dist);
      return;
    }
    // South-West
    if (dirn <= 90.0) {
      xValues[index] = x - (int) (Math.sin(Math.toRadians(dirn - 180)) * dist);
      yValues[index] = y + (int) (Math.cos(Math.toRadians(dirn - 180)) * dist);
    }
    // Nort-West
    else {
      xValues[index] = x - (int) (Math.cos(Math.toRadians(dirn - 270)) * dist);
      yValues[index] = y - (int) (Math.sin(Math.toRadians(dirn - 270)) * dist);
    }
  }
 public void loseCoins() {
   int x = player1.getX();
   int y = player1.getY();
   double losePercentage = 0.1;
   for (int i = 0;
       i < (int) coins * losePercentage;
       i++) { // makes the user lose 10 percent of the coin and draws them in a circle
     // System.out.println(i);
     int xPos = x + (int) (100 * Math.cos(Math.toRadians((360 / (coins * losePercentage)) * i)));
     int yPos = y - (int) (100 * Math.sin(Math.toRadians((360 / (coins * losePercentage)) * i)));
     coinList.add(new Coin(xPos, yPos, 3));
   }
   coins -= (int) (coins * losePercentage);
 }
  /**
   * When scanning a robot we need to add it to the collection of scanned objects so it can be used
   * later for updates to the bots movement.
   */
  public void onScannedRobot(ScannedRobotEvent e) {
    double targetBearing = getHeading() + e.getBearing();
    double tmpX = getX() + e.getDistance() * Math.sin(Math.toRadians(targetBearing));
    double tmpY = getY() + e.getDistance() * Math.cos(Math.toRadians(targetBearing));
    String name = e.getName();

    if (name.equals(GOAL_NAME)) {
      foundGoal = true;
    }

    obstacles.put(name, new Enemy(tmpX, tmpY, e.getBearing()));

    setTurnRadarRight(getRadarTurnRemaining());
  }
示例#7
0
文件: KubaAI.java 项目: Nuurek/Tanks
  protected Point2D getCrossPointWithSide(
      Point2D point,
      double rotationAngleInDegrees,
      double fieldWidth,
      double fieldHeight,
      GameState.SystemSides side) {
    double centerX = point.getX(), centerY = point.getY();

    double angle = (rotationAngleInDegrees + 360) % 360;

    if (angle == 90) {
      return new Point2D(centerX, fieldHeight);
    } else if (angle == 270) {
      return new Point2D(centerX, 0);
    }

    double a = Math.tan(Math.toRadians(angle));
    double b = centerY - a * centerX;

    switch (side) {
      case Right:
        return new Point2D(fieldWidth, a * fieldWidth + b);
      case Down:
        return new Point2D((fieldHeight - b) / a, fieldHeight);
      case Left:
        return new Point2D(0, b);
      case Up:
        return new Point2D(-b / a, 0);
      default:
        return new Point2D(0, 0);
    }
  }
示例#8
0
 // Set the target angular speed
 public void setRotation(float speed) {
   if (speed == Float.NaN) {
     System.out.println("Excep: setRotation");
     return;
   }
   targetAngularSpeed = (float) Math.toRadians(speed);
 }
示例#9
0
    void draw(Graphics2D g) {

      // toX/toY is tip of arrow and fx/fy is a point on the line -
      // fx/fy is used to determine direction & angle

      AffineTransform at = AffineTransform.getTranslateInstance(toX, toY);
      int b = 9;
      double theta = Math.toRadians(20);
      // The idea of using a GeneralPath is so we can
      // create the (three lines that make up the) arrow
      // (only) one time and then use AffineTransform to
      // place it anywhere we want.
      GeneralPath path = new GeneralPath();

      // distance between line and the arrow mark <** not **
      // Start a new line segment from the position of (0,0).
      path.moveTo(0, 0);
      // Create one of the two arrow head lines.
      int x = (int) (-b * Math.cos(theta));
      int y = (int) (b * Math.sin(theta));
      path.lineTo(x, y);

      // distance between line and the arrow mark <** not **
      // Make the other arrow head line.
      int x2 = (int) (-b * Math.cos(-theta));
      int y2 = (int) (b * Math.sin(-theta));
      // path.moveTo(0,0);
      path.lineTo(x2, y2);
      path.closePath();

      // theta is in radians
      double s, t;
      s = toY - fy; // calculate slopes.
      t = toX - fx;
      if (t != 0) {
        s = s / t;
        theta = Math.atan(s);
        if (t < 0) theta += Math.PI;
      } else if (s < 0) theta = -(Math.PI / 2);
      else theta = Math.PI / 2;

      at.rotate(theta);
      // at.rotate(theta,toX,toY);
      Shape shape = at.createTransformedShape(path);
      if (checkStatus == Status.UNCHECKED) g.setColor(Color.BLACK);
      else if (checkStatus == Status.COMPATIBLE) g.setColor(FOREST_GREEN);
      else g.setColor(ORANGE_RED);
      g.fill(shape);
      g.draw(shape);
    }
示例#10
0
  private static LinkedList<Point2D> getCirclePoints(
      double centerLat, double centerLong, int numberOfPoints, double radius) {

    LinkedList<Point2D> Point2Ds = new LinkedList<Point2D>();

    double lat1, long1;
    double d_rad;
    double delta_pts;
    double radial, lat_rad, dlon_rad, lon_rad;

    // convert coordinates to radians
    lat1 = Math.toRadians(centerLat);
    long1 = Math.toRadians(centerLong);

    // radius is in meters
    d_rad = radius / 6378137;

    // loop through the array and write points
    for (int i = 0; i <= numberOfPoints; i++) {
      delta_pts = 360 / (double) numberOfPoints;
      radial = Math.toRadians((double) i * delta_pts);

      // This algorithm is limited to distances such that dlon < pi/2
      lat_rad =
          Math.asin(
              Math.sin(lat1) * Math.cos(d_rad)
                  + Math.cos(lat1) * Math.sin(d_rad) * Math.cos(radial));
      dlon_rad =
          Math.atan2(
              Math.sin(radial) * Math.sin(d_rad) * Math.cos(lat1),
              Math.cos(d_rad) - Math.sin(lat1) * Math.sin(lat_rad));
      lon_rad = ((long1 + dlon_rad + Math.PI) % (2 * Math.PI)) - Math.PI;

      Point2Ds.add(new Point2D.Double(Math.toDegrees(lat_rad), Math.toDegrees(lon_rad)));
    }
    return Point2Ds;
  }
示例#11
0
  private Tile[] rotate(int angle) {
    Tile[] newTiles = new Tile[4 * 4];
    int offsetX = 3, offsetY = 3;
    if (angle == 90) {
      offsetY = 0;
    } else if (angle == 270) {
      offsetX = 0;
    }

    double rad = Math.toRadians(angle);
    int cos = (int) Math.cos(rad);
    int sin = (int) Math.sin(rad);
    for (int x = 0; x < 4; x++) {
      for (int y = 0; y < 4; y++) {
        int newX = (x * cos) - (y * sin) + offsetX;
        int newY = (x * sin) + (y * cos) + offsetY;
        newTiles[(newX) + (newY) * 4] = tileAt(x, y);
      }
    }
    return newTiles;
  }
 // To add/remove functions change evaluateOperator() and registration
 public double evaluateFunction(String fncnam, ArgParser fncargs) throws ArithmeticException {
   switch (Character.toLowerCase(fncnam.charAt(0))) {
     case 'a':
       {
         if (fncnam.equalsIgnoreCase("abs")) {
           return Math.abs(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("acos")) {
           return Math.acos(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("asin")) {
           return Math.asin(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("atan")) {
           return Math.atan(fncargs.next());
         }
       }
       break;
     case 'c':
       {
         if (fncnam.equalsIgnoreCase("cbrt")) {
           return Math.cbrt(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("ceil")) {
           return Math.ceil(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("cos")) {
           return Math.cos(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("cosh")) {
           return Math.cosh(fncargs.next());
         }
       }
       break;
     case 'e':
       {
         if (fncnam.equalsIgnoreCase("exp")) {
           return Math.exp(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("expm1")) {
           return Math.expm1(fncargs.next());
         }
       }
       break;
     case 'f':
       {
         if (fncnam.equalsIgnoreCase("floor")) {
           return Math.floor(fncargs.next());
         }
       }
       break;
     case 'g':
       {
         //              if(fncnam.equalsIgnoreCase("getExponent"   )) { return
         // Math.getExponent(fncargs.next());                } needs Java 6
       }
       break;
     case 'l':
       {
         if (fncnam.equalsIgnoreCase("log")) {
           return Math.log(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("log10")) {
           return Math.log10(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("log1p")) {
           return Math.log1p(fncargs.next());
         }
       }
       break;
     case 'm':
       {
         if (fncnam.equalsIgnoreCase("max")) {
           return Math.max(fncargs.next(), fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("min")) {
           return Math.min(fncargs.next(), fncargs.next());
         }
       }
       break;
     case 'n':
       {
         //              if(fncnam.equalsIgnoreCase("nextUp"        )) { return Math.nextUp
         // (fncargs.next());                } needs Java 6
       }
       break;
     case 'r':
       {
         if (fncnam.equalsIgnoreCase("random")) {
           return Math.random();
         } // impure
         if (fncnam.equalsIgnoreCase("round")) {
           return Math.round(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("roundHE")) {
           return Math.rint(fncargs.next());
         } // round half-even
       }
       break;
     case 's':
       {
         if (fncnam.equalsIgnoreCase("signum")) {
           return Math.signum(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("sin")) {
           return Math.sin(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("sinh")) {
           return Math.sinh(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("sqrt")) {
           return Math.sqrt(fncargs.next());
         }
       }
       break;
     case 't':
       {
         if (fncnam.equalsIgnoreCase("tan")) {
           return Math.tan(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("tanh")) {
           return Math.tanh(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("toDegrees")) {
           return Math.toDegrees(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("toRadians")) {
           return Math.toRadians(fncargs.next());
         }
       }
       break;
     case 'u':
       {
         if (fncnam.equalsIgnoreCase("ulp")) {
           return Math.ulp(fncargs.next());
         }
       }
       break;
       // no default
   }
   throw new UnsupportedOperationException(
       "MathEval internal function setup is incorrect - internal function \""
           + fncnam
           + "\" not handled");
 }
示例#13
0
  public void open(RandomAccessFile raf, NetcdfFile ncfile, CancelTask cancelTask)
      throws IOException {
    NexradStationDB.init();

    volScan = new Cinrad2VolumeScan(raf, cancelTask);
    if (volScan.hasDifferentDopplarResolutions())
      throw new IllegalStateException("volScan.hasDifferentDopplarResolutions");

    radialDim = new Dimension("radial", volScan.getMaxRadials());
    ncfile.addDimension(null, radialDim);

    makeVariable(
        ncfile,
        Cinrad2Record.REFLECTIVITY,
        "Reflectivity",
        "Reflectivity",
        "R",
        volScan.getReflectivityGroups());
    int velocity_type =
        (volScan.getDopplarResolution() == Cinrad2Record.DOPPLER_RESOLUTION_HIGH_CODE)
            ? Cinrad2Record.VELOCITY_HI
            : Cinrad2Record.VELOCITY_LOW;
    Variable v =
        makeVariable(
            ncfile,
            velocity_type,
            "RadialVelocity",
            "Radial Velocity",
            "V",
            volScan.getVelocityGroups());
    makeVariableNoCoords(
        ncfile, Cinrad2Record.SPECTRUM_WIDTH, "SpectrumWidth", "Spectrum Width", v);

    if (volScan.getStationId() != null) {
      ncfile.addAttribute(null, new Attribute("Station", volScan.getStationId()));
      ncfile.addAttribute(null, new Attribute("StationName", volScan.getStationName()));
      ncfile.addAttribute(
          null, new Attribute("StationLatitude", new Double(volScan.getStationLatitude())));
      ncfile.addAttribute(
          null, new Attribute("StationLongitude", new Double(volScan.getStationLongitude())));
      ncfile.addAttribute(
          null,
          new Attribute("StationElevationInMeters", new Double(volScan.getStationElevation())));

      double latRadiusDegrees = Math.toDegrees(radarRadius / ucar.unidata.geoloc.Earth.getRadius());
      ncfile.addAttribute(
          null,
          new Attribute(
              "geospatial_lat_min", new Double(volScan.getStationLatitude() - latRadiusDegrees)));
      ncfile.addAttribute(
          null,
          new Attribute(
              "geospatial_lat_max", new Double(volScan.getStationLatitude() + latRadiusDegrees)));
      double cosLat = Math.cos(Math.toRadians(volScan.getStationLatitude()));
      double lonRadiusDegrees =
          Math.toDegrees(radarRadius / cosLat / ucar.unidata.geoloc.Earth.getRadius());
      ncfile.addAttribute(
          null,
          new Attribute(
              "geospatial_lon_min", new Double(volScan.getStationLongitude() - lonRadiusDegrees)));
      ncfile.addAttribute(
          null,
          new Attribute(
              "geospatial_lon_max", new Double(volScan.getStationLongitude() + lonRadiusDegrees)));

      // add a radial coordinate transform (experimental)
      Variable ct = new Variable(ncfile, null, null, "radialCoordinateTransform");
      ct.setDataType(DataType.CHAR);
      ct.setDimensions(""); // scalar
      ct.addAttribute(new Attribute("transform_name", "Radial"));
      ct.addAttribute(new Attribute("center_latitude", new Double(volScan.getStationLatitude())));
      ct.addAttribute(new Attribute("center_longitude", new Double(volScan.getStationLongitude())));
      ct.addAttribute(new Attribute("center_elevation", new Double(volScan.getStationElevation())));
      ct.addAttribute(new Attribute(_Coordinate.TransformType, "Radial"));
      ct.addAttribute(
          new Attribute(_Coordinate.AxisTypes, "RadialElevation RadialAzimuth RadialDistance"));

      Array data =
          Array.factory(DataType.CHAR.getPrimitiveClassType(), new int[0], new char[] {' '});
      ct.setCachedData(data, true);
      ncfile.addVariable(null, ct);
    }

    DateFormatter formatter = new DateFormatter();

    ncfile.addAttribute(null, new Attribute(CDM.CONVENTIONS, _Coordinate.Convention));
    ncfile.addAttribute(null, new Attribute("format", volScan.getDataFormat()));
    ncfile.addAttribute(null, new Attribute(CF.FEATURE_TYPE, FeatureType.RADIAL.toString()));
    // Date d = Cinrad2Record.getDate(volScan.getTitleJulianDays(), volScan.getTitleMsecs());
    // ncfile.addAttribute(null, new Attribute("base_date", formatter.toDateOnlyString(d)));

    ncfile.addAttribute(
        null,
        new Attribute(
            "time_coverage_start", formatter.toDateTimeStringISO(volScan.getStartDate())));
    ; // .toDateTimeStringISO(d)));
    ncfile.addAttribute(
        null,
        new Attribute("time_coverage_end", formatter.toDateTimeStringISO(volScan.getEndDate())));

    ncfile.addAttribute(
        null,
        new Attribute(CDM.HISTORY, "Direct read of Nexrad Level 2 file into NetCDF-Java 2.2 API"));
    ncfile.addAttribute(null, new Attribute("DataType", "Radial"));

    ncfile.addAttribute(
        null,
        new Attribute(
            "Title",
            "Nexrad Level 2 Station "
                + volScan.getStationId()
                + " from "
                + formatter.toDateTimeStringISO(volScan.getStartDate())
                + " to "
                + formatter.toDateTimeStringISO(volScan.getEndDate())));

    ncfile.addAttribute(
        null,
        new Attribute(
            "Summary",
            "Weather Surveillance Radar-1988 Doppler (WSR-88D) "
                + "Level II data are the three meteorological base data quantities: reflectivity, mean radial velocity, and "
                + "spectrum width."));

    ncfile.addAttribute(
        null,
        new Attribute(
            "keywords",
            "WSR-88D; NEXRAD; Radar Level II; reflectivity; mean radial velocity; spectrum width"));

    ncfile.addAttribute(
        null,
        new Attribute(
            "VolumeCoveragePatternName",
            Cinrad2Record.getVolumeCoveragePatternName(volScan.getVCP())));
    ncfile.addAttribute(
        null, new Attribute("VolumeCoveragePattern", new Integer(volScan.getVCP())));
    ncfile.addAttribute(
        null,
        new Attribute(
            "HorizonatalBeamWidthInDegrees", new Double(Cinrad2Record.HORIZONTAL_BEAM_WIDTH)));

    ncfile.finish();
  }
示例#14
0
public class NeighborSearch {
  public static final int numZones = 180;
  public static final int numBlocks = 360;
  public static double theta = 1.0 / 60.0;
  public static double blockWidth = 360.0 / numBlocks;
  public static double zoneHeight = 180.0 / numZones;
  private static double blockRanges[][] = new double[numBlocks][2];
  private static double zoneRanges[][] = new double[numZones][2];
  private static double maxAlphas[] = new double[numZones];
  private static double costheta = Math.cos(Math.toRadians(theta));

  public static double calAlpha(double theta, double dec) {
    if (Math.abs(dec) + theta > 89.9) return 180;

    return (double)
        Math.toDegrees(
            Math.abs(
                Math.atan(
                    Math.sin(Math.toRadians(theta))
                        / Math.sqrt(
                            Math.cos(Math.toRadians(dec - theta))
                                * Math.cos(Math.toRadians(dec + theta))))));
  }

  public static void init() {
    zoneRanges[0][0] = -90;
    zoneRanges[0][1] = -90 + zoneHeight;
    for (int i = 1; i < zoneRanges.length; i++) {
      zoneRanges[i][0] = zoneRanges[i - 1][1];
      zoneRanges[i][1] = zoneRanges[i][0] + zoneHeight;
    }

    blockRanges[0][0] = 0;
    blockRanges[0][1] = blockWidth;
    for (int i = 1; i < blockRanges.length; i++) {
      blockRanges[i][0] = blockRanges[i - 1][1];
      blockRanges[i][1] = blockRanges[i][0] + blockWidth;
    }

    for (int i = 0; i < maxAlphas.length; i++) {
      double maxDec = zoneRanges[i][1];
      if (maxDec <= 0) maxDec = zoneRanges[i][0];
      maxAlphas[i] = calAlpha(theta, maxDec);
    }
  }

  public static class Map extends MapReduceBase
      implements Mapper<LongWritable, Star, BlockIDWritable, PairWritable> {

    /* it seems it's very costly to create an object in Java.
     * reuse these objects in every map invocation. */
    private BlockIDWritable loc = new BlockIDWritable();
    private PairWritable p = new PairWritable();
    BlockIDWritable loc1 = new BlockIDWritable();

    public Map() {
      init();
    }

    public void map(
        LongWritable key,
        Star value,
        OutputCollector<BlockIDWritable, PairWritable> output,
        Reporter reporter)
        throws IOException {

      loc.set(value.ra, value.dec);
      int zoneNum = loc.zoneNum;
      int raNum = loc.raNum;
      p.set(value, null);

      /*
       * When the block size increases (> theta), only part of a block
       * needs to be copied to its neighbor.
       */
      output.collect(loc, p);

      /*
       * only replicate objects in the border of a block. I expect most of
       * objects don't need to be copied.
       */
      if (value.dec > zoneRanges[zoneNum][0] + theta
          && value.dec < zoneRanges[zoneNum][1] - theta
          && value.ra > blockRanges[raNum][0] + maxAlphas[zoneNum]
          && value.ra < blockRanges[raNum][1] - maxAlphas[zoneNum]) return;

      /*
       * the code below is to copy the star to some neighbors. We only
       * need to copy an object to the bottom, left, left bottom, left top
       * neighbors
       */
      value.margin = true;

      /*
       * we should treat the entire zone 0 as a block, so we only needs to
       * copy some objects at the corner to their neighbors
       */
      if (loc.zoneNum == 0) {
        /* copy the object to the right top neighbor */
        if (value.ra >= blockRanges[raNum][1] - maxAlphas[zoneNum]
            && value.ra <= blockRanges[raNum][1]
            && value.dec >= zoneRanges[zoneNum][1] - theta
            && value.dec <= zoneRanges[zoneNum][1]) {
          //					BlockIDWritable loc1 = new BlockIDWritable();
          /* raNum of objects in zone 0 is always 0,
           * we need to recalculate it. */
          //					loc1.raNum = BlockIDWritable.ra2Num(value.ra) + 1;
          //					if (loc1.raNum == numBlocks) {
          //						loc1.raNum = 0;
          //						value.ra -= 360;
          //					}
          //					loc1.zoneNum = loc.zoneNum + 1;
          ///					output.collect(loc1, p);
        }
        return;
      } else if (loc.zoneNum == numZones - 1) {
        /* copy the object to the bottom neighbor */
        if (value.dec >= zoneRanges[zoneNum][0] && value.dec <= zoneRanges[zoneNum][0] + theta) {
          /* raNum of objects in zone zoneNum - 1 is always 0,
           * we need to recalculate it. */
          loc1.raNum = BlockIDWritable.ra2Num(value.ra);
          loc1.zoneNum = loc.zoneNum - 1;
          output.collect(loc1, p);

          /* copy the object to the right bottom neighbor */
          while (value.ra >= blockRanges[loc1.raNum][1] - maxAlphas[zoneNum]
              && value.ra <= blockRanges[loc1.raNum][1]) {
            loc1.raNum++;
            if (loc1.raNum == numBlocks) {
              loc1.raNum = 0;
              value.ra -= 360;
            }
            loc1.zoneNum = loc.zoneNum - 1;
            output.collect(loc1, p);
          }
        }
        return;
      }

      boolean wrap = false;
      loc1.raNum = loc.raNum;
      /* copy the object to the right neighbor */
      while (value.ra >= blockRanges[loc1.raNum][1] - maxAlphas[zoneNum]
          && value.ra <= blockRanges[loc1.raNum][1]) {
        loc1.raNum++;
        loc1.zoneNum = loc.zoneNum;
        /*
         * when the object is copied to the right neighbor, we need to
         * be careful. we need to convert ra and raNum if ra is close to
         * 360.
         */
        if (loc1.raNum == numBlocks) {
          loc1.raNum = 0;
          value.ra -= 360;
          wrap = true;
        }
        output.collect(loc1, p);
        /* copy the object to the right bottom neighbor */
        if (value.dec >= zoneRanges[zoneNum][0] && value.dec <= zoneRanges[zoneNum][0] + theta) {
          loc1.zoneNum = loc.zoneNum - 1;
          output.collect(loc1, p);
        }
        /* copy the object to the right top neighbor */
        if (value.dec >= zoneRanges[zoneNum][1] - theta && value.dec <= zoneRanges[zoneNum][1]) {
          loc1.zoneNum = loc.zoneNum + 1;
          output.collect(loc1, p);
        }
      }
      if (wrap) {
        value.ra += 360;
      }

      /* copy the object to the bottom neighbor */
      if (value.dec >= zoneRanges[zoneNum][0] && value.dec <= zoneRanges[zoneNum][0] + theta) {
        loc1.raNum = loc.raNum;
        loc1.zoneNum = loc.zoneNum - 1;
        if (loc1.zoneNum == 0) loc1.raNum = 0;
        output.collect(loc1, p);
      }
    }
  }

  public static class Reduce extends MapReduceBase
      implements Reducer<BlockIDWritable, PairWritable, BlockIDWritable, PairWritable> {
    PairWritable p = new PairWritable();

    public Reduce() {
      init();
    }

    void search(
        Vector<Star> v1,
        Vector<Star> v2,
        BlockIDWritable key,
        OutputCollector<BlockIDWritable, PairWritable> output)
        throws IOException {
      for (int i = 0; i < v1.size(); i++) {
        for (int j = 0; j < v2.size(); j++) {
          Star star1 = v1.get(i);
          Star star2 = v2.get(j);
          // what is this margin about
          if (star1.margin && star2.margin) continue;

          double dist = star1.x * star2.x + star1.y * star2.y + star1.z * star2.z;
          if (dist > costheta) {
            p.set(star1, star2, dist);
            output.collect(key, p);
            p.set(star2, star1, dist);
            output.collect(key, p);
            //		num += 2;

          }
        }
      } // end for i,j
    }

    public void reduce(
        BlockIDWritable key,
        Iterator<PairWritable> values,
        OutputCollector<BlockIDWritable, PairWritable> output,
        Reporter reporter)
        throws IOException {
      // Vector<Star> starV = new Vector<Star>();
      int buketsizeX = 0;
      int buketsizeY = 0;
      double bwidth = maxAlphas[key.zoneNum]; // ra ,x
      double bheight = theta; // dec ,y
      /* add 10 more in each dimension to make sure there is no overflow. */
      Vector<Star>[][] arrstarV =
          new Vector[((int) (zoneHeight / bheight)) + 10]
              [((int) (blockWidth / bwidth)) + 10]; // create bucket vector[Y][X]

      int num = 0;
      while (values.hasNext()) {
        num++;
        Star s = values.next().get(0);

        // participant
        double posx = (s.ra - blockRanges[key.raNum][0]) / bwidth;
        int x = (int) posx + 1; // shit by 1 in case star comes from other block
        double posy = (s.dec - zoneRanges[key.zoneNum][0]) / bheight;
        int y = (int) posy + 1;

        // set bucket size as max
        if (buketsizeX < x) buketsizeX = x;
        if (buketsizeY < y) buketsizeY = y;
        // create according bucket
        if (arrstarV[y][x] == null)
          // TODO avaoid creating vectors here.
          arrstarV[y][x] = new Vector<Star>();
        // put star into bucket
        arrstarV[y][x].add(s);
      }
      // start reducer
      int i, j, row, col;
      // for each bucket
      for (row = 0; row <= buketsizeY; row++) {
        for (col = 0; col <= buketsizeX; col++) {
          //		starV.clear();
          // construct a new vector to do compare
          // TODO we need to avoid searching objects in the border.
          if (arrstarV[row][col] != null) {
            // old method to generate output
            for (i = 0; i < arrstarV[row][col].size(); i++) {
              for (j = i + 1; j < arrstarV[row][col].size(); j++) {
                Star star1 = arrstarV[row][col].get(i);
                Star star2 = arrstarV[row][col].get(j);
                // what is this margin about
                if (star1.margin && star2.margin) continue;

                double dist = star1.x * star2.x + star1.y * star2.y + star1.z * star2.z;
                if (dist > costheta) {
                  p.set(star1, star2, dist);
                  output.collect(key, p);
                  p.set(star2, star1, dist);
                  output.collect(key, p);
                  //		num += 2;

                }
              }
            } // end for i,j

          } // end if
          else {
            continue;
          }
          // 4 more neighbors
          // right upper arrstarV[row-1][col+1] vs arrstarV[row][col]
          if (row != 0 && arrstarV[row - 1][col + 1] != null) {
            search(arrstarV[row][col], arrstarV[row - 1][col + 1], key, output);
          }
          // right arrstarV[row][col+1] vs arrstarV[row][col]
          if (arrstarV[row][col + 1] != null) {
            search(arrstarV[row][col], arrstarV[row][col + 1], key, output);
          }
          // right lower
          if (arrstarV[row + 1][col + 1] != null) {
            search(arrstarV[row][col], arrstarV[row + 1][col + 1], key, output);
          }
          // lower
          if (arrstarV[row + 1][col] != null) {
            search(arrstarV[row][col], arrstarV[row + 1][col], key, output);
          } // end if
        } // end colum
      } // end row
    }
  }

  public static void main(String[] args) throws Exception {
    JobConf conf = new JobConf(NeighborSearch.class);
    conf.setJobName("star searching");

    conf.setOutputKeyClass(BlockIDWritable.class);
    conf.setOutputValueClass(PairWritable.class);

    conf.setMapperClass(Map.class);
    // conf.setCombinerClass(Reduce.class);
    conf.setReducerClass(Reduce.class);
    //		conf.setPartitionerClass(BlockPartitioner.class);

    //		conf.setFloat("mapred.reduce.slowstart.completed.maps", (float) 1.0);

    conf.setInputFormat(StarInputFormat.class);
    conf.setOutputFormat(StarOutputFormat.class);

    FileInputFormat.setInputPaths(conf, new Path(args[0]));
    FileOutputFormat.setOutputPath(conf, new Path(args[1]));

    JobClient.runJob(conf);
  }
}
示例#15
0
 public static void main(String[] args) {
   double deg = 30;
   double rad = Math.toRadians(deg);
   double ans = Math.atan(rad);
   System.out.println(ans);
 }
示例#16
0
 public Vector2 getDirectionPlane() {
   return (new Vector2(
           (float) (-Math.cos(Math.toRadians(this.yaw) - Math.PI / 2)),
           (float) (-Math.sin(Math.toRadians(this.yaw) - Math.PI / 2))))
       .normalize();
 }
示例#17
0
 /**
  * Returns the text rotation in radians : subclassers that don't support rotating text may return
  * 0 here. Used by TextLayout only.
  */
 protected double getRotation() {
   //			debug(set.getAttribute(TEXT_ROTATION).toString());
   return Math.toRadians(element.getAttribute(TEXT_ROTATION).doubleValue());
 }