private void adjustDateLineCrossingPoints() {
      ArrayList<LatLon> corners = new ArrayList<LatLon>(Arrays.asList(sw, se, nw, ne));
      if (!LatLon.locationsCrossDateLine(corners)) return;

      double lonSign = 0;
      for (LatLon corner : corners) {
        if (Math.abs(corner.getLongitude().degrees) != 180)
          lonSign = Math.signum(corner.getLongitude().degrees);
      }

      if (lonSign == 0) return;

      if (Math.abs(sw.getLongitude().degrees) == 180
          && Math.signum(sw.getLongitude().degrees) != lonSign)
        sw = new Position(sw.getLatitude(), sw.getLongitude().multiply(-1), sw.getElevation());
      if (Math.abs(se.getLongitude().degrees) == 180
          && Math.signum(se.getLongitude().degrees) != lonSign)
        se = new Position(se.getLatitude(), se.getLongitude().multiply(-1), se.getElevation());
      if (Math.abs(nw.getLongitude().degrees) == 180
          && Math.signum(nw.getLongitude().degrees) != lonSign)
        nw = new Position(nw.getLatitude(), nw.getLongitude().multiply(-1), nw.getElevation());
      if (Math.abs(ne.getLongitude().degrees) == 180
          && Math.signum(ne.getLongitude().degrees) != lonSign)
        ne = new Position(ne.getLatitude(), ne.getLongitude().multiply(-1), ne.getElevation());
    }
  public static Sector[] splitBoundingSectors(Iterable<? extends LatLon> locations) {
    if (locations == null) {
      throw new IllegalArgumentException("Location In List Is Null");
    }

    if (!locations.iterator().hasNext()) {
      return null;
    }

    double minLat = Angle.POS90.getDegrees();
    double minLon = Angle.POS180.getDegrees();
    double maxLat = Angle.NEG90.getDegrees();
    double maxLon = Angle.NEG180.getDegrees();

    LatLon lastLocation = null;

    for (LatLon ll : locations) {
      double lat = ll.getLatitude().getDegrees();
      if (lat < minLat) {
        minLat = lat;
      }
      if (lat > maxLat) {
        maxLat = lat;
      }

      double lon = ll.getLongitude().getDegrees();
      if (lon >= 0 && lon < minLon) {
        minLon = lon;
      }
      if (lon <= 0 && lon > maxLon) {
        maxLon = lon;
      }

      if (lastLocation != null) {
        double lastLon = lastLocation.getLongitude().getDegrees();
        if (Math.signum(lon) != Math.signum(lastLon)) {
          if (Math.abs(lon - lastLon) < 180) {
            // Crossing the zero longitude line too
            maxLon = 0;
            minLon = 0;
          }
        }
      }
      lastLocation = ll;
    }

    if (minLat == maxLat && minLon == maxLon) {
      return null;
    }

    return new Sector[] {
      Sector.fromDegrees(minLat, maxLat, minLon, 180), // Sector on eastern hemisphere.
      Sector.fromDegrees(minLat, maxLat, -180, maxLon) // Sector on western hemisphere.
    };
  }
Esempio n. 3
0
 private final void computeArea() {
   // The area of a quadrilateral is 0.5*p*q*sin(theta)
   // Where p and q are the length of the 2 diagonals and theta is the angle between them
   // If we rotate P in the right direction, then area = 0.5*p*q*cos(theta) where theta is
   // the angle between Q and the rotated P, but this is simply 0.5 * dot product of P' and Q
   // Note, it is possible because of the cos to get a negative area, when this happens, it means
   // that the quadrilateral has flipped and that the normally inward pointing normals are
   // now pointing outward, so if we get a negative area, we should flip the force vectors...
   Vector2D P = tv.getPosition().subtract(d.getPosition());
   Vector2D Q = dt.getPosition().subtract(v.getPosition());
   area = 0.5 * P.rotate90().dot(Q);
   if (Math.signum(area) != Math.signum(desiredArea) && desiredArea != 0) {
     System.err.println(
         "Compartment:" + this.toString() + " has flipped inside out. Area:" + area);
   }
 }
