Exemplo n.º 1
0
  @Override
  public void trainMostSimilar(List<EnsembleSim> simList) {
    if (simList.isEmpty()) {
      throw new IllegalStateException("no examples to train on!");
    }
    mostSimilarInterpolator.trainMostSimilar(simList);

    // Remove things that have no observed metrics
    List<EnsembleSim> pruned = new ArrayList<EnsembleSim>();
    for (EnsembleSim es : simList) {
      if (es != null && es.getNumMetricsWithScore() > 0) {
        pruned.add(es);
      }
    }

    double[][] X = new double[pruned.size()][numMetrics * 2];
    double[] Y = new double[pruned.size()];
    for (int i = 0; i < pruned.size(); i++) {
      Y[i] = pruned.get(i).knownSim.similarity;
      EnsembleSim es = mostSimilarInterpolator.interpolate(pruned.get(i));
      for (int j = 0; j < numMetrics; j++) {
        X[i][2 * j] = es.getScores().get(j);
        X[i][2 * j + 1] = Math.log(es.getRanks().get(j) + 1);
      }
    }

    OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression();
    regression.newSampleData(Y, X);

    mostSimilarCoefficients = new TDoubleArrayList(regression.estimateRegressionParameters());
    double pearson = Math.sqrt(regression.calculateRSquared());
    LOG.info("coefficients are " + mostSimilarCoefficients.toString());
    LOG.info("pearson for multiple regression is " + pearson);
  }
Exemplo n.º 2
0
  public static double[] interpolate(
      double min, double max, double step, double curve[][], double result[]) {
    Interpolator interpolator = new Interpolator();

    if (result == null) result = new double[(int) ((max - min) / step)];

    for (int i = 0; i < result.length; i++)
      result[i] = interpolator.interpolate(min + step * i, curve);

    return result;
  }
Exemplo n.º 3
0
  public static short[] interpolate(
      double min, double max, double step, double curve[][], short result[]) {
    Interpolator interpolator = new Interpolator();

    if (result == null) result = new short[(int) ((max - min) / step)];

    for (int i = 0; i < result.length; i++)
      result[i] =
          (short) ((int) (interpolator.interpolate(min + step * i, curve) * 0xffff + 0.5) & 0xffff);

    return result;
  }
Exemplo n.º 4
0
  /**
   * Computes the interpolation of the new bets.
   *
   * @param bets
   */
  public synchronized void updateBets(List<BetContainer> bets) {

    // Add bets not in the list betsPoint
    for (BetContainer betContainer : bets) {
      boolean found = false;
      for (Interpolator<BetContainer> b : betsPoint) {
        if (b.getObject().equals(betContainer)) {
          found = true;
        }
      }
      if (!found) {
        betsPoint.add(
            new Interpolator<BetContainer>(
                baseX(betContainer.getBet().getBetToken().getStable() - 1, BET_Y_POSITION) - 10,
                BET_Y_POSITION,
                betContainer));
      }
    }

    // Remove bets in the list betsPoint that are not in bets
    Iterator<Interpolator<BetContainer>> bIter = betsPoint.iterator();
    while (bIter.hasNext()) {
      Interpolator<BetContainer> b = bIter.next();
      boolean found = false;
      for (BetContainer betContainer : bets) {
        if (b.getObject().equals(betContainer)) {
          found = true;
        }
      }
      if (!found) {
        bIter.remove();
      }
    }

    // Check if there's more than one interpolator overlapped and move them
    boolean overlap = false;
    do {
      overlap = false;
      for (Interpolator<BetContainer> i1 : betsPoint) {
        for (Interpolator<BetContainer> i2 : betsPoint) {
          if (i1 != i2
              && Math.abs(i1.destination.x - i2.destination.x) < 20
              && Math.abs(i1.destination.y - i2.destination.y) < 45) {
            i1.setNewPosition(i1.destination.x, i1.destination.y + 30, 1000);
            i2.setNewPosition(i2.destination.x, i2.destination.y - 30, 1000);
            i1.start();
            i2.start();
            overlap = true;
          }
        }
      }
    } while (overlap);
  }
