Example #1
0
 public Object getData(final WModelIndex index, int role) {
   if (role != ItemDataRole.DisplayRole) {
     return super.getData(index, role);
   }
   double delta_y = (this.yEnd_ - this.yStart_) / (this.getColumnCount() - 2);
   if (index.getRow() == 0) {
     if (index.getColumn() == 0) {
       return 0.0;
     }
     return this.yStart_ + (index.getColumn() - 1) * delta_y;
   }
   double delta_x = (this.xEnd_ - this.xStart_) / (this.getRowCount() - 2);
   if (index.getColumn() == 0) {
     if (index.getRow() == 0) {
       return 0.0;
     }
     return this.xStart_ + (index.getRow() - 1) * delta_x;
   }
   double x;
   double y;
   y = this.yStart_ + (index.getColumn() - 1) * delta_y;
   x = this.xStart_ + (index.getRow() - 1) * delta_x;
   return 4
       * Math.sin(Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)))
       / Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
 }
Example #2
0
  private double rec(int idx, double rem) {
    if (idx >= 3) {
      return rem / walkSpeed;
    }

    double ans = INF;
    double left = 0;
    double right = rem;

    for (int iter = 0; iter < 100; iter++) {
      double m1 = left + (right - left) / 3.0;
      double m2 = right - (right - left) / 3.0;

      double a1 = rec(idx + 1, rem - m1) + Math.sqrt(sq(a[idx][0]) + sq(m1)) / a[idx][1];
      ans = Math.min(ans, a1);

      double a2 = rec(idx + 1, rem - m2) + Math.sqrt(sq(a[idx][0]) + sq(m2)) / a[idx][1];
      ans = Math.min(ans, a2);

      if (a1 < a2) {
        right = m2;
      } else {
        left = m1;
      }
    }

    return ans;
  }
Example #3
0
 public static double pt(double t, double df) {
   // ALGORITHM AS 3  APPL. STATIST. (1968) VOL.17, P.189
   // Computes P(T<t)
   double a, b, idf, im2, ioe, s, c, ks, fk, k;
   double g1 = 0.3183098862; // =1/pi;
   if (df < 1) throw new IllegalArgumentException("Illegal argument df for pt(t,df).");
   idf = df;
   a = t / Math.sqrt(idf);
   b = idf / (idf + t * t);
   im2 = df - 2;
   ioe = idf % 2;
   s = 1;
   c = 1;
   idf = 1;
   ks = 2 + ioe;
   fk = ks;
   if (im2 >= 2) {
     for (k = ks; k <= im2; k += 2) {
       c = c * b * (fk - 1) / fk;
       s += c;
       if (s != idf) {
         idf = s;
         fk += 2;
       }
     }
   }
   if (ioe != 1) return 0.5 + 0.5 * a * Math.sqrt(b) * s;
   if (df == 1) s = 0;
   return 0.5 + (a * b * s + Math.atan(a)) * g1;
 }
    public Double eval(Double lmbda) {
      double c1 = 0.0;
      double c3 = -1.0 / (double) Math.sqrt(2.0 * variance);
      double sum = 0.0;

      double cpart = -0.5 * Math.log(Math.sqrt(2.0 * Math.PI * variance));

      for (int i = 0; i < data.size(); i++) {
        for (int k = 0; k < channels.length; k++) {
          c1 += cpart;
          double pi = 0.0;

          for (Integer t : transcripts.keySet()) {
            if (transcripts.get(t).contains(i)) {
              double dit = delta(i, t);
              double gammai = gammas[t][k];
              double pit = gammai * Math.exp(-lmbda * dit);
              pi += pit;
            }
          }

          double zi = Math.log(pi);
          double err = data.values(i)[channels[k]] - zi;

          sum += (err * err);
        }
      }

      return c1 + c3 * sum;
    }
    public Double eval(Double gamma) {
      double c1 = 0.0;
      double c3 = -1.0 / (double) Math.sqrt(2.0 * variance);
      double sum = 0.0;

      double cpart = -0.5 * Math.log(Math.sqrt(2.0 * Math.PI * variance));

      for (Integer i : transcripts.get(gammat)) {
        c1 += cpart;
        double pi = 0.0;

        for (int t = 0; t < fiveprime.length; t++) {
          if (transcripts.get(t).contains(i)) {
            double gammai = gammat == t ? gamma : gammas[t][gammak];
            double dit = delta(i, t);

            double pit = gammai * Math.exp(-lambda * dit);
            pi += pit;
          }
        }

        double zi = Math.log(pi);
        double err = data.values(i)[channels[gammak]] - zi;

        sum += (err * err);
      }

      return c1 + c3 * sum;
    }