Esempio n. 4
0
    public void update() {
      // See Compute Area for reason of the absolute value and signum of area...
      double pressureForce =
          Constants.get().getPressure() * (Math.abs(area) - Math.abs(desiredArea));
      pressureForce =
          Math.signum(area) * Math.signum(pressureForce) * Math.sqrt(Math.abs(pressureForce));

      // The pressure is applied on every segment proportionally to its area.
      for (int i = 0, n = nodeList.size(); i < n; i++) {
        Node prevNode = nodeList.get(i);
        Node curNode = nodeList.get((i + 1) % n);
        Node nextNode = nodeList.get((i + 2) % n);

        Vector2D prevVector = curNode.getPosition().subtract(prevNode.getPosition()).rotate270();
        Vector2D nextVector = nextNode.getPosition().subtract(curNode.getPosition()).rotate270();
        forces.put(curNode, prevVector.scale(pressureForce).add(nextVector.scale(pressureForce)));
      }
    }
  /**
   * convenience API to add a curved section to the design
   *
   * @param radius: the bending radius of the section
   * @param eighths: the angle in multiples of 45 deg
   * @return the resulting track design
   */
  public TrackDesign curve(double radius, int eighths) {

    // reasoning: with quarters only, boxing the track becomes a matter of boxing the anchors
    for (int i = 0; i < Math.abs(eighths); i++) {
      Anchor previous = getLastAnchor();
      TrackSection section = new Curve(radius, (int) (Math.signum(eighths)), previous);
      sections.add(section);
    }
    return this;
  }
 public void addPerLengthNumericProximity(
     Counter<String> features, final NumericMentionExpression e) {
   List<NumericTuple> args = e.expression.arguments();
   {
     double multiplier = e.mention_normalized_value / args.get(0).val;
     features.incrementCount("abs-numeric-distance-1", Math.abs(Math.log(multiplier)));
     features.incrementCount("sign-numeric-distance-1", Math.signum(Math.log(multiplier)));
   }
   if (args.size() > 1) {
     double multiplier = e.mention_normalized_value / args.get(1).val;
     features.incrementCount("abs-numeric-distance-2", Math.abs(Math.log(multiplier)));
     features.incrementCount("sign-numeric-distance-2", Math.signum(Math.log(multiplier)));
   }
   if (args.size() > 2) {
     double multiplier = e.mention_normalized_value / args.get(2).val;
     features.incrementCount("abs-numeric-distance-3", Math.abs(Math.log(multiplier)));
     features.incrementCount("sign-numeric-distance-3", Math.signum(Math.log(multiplier)));
   }
 }
Esempio n. 7
0
  private Point teleport(Point location, double offset, Map<Integer, Point> id_lut) {
    Point self = id_lut.get(self_id);
    double x = Math.max(Math.min(location.x, 20), 0);
    double y = Math.max(Math.min(location.y, 20), 0);
    double dx = x - self.x;
    double dy = y - self.y;
    double r = Math.hypot(dx, dy) - offset;
    if (Math.abs(r) > 6) {
      r = Math.signum(r) * 6;
    }
    double th = Math.atan2(dy, dx);

    return new Point(r * Math.cos(th), r * Math.sin(th), self_id);
  }