Exemplo n.º 5
0
  @Override
  public void trainSimilarity(List<EnsembleSim> simList) {
    if (simList.isEmpty()) {
      throw new IllegalArgumentException("no examples to train on!");
    }
    similarityInterpolator.trainSimilarity(simList);
    double[][] X = new double[simList.size()][numMetrics];
    double[] Y = new double[simList.size()];
    for (int i = 0; i < simList.size(); i++) {
      Y[i] = simList.get(i).knownSim.similarity;
      EnsembleSim es = similarityInterpolator.interpolate(simList.get(i));
      for (int j = 0; j < numMetrics; j++) {
        X[i][j] = es.getScores().get(j);
      }
    }
    OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression();
    regression.newSampleData(Y, X);

    simlarityCoefficients = new TDoubleArrayList(regression.estimateRegressionParameters());
    double pearson = Math.sqrt(regression.calculateRSquared());
    LOG.info("coefficients are " + simlarityCoefficients.toString());
    LOG.info("pearson for multiple regression is " + pearson);
  }
Exemplo n.º 6
0
 @Override
 public SRResult predictSimilarity(List<SRResult> scores) {
   if (scores.size() + 1 != simlarityCoefficients.size()) {
     throw new IllegalStateException();
   }
   double weightedScore = simlarityCoefficients.get(0);
   for (int i = 0; i < scores.size(); i++) {
     double s = scores.get(i) == null ? Double.NaN : scores.get(i).getScore();
     if (Double.isNaN(s) || Double.isInfinite(s)) {
       s = similarityInterpolator.getInterpolatedScore(i);
     }
     weightedScore += (s * simlarityCoefficients.get(i + 1));
   }
   return new SRResult(weightedScore);
 }
Exemplo n.º 7
0
  @Override
  public SRResultList predictMostSimilar(
      List<SRResultList> scores, int maxResults, TIntSet validIds) {
    if (2 * scores.size() + 1 != mostSimilarCoefficients.size()) {
      throw new IllegalStateException();
    }
    TIntSet allIds = new TIntHashSet(); // ids returned by at least one metric
    for (SRResultList resultList : scores) {
      if (resultList != null) {
        for (SRResult result : resultList) {
          allIds.add(result.getId());
        }
      }
    }

    TIntDoubleHashMap scoreMap = new TIntDoubleHashMap();
    for (int id : allIds.toArray()) {
      scoreMap.put(id, mostSimilarCoefficients.get(0));
    }
    int i = 1;
    for (SRResultList resultList : scores) {
      TIntSet unknownIds = new TIntHashSet(allIds);
      double c1 = mostSimilarCoefficients.get(i); // score coeff
      double c2 = mostSimilarCoefficients.get(i + 1); // rank coefficient
      if (resultList != null) {
        for (int j = 0; j < resultList.numDocs(); j++) {
          int rank = j + 1;
          // expand or contract ranks proportionately
          if (validIds != null) {
            double k = 1.0 * numTrainingCandidateArticles / validIds.size();
            rank = (int) (rank * k);
          }
          SRResult result = resultList.get(j);
          unknownIds.remove(result.getId());
          double value = c1 * result.getScore() + c2 * Math.log(rank);
          if (debug) {
            System.err.format(
                "%s %d. %.3f (id=%d), computing %.3f * %.3f + %.3f * (log(%d) = %.3f)\n",
                "m" + i, j, value, result.getId(), c1, result.getScore(), c2, rank, Math.log(rank));
          }
          scoreMap.adjustValue(result.getId(), value);
        }
      }

      // interpolate scores for unknown ids
      double value =
          c1 * mostSimilarInterpolator.getInterpolatedScore(i / 2)
              + c2 * Math.log(mostSimilarInterpolator.getInterpolatedRank(i / 2));
      for (int id : unknownIds.toArray()) {
        scoreMap.adjustValue(id, value);
      }
      i += 2;
    }
    List<SRResult> resultList = new ArrayList<SRResult>();
    for (int id : scoreMap.keys()) {
      resultList.add(new SRResult(id, scoreMap.get(id)));
    }
    Collections.sort(resultList);
    Collections.reverse(resultList);
    int size = maxResults > resultList.size() ? resultList.size() : maxResults;
    SRResultList result = new SRResultList(size);
    for (i = 0; i < size; i++) {
      result.set(i, resultList.get(i));
    }
    return result;
  }