Example #6
0
  private void spawnRandomers() {
    for (int i = 0; i < randomN; i++) {
      float x = (float) Math.random() * width;
      float y = (float) Math.random() * height;
      float r =
          (float)
              Math.sqrt(
                  Math.pow(((Player) players.get(0)).getX() - x, 2)
                      + Math.pow(((Player) players.get(0)).getY() - x, 2));

      while (r < distanceLimit) {
        x = (float) Math.random() * width;
        y = (float) Math.random() * height;
        r =
            (float)
                Math.sqrt(
                    Math.pow(((Player) players.get(0)).getX() - x, 2)
                        + Math.pow(((Player) players.get(0)).getY() - y, 2));
      }

      enemies.add(new EnemyTypes.Random(x, y, 0.5f, borders));
    }

    spawnRandomersB = false;
  }
Example #7
0
 private void getintbright() {
   weights = new float[ncurves][xpts][ypts];
   for (int i = 0; i < ncurves; i++) {
     nmeas[i] = 0;
     for (int j = 0; j < xpts; j++) {
       for (int k = 0; k < ypts; k++) {
         nmeas[i] += (int) pch[i][j][k];
       }
     }
     double tempavg = 0.0;
     double tempavg2 = 0.0;
     double temp2avg = 0.0;
     double temp2avg2 = 0.0;
     double tempccavg = 0.0;
     for (int j = 0; j < xpts; j++) {
       for (int k = 0; k < ypts; k++) {
         double normed = (double) pch[i][j][k] / (double) nmeas[i];
         if (pch[i][j][k] > 0.0f) {
           weights[i][j][k] = (float) ((double) nmeas[i] / (normed * (1.0f - normed)));
         } else {
           weights[i][j][k] = 1.0f;
         }
         tempavg += normed * (double) j;
         tempavg2 += normed * (double) j * (double) j;
         temp2avg += normed * (double) k;
         temp2avg2 += normed * (double) k * (double) k;
         tempccavg += normed * (double) k * (double) j;
       }
     }
     tempccavg -= tempavg * temp2avg;
     brightcc[i] = tempccavg / Math.sqrt(tempavg * temp2avg);
     tempavg2 -= tempavg * tempavg;
     tempavg2 /= tempavg;
     bright1[i] = (tempavg2 - 1.0);
     temp2avg2 -= temp2avg * temp2avg;
     temp2avg2 /= temp2avg;
     bright2[i] = (temp2avg2 - 1.0);
     intensity1[i] = tempavg;
     intensity2[i] = temp2avg;
     if (psfflag == 0) {
       bright1[i] /= 0.3536;
       bright2[i] /= 0.3536;
       brightcc[i] /= 0.3536;
     } else {
       if (psfflag == 1) {
         bright1[i] /= 0.078;
         bright2[i] /= 0.078;
         brightcc[i] /= 0.078;
       } else {
         bright1[i] /= 0.5;
         bright2[i] /= 0.5;
         brightcc[i] /= 0.5;
       }
     }
     number1[i] = intensity1[i] / bright1[i];
     number2[i] = intensity2[i] / bright2[i];
     brightmincc[i] = (bright1[i] * beta) * Math.sqrt(intensity1[i] / intensity2[i]);
   }
 }