Esempio n. 8
0
  /**
   * Compute the (inward) normal at each node by averaging the unit direction vectors of the two
   * edges connected to it.
   */
  private void computeNormals() {
    for (int i = 0, n = nodeList.size(); i < n; i++) {
      Node prevNode = nodeList.get(i);
      Node curNode = nodeList.get((i + 1) % n);
      Node nextNode = nodeList.get((i + 2) % n);

      Vector2D prevEdge = curNode.getPosition().subtract(prevNode.getPosition());
      Vector2D nextEdge = nextNode.getPosition().subtract(curNode.getPosition());

      double crossProd = prevEdge.crossMag(nextEdge);
      Vector2D normal =
          prevEdge.normalize().subtract(nextEdge.normalize()).scaleTo(Math.signum(crossProd));

      normals.put(curNode, normal);
    }
  }
  @SuppressWarnings({"UnnecessaryLocalVariable"})
  public double[] getBilinearCoords(double alpha, double beta) {
    // TODO: this method isn't always finding the correct -- or any -- roots
    double eps = 1e-9;
    double u, v;

    double alpha11 = this.w11[1];
    double beta11 = this.w11[2];

    if (Math.abs(alpha11 - 1) < eps) // if alpha11 == 1
    {
      u = alpha;
      if (Math.abs(beta11 - 1) < eps) // if beta == 1
      v = beta;
      else v = beta / (u * (beta11 - 1) + 1);
    } else if (Math.abs(beta11 - 1) < eps) // if beta = 1
    {
      v = beta;
      u = alpha / (v * (alpha11 - 1) + 1);
    } else {
      double a = 1d - beta11;
      double b = alpha * (beta11 - 1) - beta * (alpha11 - 1) - 1;
      double c = alpha;
      double b24ac = b * b - 4 * a * c;

      if (a == 0 || b24ac < 0) return new double[] {-1, -1}; // TODO: Warn.

      double q = -0.5 * (b + (b != 0 ? Math.signum(b) : 1) * Math.sqrt(b24ac));
      u = q / a;
      double ualt = c / q;
      u = Math.abs(u) <= Math.abs(ualt) ? u : ualt;
      if (u < 0 || u > 1) u = c / q;

      v = u * (beta11 - 1) + 1;
      v = Math.abs(v) >= eps ? beta / v : -1;
    }

    return new double[] {u, v};
  }
Esempio n. 10
0
 @Override
 public int compareTo(X that) {
   // TODO Auto-generated method stub
   if (this.b == that.b) return this.a - that.a;
   return (int) Math.signum(that.b - this.b);
 }
 public int compare(ScoreDoc o1, ScoreDoc o2) {
   return (int) Math.signum(o2.score - o1.score);
 }
Esempio n. 12
0
 /**
  * See how far we have gone in which direction since last going the other direction.
  *
  * @return The (signed) distance.
  */
 public int getCurrentDistance() {
   return m_distanceThisDirection * (int) Math.signum(m_lastStep);
 }
 // 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");
 }
  private long estimateNj(final long nj, final double q) {
    // To estimate Nj.

    // 1. Know that Nj >= nj
    // 2. Know that Nj <= N (rowCount)
    long minNj = nj;
    long maxNj = N;

    // Binary search our way to a best Nj value.  Could do this in
    // floating point and come within epsilon of the correct value,
    // but I think we just want to round to the nearest integer.

    final double _1q = 1.0 - q;
    final double njTarget = (double) nj;

    long bestNj = -1;
    long prevBestNj = -1;
    double bestNjDelta = Double.MAX_VALUE;
    do {
      long Nj = ((maxNj - minNj) / 2) + minNj;

      // nj = (q * Nj) / (1 - (1 - q)^Nj)
      double njGuess = compute_nj(q, _1q, (double) Nj);

      if (njGuess == njTarget) {
        // Nailed it.
        return Nj;
      }

      double delta = njTarget - njGuess;
      if (Double.isNaN(delta)) {
        throw new RuntimeException("Got NaN");
      }

      int sign = (int) Math.signum(delta);
      delta = Math.abs(delta);

      if (sign < 0) {
        // Guess is too high
        maxNj = Nj;
      } else if (sign > 0) {
        // Guess it too low
        minNj = Nj;
      } else {
        // Shouldn't be possible.
        assert (false);
        return Nj;
      }

      if (delta <= 1.0) {
        // Very close.
        if (sign < 0) {
          if ((Nj - 1) < minNj) {
            return Nj;
          }

          // Make one last attempt at Nj - 1
          minNj = Nj - 1;
        } else {
          // sign > 0
          if ((Nj + 1) > maxNj) {
            return Nj;
          }

          maxNj = Nj + 1;
        }
      }

      if (delta < bestNjDelta) {
        prevBestNj = bestNj;

        bestNjDelta = delta;
        bestNj = Nj;
      }
    } while ((maxNj - minNj) > 1);

    if (bestNj == minNj) {
      if (prevBestNj == maxNj) {
        // Just tried maxNj, don't try it again.
        return bestNj;
      }

      // Try maxNj to make sure.
      // nj = (q * Nj) / (1 - (1 - q)^Nj)
      double njGuess = compute_nj(q, _1q, (double) maxNj);

      if (Math.abs(njTarget - njGuess) < bestNjDelta) {
        return maxNj;
      }
    } else if (bestNj == maxNj) {
      if (prevBestNj == minNj) {
        // Just tried minNj, don't try it again.
        return bestNj;
      }

      // Try minNj to make sure
      // Try maxNj to make sure.
      // nj = (q * Nj) / (1 - (1 - q)^Nj)
      double njGuess = compute_nj(q, _1q, (double) minNj);

      if (Math.abs(njTarget - njGuess) < bestNjDelta) {
        return minNj;
      }
    } else {
      assert (false);
    }

    return bestNj;
  }