Exemplo n.º 8
0
 public double getLastFrame() {
   return interpolator.getLastFrame();
 }
Exemplo n.º 9
0
 public double getDMulValue(final double alpha) {
   return interpolator.getDMulValue(alpha)[0];
 }
Exemplo n.º 10
0
 public double getValueAtFrame(final double frame) {
   return interpolator.getValueAtFrame(frame)[0];
 }
Exemplo n.º 11
0
  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.drawCircle(
        mLockDimensions.circleX,
        mLockDimensions.circleY,
        mLockDimensions.circleRadius,
        isEnabled()
            ? isLocked() ? mLockedBackgroundPaint : mUnlockedBackgroundPaint
            : mDisabledBackgroundPaint);
    canvas.drawRoundRect(
        mLockDimensions.lockLeftX,
        mLockDimensions.lockTopY,
        mLockDimensions.lockRightX,
        mLockDimensions.lockBottomY,
        mLockDimensions.strokeWidth,
        mLockDimensions.strokeWidth,
        mLockPaint);
    canvas.drawCircle(
        mLockDimensions.keyHoleX,
        mLockDimensions.keyHoleY,
        mLockDimensions.keyHoleRadius,
        mLockPaint);
    canvas.drawLine(
        mLockDimensions.handleSideLeftX,
        mLockDimensions.handleLeftSideBottomY,
        mLockDimensions.handleSideLeftX,
        mLockDimensions.handleSideTopY,
        mLockPaint);
    canvas.drawLine(
        mLockDimensions.handleSideRightX,
        mLockDimensions.handleRightSideBottomY,
        mLockDimensions.handleSideRightX,
        mLockDimensions.handleSideTopY,
        mLockPaint);
    canvas.drawArc(
        mLockDimensions.handleArcLeftX,
        mLockDimensions.handleArcTopY,
        mLockDimensions.handleArcRightX,
        mLockDimensions.handleArcBottomY,
        180f,
        180f,
        false,
        mLockPaint);
    canvas.drawCircle(
        mLockDimensions.circleX, mLockDimensions.circleY, mLockDimensions.tintSize, mShadowPaint);

    if (isDown()) {
      if (mShadowInterpolator == null) {
        mShadowInterpolator = new Interpolator();
      }
      mLockDimensions.tintSize =
          mShadowInterpolator.getInterpolation() * mLockDimensions.circleRadius;
      if (mLockDimensions.tintSize < mLockDimensions.circleRadius) {
        postInvalidateDelayed(FPS);
      }
    } else if (mAnimateLock) {
      if (mAnimationInterpolator == null) {
        mAnimationInterpolator = new Interpolator();
      }
      if (isLocked()) {
        mLockDimensions.animateHandle =
            (1 - mAnimationInterpolator.getInterpolation()) * mLockDimensions.handleRightSideLength;
        mLockDimensions.update();
        if (mLockDimensions.animateHandle > 0) {
          postInvalidateDelayed(FPS);
        } else {
          mAnimateLock = false;
        }
      } else {
        mLockDimensions.animateHandle =
            mAnimationInterpolator.getInterpolation() * mLockDimensions.handleRightSideLength;
        mLockDimensions.update();
        if (mLockDimensions.animateHandle < mLockDimensions.handleRightSideLength * 2.0) {
          postInvalidateDelayed(FPS);
        } else {
          mAnimateLock = false;
        }
      }
    }
  }
  /**
   * Returns the next character in the filtered stream, replacing tokens from the original stream.
   *
   * @return the next character in the resulting stream, or -1 if the end of the resulting stream
   *     has been reached
   * @exception IOException if the underlying stream throws an IOException during reading
   */
  public int read() throws IOException {
    if (replaceIndex != -1 && replaceIndex < replaceData.length()) {
      int ch = replaceData.charAt(replaceIndex++);
      if (replaceIndex >= replaceData.length()) {
        replaceIndex = -1;
      }
      return ch;
    }

    int ch = -1;
    if (previousIndex != -1 && previousIndex < this.endToken.length()) {
      ch = this.endToken.charAt(previousIndex++);
    } else {
      ch = in.read();
    }

    if (ch == this.beginToken.charAt(0)) {
      StringBuffer key = new StringBuffer();

      key.append((char) ch);

      int beginTokenMatchPos = 1;

      do {
        if (previousIndex != -1 && previousIndex < this.endToken.length()) {
          ch = this.endToken.charAt(previousIndex++);
        } else {
          ch = in.read();
        }
        if (ch != -1) {
          key.append((char) ch);

          if ((beginTokenMatchPos < this.beginToken.length())
              && (ch != this.beginToken.charAt(beginTokenMatchPos++))) {
            ch = -1; // not really EOF but to trigger code below
            break;
          }
        } else {
          break;
        }
      } while (ch != this.endToken.charAt(0));

      // now test endToken
      if (ch != -1 && this.endToken.length() > 1) {
        int endTokenMatchPos = 1;

        do {
          if (previousIndex != -1 && previousIndex < this.endToken.length()) {
            ch = this.endToken.charAt(previousIndex++);
          } else {
            ch = in.read();
          }

          if (ch != -1) {
            key.append((char) ch);

            if (ch != this.endToken.charAt(endTokenMatchPos++)) {
              ch = -1; // not really EOF but to trigger code below
              break;
            }

          } else {
            break;
          }
        } while (endTokenMatchPos < this.endToken.length());
      }

      // There is nothing left to read so we have the situation where the begin/end token
      // are in fact the same and as there is nothing left to read we have got ourselves
      // end of a token boundary so let it pass through.
      if (ch == -1) {
        replaceData = key.toString();
        replaceIndex = 1;
        return replaceData.charAt(0);
      }

      String value;
      try {
        value = interpolator.interpolate(key.toString(), "");
      } catch (InterpolationException e) {
        IllegalArgumentException error = new IllegalArgumentException(e.getMessage());
        error.initCause(e);

        throw error;
      }

      if (value != null) {
        if (value.length() != 0) {
          replaceData = value;
          replaceIndex = 0;
        }
        return read();
      } else {
        previousIndex = 0;
        replaceData = key.substring(0, key.length() - this.endToken.length());
        replaceIndex = 0;
        return this.beginToken.charAt(0);
      }
    }

    return ch;
  }