Example #8
0
  public static double qt(double p, double ndf, boolean lower_tail) {
    // Algorithm 396: Student's t-quantiles by
    // G.W. Hill CACM 13(10), 619-620, October 1970
    if (p <= 0 || p >= 1 || ndf < 1)
      throw new IllegalArgumentException("Invalid p or df in call to qt(double,double,boolean).");
    double eps = 1e-12;
    double M_PI_2 = 1.570796326794896619231321691640; // pi/2
    boolean neg;
    double P, q, prob, a, b, c, d, y, x;
    if ((lower_tail && p > 0.5) || (!lower_tail && p < 0.5)) {
      neg = false;
      P = 2 * (lower_tail ? (1 - p) : p);
    } else {
      neg = true;
      P = 2 * (lower_tail ? p : (1 - p));
    }

    if (Math.abs(ndf - 2) < eps) {
        /* df ~= 2 */
      q = Math.sqrt(2 / (P * (2 - P)) - 2);
    } else if (ndf < 1 + eps) {
        /* df ~= 1 */
      prob = P * M_PI_2;
      q = Math.cos(prob) / Math.sin(prob);
    } else {
        /*-- usual case;  including, e.g.,  df = 1.1 */
      a = 1 / (ndf - 0.5);
      b = 48 / (a * a);
      c = ((20700 * a / b - 98) * a - 16) * a + 96.36;
      d = ((94.5 / (b + c) - 3) / b + 1) * Math.sqrt(a * M_PI_2) * ndf;
      y = Math.pow(d * P, 2 / ndf);
      if (y > 0.05 + a) {
        /* Asymptotic inverse expansion about normal */
        x = qnorm(0.5 * P, false);
        y = x * x;
        if (ndf < 5) c += 0.3 * (ndf - 4.5) * (x + 0.6);
        c = (((0.05 * d * x - 5) * x - 7) * x - 2) * x + b + c;
        y = (((((0.4 * y + 6.3) * y + 36) * y + 94.5) / c - y - 3) / b + 1) * x;
        y = a * y * y;
        if (y > 0.002) /* FIXME: This cutoff is machine-precision dependent*/ y = Math.exp(y) - 1;
        else {
            /* Taylor of    e^y -1 : */
          y = (0.5 * y + 1) * y;
        }
      } else {
        y =
            ((1 / (((ndf + 6) / (ndf * y) - 0.089 * d - 0.822) * (ndf + 2) * 3) + 0.5 / (ndf + 4))
                            * y
                        - 1)
                    * (ndf + 1)
                    / (ndf + 2)
                + 1 / y;
      }
      q = Math.sqrt(ndf * y);
    }
    if (neg) q = -q;
    return q;
  }
Example #9
0
  /**
   * Calculates word order similarity between the sentences, with weighted words
   *
   * @param s1 sentence 1
   * @param s2 sentence 2
   * @param weights1 of sentence 1
   * @param weights2 of sentence 2
   * @return Word order similarity value
   */
  public double orderSimilarity(
      List<double[]> s1,
      List<double[]> s2,
      List<double[]> weights1,
      List<double[]> weights2,
      String sent2,
      String unique) {
    double[] s1Dist = s1.get(0);
    double[] s1Friend = s1.get(1);
    double[] s2Dist = s2.get(0);
    double[] s2Friend = s2.get(1);
    double[] r1 = new double[s1Dist.length];
    double[] r2 = new double[s2Dist.length];
    String[] sent = sent2.split(" ");
    String[] un = unique.split(" ");
    String word;

    // Specifies word order vectors for either sentence.
    // Threshold specifies that words can be seen as the same if similar enough
    // If same word not found in unique sentence, the order value is 0
    for (int i = 0; i < r1.length; i++) {
      if (s1Dist[i] == 1.0) {
        r1[i] = i + 1;
      } else if (s1Dist[i] >= threshold) {
        r1[i] = s1Friend[i] + 1;

      } else {
        r1[i] = 0;
      }
    }
    for (int i = 0; i < r2.length; i++) {
      if (s2Dist[i] == 1.0) {
        word = un[i];
        r2[i] = Arrays.asList(sent).indexOf(word) + 1;
      } else if (s2Dist[i] >= threshold) {
        r2[i] = s2Friend[i] + 1;

      } else {
        r2[i] = 0.0;
      }
    }
    double numerator = 0.0;
    double denominator = 0.0;
    // Calculate order similarity while avoiding division by 0
    for (int i = 0; i < r1.length; i++) {
      numerator = numerator + Math.pow((r1[i] - r2[i]) * weights1.get(0)[i], 2);
      denominator = denominator + Math.pow((r1[i] + r2[i]) * weights1.get(0)[i], 2);
    }
    numerator = Math.sqrt(numerator);
    denominator = Math.sqrt(denominator);
    if (denominator == 0.0) {
      numerator = 1;
      denominator = 1;
    }

    return numerator / denominator;
  }