Esempio n. 15
0
  public void addObservedResult(
      double min, double max, double closeVal, long currentTime, String passCode)
      throws IllegalStateValueDataModificationException {
    if (!this.passCode.equals(passCode)) {
      throw new IllegalStateValueDataModificationException();
    }

    int priority = 0;
    Set<Long> closedOrders = new HashSet<Long>();
    for (Map.Entry<Long, OpenOrder> entry : openOrders.entrySet()) {
      long orderNumber = entry.getKey();
      if (orderNumber != currentTime) {
        OpenOrder order = entry.getValue();
        double weight = Math.exp(-priority);
        Integer timeClass = (int) (Math.log(currentTime - orderNumber) / Math.log(2));
        int maxClass = (int) ((max - order.getPrice()) / res);
        int minClass = (int) ((min - order.getPrice()) / res);
        if (!dist.containsKey(timeClass)) {
          dist.put(timeClass, new TreeMap<Integer, Double>());
        }
        for (int i = minClass; i <= maxClass; i++) {
          if (!dist.get(timeClass).containsKey(i)) {
            dist.get(timeClass).put(i, 0.0);
          }

          if (!collapsedDist.containsKey(i)) {
            collapsedDist.put(i, 0.0);
          }
        }
        if (minClass != 0 && maxClass != 0) {
          for (int i = minClass; i <= maxClass; i++) {
            dist.get(timeClass).put(i, dist.get(timeClass).get(i) + weight);
            collapsedDist.put(i, collapsedDist.get(i) + weight);
          }
        }
        sumWeights += weight;
        boolean closed = false;
        if (!order.isClosed()) {
          if (order.getPosition() == 'L') {
            closed = order.newPrice(min);
            if (Math.random() > 0.5) // (!closed)
            {
              closed = order.newPrice(max);
            }
          } else {
            closed = order.newPrice(max);
            if (Math.random() > 0.5) // (!closed)
            {
              closed = order.newPrice(min);
            }
          }

          if (!closed && (currentTime - orderNumber) > maxAge) {
            order.close(closeVal);
            closed = true;
          }

          if (closed) {
            double profit = weight * (order.getPnL() / res);
            // System.out.println("Order Closed from " + state + ": " + orderNumber + ": Profit: " +
            // profit);

            pnl += profit;
            sum = pnl;
            sum2PnL += (profit * profit);
            sum2 = sum2PnL;
            correlator.pnl -= average;
            countClosed += weight;

            average = pnl / countClosed;
            correlator.pnl += average;
            correlator.stackPnL.addToStack(Math.signum(profit));

            double variance = Math.abs(sum2 / countClosed - average);

            sdev = Math.sqrt(variance);
            double average2PnL = average * average;
            sharpe = Math.sqrt(average2PnL / variance);
          }
        }

        if (closed && (currentTime - orderNumber) >= maxAge) {
          closedOrders.add(orderNumber);
        }

        priority++;
      }
    }
    for (long orderNumber : closedOrders) {
      openOrders.remove(orderNumber);
    }
    if (openOrders.isEmpty()) {
      correlator.removeLiveState(this);
    }
  }
 public void addNumericProximity(Counter<String> features, final NumericMentionExpression e) {
   double multiplier = e.mention_normalized_value / e.expression_value;
   features.incrementCount("numeric-distance", Math.log(multiplier));
   features.incrementCount("abs-numeric-distance", Math.abs(Math.log(multiplier)));
   features.incrementCount("sign-numeric-distance", Math.signum(Math.log(multiplier)));
 }