Exemplo n.º 13
0
  /** Overrides the paintComponent method to paint the horses images in their proper position. */
  @Override
  public synchronized void paintComponent(Graphics g) {
    // Draw the six images of the horses
    for (int i = 0; i < horsesPoint.size(); i++) {
      Image image = horsesImage.get(i);
      Interpolator<Object> interpolator = horsesPoint.get(i);
      g.drawImage(image, interpolator.getXPosition(), interpolator.getYPosition(), 25, 25, null);
    }

    // Draw the images of the bets
    for (Interpolator<BetContainer> b : betsPoint) {
      Image image = b.getObject().getBet().getBetToken().getImage();
      Interpolator<BetContainer> interpolator = b;
      g.drawImage(image, interpolator.getXPosition(), interpolator.getYPosition(), 40, 40, null);
      String danari = String.format("%d$", b.getObject().getBet().getValue());

      try {
        g.setColor(Color.BLACK);
        g.setFont(font.deriveFont(15F));
      } catch (NullPointerException e) {
        // Font not loaded
      }

      g.drawString(
          b.getObject().getPlayerName(),
          interpolator.getXPosition(),
          interpolator.getYPosition() + 51);
      g.drawString(danari, interpolator.getXPosition(), interpolator.getYPosition() + 65);
    }
    super.paintComponent(g);
  }