Example #10
0
  public static void main(String[] args) throws IOException {
    // Use BufferedReader rather than RandomAccessFile; it's much faster
    BufferedReader f = new BufferedReader(new FileReader("dinner.in"));
    // input file name goes above
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("dinner.out")));
    // Use StringTokenizer vs. readLine/split -- lots faster
    StringTokenizer st = new StringTokenizer(f.readLine());
    // Get line, break into tokens
    int i1 = Integer.parseInt(st.nextToken()); // first integer
    int i2 = Integer.parseInt(st.nextToken()); // second integer
    int[] abscissas = new int[i1];
    int[] ordinates = new int[i1];
    for (int i = 0; i < i1; i++) {
      st = new StringTokenizer(f.readLine());
      if (st.hasMoreTokens()) {
        abscissas[i] = Integer.parseInt(st.nextToken());
        ordinates[i] = Integer.parseInt(st.nextToken());
      }
    }
    for (int i = 0; i < i2; i++) {
      st = new StringTokenizer(f.readLine());
      if (st.hasMoreTokens()) {
        int temp1 = Integer.parseInt(st.nextToken());
        int temp2 = Integer.parseInt(st.nextToken());
        double minDist = Integer.MAX_VALUE;
        int mark = 0;
        for (int x = 0; x < i1; x++) {
          if (minDist
              > Math.sqrt(
                  (abscissas[x] - temp1) * (abscissas[x] - temp1)
                      + (ordinates[x] - temp2) * (ordinates[x] - temp2))) {
            minDist =
                Math.sqrt(
                    (abscissas[x] - temp1) * (abscissas[x] - temp1)
                        + (ordinates[x] - temp2) * (ordinates[x] - temp2));
            mark = x;
          }
        }
        abscissas[mark] = 1000001;
        ordinates[mark] = 1000001;
      }
    }

    for (int i = 0; i < i1; i++) {
      if (abscissas[i] != 1000001) {

        System.out.println(i + 1);
      }
    }
    out.close(); // close the output file
    System.exit(0); // don't omit this!
  }
Example #11
0
 private void write_xvg_mean_sd(
     float fc, int r, float[][] arr1, float[][] arr2, float[][] box, String output) {
   // The mean and standard deviation for this method was tested and validated with calculations in
   // R.
   int nOxygen = r / 3;
   float[][] del = new float[nOxygen][3];
   float stdvX, stdvY, stdvZ;
   stdvX = stdvY = stdvZ = 0;
   int i, j;
   for (i = 0; i < nOxygen; i++) {
     del[i][0] = arr2[i * 3][0] - arr1[i * 3][0];
     del[i][1] = arr2[i * 3][1] - arr1[i * 3][1];
     del[i][2] = arr2[i * 3][2] - arr1[i * 3][2];
     if (output.equals("crd")) {
       for (j = 0; j < 3; j++) {
         if ((del[i][j] < 0) && (del[i][j] < (-1 * box[j][j] / 2))) {
           del[i][j] = del[i][j] + box[j][j];
         } else if ((del[i][j] > 0) && (del[i][j] > (box[j][j] / 2))) {
           del[i][j] = del[i][j] - box[j][j];
         }
       }
     }
     sumX = sumX + (del[i][0]);
     sumY = sumY + (del[i][1]);
     sumZ = sumZ + (del[i][2]);
   }
   sumX /= nOxygen;
   sumY /= nOxygen;
   sumZ /= nOxygen;
   for (i = 0; i < nOxygen; i++) {
     stdvX = stdvX + ((del[i][0] - sumX) * (del[i][0] - sumX));
     stdvY = stdvY + ((del[i][1] - sumY) * (del[i][1] - sumY));
     stdvZ = stdvZ + ((del[i][2] - sumZ) * (del[i][2] - sumZ));
   }
   stdvX = (float) Math.sqrt(stdvX / (nOxygen - 1));
   stdvY = (float) Math.sqrt(stdvY / (nOxygen - 1));
   stdvZ = (float) Math.sqrt(stdvZ / (nOxygen - 1));
   if (output.equals("crd")) {
     doutC.println(
         fc + "\t" + sumX + "\t" + stdvX + "\t" + sumY + "\t" + stdvY + "\t" + sumZ + "\t"
             + stdvZ);
   } else if (output.equals("vel")) {
     doutV.println(
         fc + "\t" + sumX + "\t" + stdvX + "\t" + sumY + "\t" + stdvY + "\t" + sumZ + "\t"
             + stdvZ);
   } else if (output.equals("frc")) {
     doutF.println(
         fc + "\t" + sumX + "\t" + stdvX + "\t" + sumY + "\t" + stdvY + "\t" + sumZ + "\t"
             + stdvZ);
   }
 }
Example #12
0
 static { // data[] is a bitmap image of the ball of radius R
   data = new byte[R * 2 * R * 2];
   for (int Y = -R; Y < R; Y++) {
     int x0 = (int) (Math.sqrt(R * R - Y * Y) + 0.5);
     for (int X = -x0; X < x0; X++) {
       // sqrt(x^2 + y^2) gives distance from the spot light
       int x = X + hx, y = Y + hy;
       int r = (int) (Math.sqrt(x * x + y * y) + 0.5);
       // set the maximal intensity to the maximal distance
       // (in pixels) from the spot light
       if (r > maxr) maxr = r;
       data[(Y + R) * (R * 2) + (X + R)] = (r <= 0) ? 1 : (byte) r;
     }
   }
 }
Example #13
0
  // For now the final output is unusable.  The associated quantization step
  // needs some tweaking.  If you get this part working, please let me know.
  public double[][] forwardDCTExtreme(float[][] input) {
    double[][] output = new double[N][N];
    double tmp0;
    double tmp1;
    double tmp2;
    double tmp3;
    double tmp4;
    double tmp5;
    double tmp6;
    double tmp7;
    double tmp10;
    double tmp11;
    double tmp12;
    double tmp13;
    double z1;
    double z2;
    double z3;
    double z4;
    double z5;
    double z11;
    double z13;
    int i;
    int j;
    int v;
    int u;
    int x;
    int y;

    for (v = 0; v < 8; v++) {
      for (u = 0; u < 8; u++) {
        for (x = 0; x < 8; x++) {
          for (y = 0; y < 8; y++) {
            output[v][u] +=
                (((double) input[x][y])
                    * Math.cos(((double) ((2 * x) + 1) * (double) u * Math.PI) / (double) 16)
                    * Math.cos(((double) ((2 * y) + 1) * (double) v * Math.PI) / (double) 16));
          }
        }

        output[v][u] *=
            ((double) (0.25)
                * ((u == 0) ? ((double) 1.0 / Math.sqrt(2)) : (double) 1.0)
                * ((v == 0) ? ((double) 1.0 / Math.sqrt(2)) : (double) 1.0));
      }
    }

    return output;
  }
Example #14
0
  public void calcSigma() {

    Double summation = new Double(0);

    // Take the sum of gdplist and divide by n

    for (Double x1 : gdplist) summation += x1;

    average = summation / gdplist.size();

    // Now we have the mean

    // Take the difference of the GDP by year and the mean
    // Sum all of the squares of the differences
    // Take the square root of the sum == std deviation

    summation = new Double(0);

    for (Double x1 : gdplist) { // look at each year GDP
      Double x2 = x1 - average; // subtract the average from that year GDP

      summation += (x2 * x2); // square the result and add it to a total sum
    }

    summation = summation / gdplist.size();

    stdev = Math.sqrt(summation);
  }
Example #15
0
 private static void notifyTerminated(long time, long time2) {
   synchronized (terminatedLock) {
     totalTime += time;
     totalTime2 += time2;
     terminatedCnt++;
     if (terminatedCnt == nCouples) {
       // All couples have terminated. Compute the average round-trip time
       long n = nCouples * ((long) nIterations);
       if (measure == BITRATE_MEASURE) {
         double totBytes = n * ((double) content.length);
         double averageBitrate = totBytes / totalTime;
         System.out.println(
             "----------------------------------\nTest completed successufully.\nAverage bitrate (Kbyte/s) = "
                 + averageBitrate
                 + "\n----------------------------------");
       } else if (measure == RTT_MEASURE) {
         long averageRoundTripTime = totalTime / n;
         double avg = (double) averageRoundTripTime;
         double x = totalTime2 + n * avg * avg - 2 * avg * totalTime;
         double standardDeviation = Math.sqrt(x / n);
         System.out.println(
             "----------------------------------\nTest completed successufully.\nAverage round trip time = "
                 + averageRoundTripTime
                 + " ms\nStandard deviation = "
                 + standardDeviation
                 + "\n----------------------------------");
       }
       System.exit(0);
     }
   }
 }
 /** Computes and returns the distance between two entities */
 public int getDistance(WorldEntity e) {
   Point wp = e.getPosition();
   Point mep = getPosition();
   int dx = wp.x - mep.x;
   int dy = wp.y - mep.y;
   return ((int) Math.round(Math.sqrt(dx * dx + dy * dy)));
 }
Example #17
0
  public void calcDimsAndStartPts(LinkedList llist, draw d) {
    /*  Determines the following variables Lenx, Leny, Startx, Starty,
    TitleStarty   */
    // Task: Calculate the length and height of a node and its starting point.
    //   It also computes the y-coordinate of the title

    double TitleToSSGap, MinGt, MaxGt, Diam, MinTitlex, MaxTitlex;
    int NumNodes, NumLines;
    super.calcDimsAndStartPts(llist, d);
    // With circular nodes, not adding Textheight works better to finetune the circle size
    Lenx = Maxstringlength - .02;
    Leny = ((linespernode + 1) * Textheight) + ((linespernode - 1) * (0.5 * Textheight));
    TDx = (Lenx + Leny) / 5.0; // Height is a third of their average *)
    TDy = TDx / Math.sqrt(3);
    TitleToSSGap = 2 * Titleheight;
    NumLines = title.size();
    Startx = 0.0;
    Starty =
        Topy
            - IconHeight
            - IconToTitleGap
            - (NumLines * Titleheight)
            - ((NumLines - 1) * (0.5 * Titleheight))
            - TitleToSSGap
            - (Lenx / 2.0)
            - .15;
    TitleStarty = (Topy - IconHeight - IconToTitleGap - Titleheight) + .05;
  }
Example #18
0
 private double doubleVectorAbs(Vector<Vector<Double>> doubleVector) {
   double totalX = 0;
   for (Vector<Double> vector : doubleVector) {
     totalX += Math.pow(vectorAbs(vector), 2);
   }
   return Math.sqrt(totalX);
 }
Example #19
0
 static void solve() throws IOException {
   int testCount = nextInt();
   for (int curTest = 0; curTest < testCount; curTest++) {
     int n = nextInt();
     int m = nextInt();
     int k = nextInt();
     int[] xCar = new int[n];
     int[] yCar = new int[n];
     for (int i = 0; i < n; i++) {
       xCar[i] = nextInt();
       yCar[i] = nextInt();
     }
     int[] xGarage = new int[m];
     int[] yGarage = new int[m];
     for (int i = 0; i < m; i++) {
       xGarage[i] = nextInt();
       yGarage[i] = nextInt();
     }
     DinicGraph g = new DinicGraph(n + m + 2);
     int source = n + m;
     int target = n + m + 1;
     int[][] d = new int[n][m];
     for (int i = 0; i < n; i++) {
       g.addEdge(source, i, 1);
     }
     for (int i = 0; i < m; i++) {
       g.addEdge(n + i, target, k);
     }
     DinicGraph.Edge[][] edges = new DinicGraph.Edge[n][m];
     for (int i = 0; i < n; i++) {
       for (int j = 0; j < m; j++) {
         edges[i][j] = g.addEdge(i, j + n, 1);
         int dx = xCar[i] - xGarage[j];
         int dy = yCar[i] - yGarage[j];
         d[i][j] = dx * dx + dy * dy;
       }
     }
     int l = -1;
     int r = 1000000000;
     while (l < r - 1) {
       int mid = l + r >> 1;
       g.clear();
       for (int i = 0; i < n; i++) {
         for (int j = 0; j < m; j++) {
           if (d[i][j] <= mid) {
             edges[i][j].cap = 1;
           } else {
             edges[i][j].cap = 0;
           }
         }
       }
       if (g.getMaxFlow(source, target) == n) {
         r = mid;
       } else {
         l = mid;
       }
     }
     out.println(Math.sqrt(r));
   }
 }
  @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);
  }
    public Double eval(Double gamma) {
      double c = 1.0 / (double) Math.sqrt(variance);
      double sum = 0.0;
      for (Integer i : transcripts.get(gammat)) {
        double pi = 0.0;

        for (int t = 0; t < fiveprime.length; t++) {
          if (transcripts.get(t).contains(i)) {
            double gammai = gammat == t ? gamma : gammas[t][gammak];
            double dit = delta(i, t);

            double pit = gammai * Math.exp(-lambda * dit);
            pi += pit;
          }
        }

        double zi = Math.log(pi);
        double err = data.values(i)[channels[gammak]] - zi;
        double ratio = (Math.exp(-lambda * delta(i, gammat))) / pi;
        double termi = (err * ratio);

        sum += termi;
      }

      return c * sum;
    }
    public Double eval(Double lmbda) {
      double c = 1.0 / (double) Math.sqrt(variance);
      double sum = 0.0;

      for (int i = 0; i < data.size(); i++) {
        for (int k = 0; k < channels.length; k++) {
          double pi = 0.0;
          double pdi = 0.0;

          for (Integer t : transcripts.keySet()) {
            if (transcripts.get(t).contains(i)) {
              double gammai = gammas[t][k];
              double dit = delta(i, t);

              double falloff = Math.exp(-lmbda * dit);
              double pit = gammai * falloff;
              double pdit = pit * dit;

              pi += pit;
              pdi += pdit;
            }
          }

          double zi = Math.log(pi);
          double err = data.values(i)[channels[k]] - zi;
          double ratio = pdi / pi;
          double termi = (err * ratio);

          sum += termi;
        }
      }

      return c * sum;
    }
Example #23
0
 /*
  *	@param	a			Quell-Wellenform
  *	@param	env			Ziel-RMS
  *	@param	average		Laenge der Samples in a, aus denen jeweils ein RMS berechnet wird
  *						(RMS = sqrt( energy/average ))
  *	@param	length		Zahl der generierten RMS (in env)
  *	@param	lastEnergy	Rueckgabewert aus dem letzten Aufruf dieser Routine
  *						(richtige Initialisierung siehe process(): summe der quadrate der prebuffered samples)
  *	@return				neuer Energiewert, der beim naechsten Aufruf als lastEnergy uebergeben werden muss
  */
 protected double calcEnv(float[] a, float[] env, int average, int length, double lastEnergy) {
   for (int i = 0, j = average; i < length; i++, j++) { //   zu alten leistungswert "vergessen" und
     lastEnergy = lastEnergy - a[i] * a[i] + a[j] * a[j]; // neuen addieren
     env[i] = (float) Math.sqrt(lastEnergy / average);
   }
   return lastEnergy;
 }
Example #24
0
 /**
  * Apply this operator (function) to the supplied argument
  *
  * @param value the argument
  * @return the result
  */
 protected double applyFunction(double value) {
   switch (m_operator) {
     case 'l':
       return Math.log(value);
     case 'b':
       return Math.abs(value);
     case 'c':
       return Math.cos(value);
     case 'e':
       return Math.exp(value);
     case 's':
       return Math.sqrt(value);
     case 'f':
       return Math.floor(value);
     case 'h':
       return Math.ceil(value);
     case 'r':
       return Math.rint(value);
     case 't':
       return Math.tan(value);
     case 'n':
       return Math.sin(value);
   }
   return Double.NaN;
 }
 double oblicz_wage(int x1, int y1, int x2, int y2) {
   double x = (double) Math.pow(Math.abs((x1 - x2)), 2);
   double y = (double) Math.pow(Math.abs((y1 - y2)), 2);
   double wynik = Math.sqrt(x + y) * 1000;
   wynik = Math.round(wynik);
   return (wynik / 1000);
 }
Example #26
0
 // Returns the distance between two planets, rounded up to the next highest
 // integer. This is the number of discrete time steps it takes to get
 // between the two planets.
 public int Distance(int sourcePlanet, int destinationPlanet) {
   Planet source = planets.get(sourcePlanet);
   Planet destination = planets.get(destinationPlanet);
   double dx = source.X() - destination.X();
   double dy = source.Y() - destination.Y();
   return (int) Math.ceil(Math.sqrt(dx * dx + dy * dy));
 }
Example #27
0
 public static boolean isPrime(int n) {
   int limit = (int) Math.sqrt(n) + 1;
   for (int i = 3; i < limit; i += 2) {
     if (n % i == 0) return false;
   }
   return true;
 }
Example #28
0
  /**
   * This private method computes the distance between an example in the dataset and a cluster
   * centroid. The distance is measure as the square root of the sum of the squares of the
   * differences between the example and the cetroid for all the dimensions.
   *
   * @param a The example in the dataset
   * @param b The culster centroid
   * @return The distance between a and b as a double precision float value.
   */
  private static double distance(double a[], double b[]) {

    // Euclid distance between two patterns
    double d = 0;
    for (int i = 0; i < a.length; i++) d += (a[i] - b[i]) * (a[i] - b[i]);
    return (double) Math.sqrt(d);
  }
Example #29
0
 public static ClosestPair findShortest(double[][] x) {
   if (x.length <= 2) {
     double ax = x[0][0];
     double ay = x[0][1];
     double bx = x[1][0];
     double by = x[1][1];
     ClosestPair p = new ClosestPair();
     p.a = "" + ax + " " + ay;
     p.b = "" + bx + " " + by;
     p.dist = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2));
     return p;
   } else {
     ClosestPair p = new ClosestPair();
     double ax = x[0][0];
     double ay = x[0][1];
     double bx = x[1][0];
     double by = x[1][1];
     double cx = x[2][0];
     double cy = x[2][1];
     double dab = (double) Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2));
     double dbc = (double) Math.sqrt(Math.pow(bx - cx, 2) + Math.pow(by - cy, 2));
     double dac = (double) Math.sqrt(Math.pow(ax - cx, 2) + Math.pow(ay - cy, 2));
     if (dab <= dbc)
       if (dab <= dac) {
         p.a = "" + ax + " " + ay;
         p.b = "" + bx + " " + by;
         p.dist = dab;
         return p;
       } else {
         p.a = "" + ax + " " + ay;
         p.b = "" + cx + " " + cy;
         p.dist = dac;
         return p;
       }
     else if (dbc <= dac) {
       p.a = "" + bx + " " + by;
       p.b = "" + cx + " " + cy;
       p.dist = dbc;
       return p;
     } else {
       p.a = "" + ax + " " + ay;
       p.b = "" + cx + " " + cy;
       p.dist = dac;
       return p;
     }
   }
 }
 public static boolean isPrime(long n) throws Exception {
   if (n == 1) return false;
   if (n == 2 || n == 3) return true;
   for (int i = 2; i <= Math.sqrt(n); i++) {
     if (n % i == 0) return false;
   }
   return true;
 }