/** Start the background thread. */
  public void start() {
    // create a random list of cities

    cities = new City[TravelingSalesman.CITY_COUNT];
    for (int i = 0; i < TravelingSalesman.CITY_COUNT; i++) {
      cities[i] =
          new City(
              (int) (Math.random() * (getBounds().width - 10)),
              (int) (Math.random() * (getBounds().height - 60)));
    }

    // create the initial chromosomes

    chromosomes = new Chromosome[TravelingSalesman.POPULATION_SIZE];
    for (int i = 0; i < TravelingSalesman.POPULATION_SIZE; i++) {
      chromosomes[i] = new Chromosome(cities);
      chromosomes[i].setCut(cutLength);
      chromosomes[i].setMutation(TravelingSalesman.MUTATION_PERCENT);
    }
    Chromosome.sortChromosomes(chromosomes, TravelingSalesman.POPULATION_SIZE);

    // start up the background thread
    started = true;
    map.update(map.getGraphics());

    generation = 0;

    if (worker != null) worker = null;
    worker = new Thread(this);
    // worker.setPriority(Thread.MIN_PRIORITY);
    worker.start();
  }
Esempio n. 2
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    TreeMap<Long, Long> tmap = new TreeMap<>();
    long res = 0;
    while (t-- > 0) {
      res = 0;
      int n = in.nextInt();
      long m = in.nextLong();
      tmap.clear();
      long[] arr = new long[n];
      res = in.nextLong();
      arr[0] = res % m;
      res = Long.MIN_VALUE;
      tmap.put(arr[0], arr[0]);
      for (int i = 1; i < arr.length; i++) {
        arr[i] = in.nextLong();
        arr[i] %= m;
        arr[i] += arr[i - 1];
        arr[i] %= m;

        if (tmap.higherEntry(arr[i]) == null) {
          res = Math.max(res, arr[i]);
          tmap.put(arr[i], arr[i]);
          continue;
        }
        long val = tmap.higherEntry(arr[i]).getValue();
        res = Math.max(res, (arr[i] - val + m) % m);
        tmap.put(arr[i], arr[i]);
      }

      System.out.println(res);
    }
  }
Esempio n. 3
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]);
   }
 }
 /**
  * Formats the specified value and enters it in the text field.
  *
  * @param value the value to be entered
  */
 public void setValue(double value) {
   if (!isVisible()) return;
   if (minValue != null) value = Math.max(value, minValue.doubleValue());
   if (maxValue != null) value = Math.min(value, maxValue.doubleValue());
   setFormatFor(value);
   setText(format.format(value));
   prevValue = value;
 }
Esempio n. 5
0
 public static Color gradientColor(double value) {
   if (value < 0.0) return Color.gray;
   if (value > 1.0) value = 1.0;
   int red = Math.min(255, (int) (512.0 - (value * 512.0)));
   int green = Math.min(255, (int) (value * 512.0));
   int blue = 0;
   return new Color(red, green, blue);
 }
Esempio n. 6
0
 public void run() {
   while (running) {
     if (!paused) {
       if (mode == 0) {
         for (double i = 0; i < 3.14f; i = i + 0.1f) {
           for (int j = 0; j < 12; j++) {
             double osc = Math.sin(i) * 127;
             int value = (int) osc;
             MIDILight(j, value);
           }
           delay(30);
         }
         for (double i = 3.14f; i >= 0; i = i - 0.1f) {
           for (int j = 0; j < 12; j++) {
             double osc = Math.sin(i) * 127;
             int value = (int) osc;
             MIDILight(j, value);
           }
           delay(30);
         }
       } else if (mode == 1) {
         for (int j = 0; j < 12; j++) {
           MIDILight(j, 127);
         }
         mode = 1000;
       } else if (mode == 2) {
         for (int j = 0; j < 12; j++) {
           MIDILight(j, 0);
         }
         mode = 1000;
       } else if (mode == 3) {
         int controller = (int) random(12);
         int randomValue = (int) random(127);
         MIDILight(controller, randomValue);
         delay(30);
       } else if (mode == 4) {
         for (int i = 0; i < 64; i++) {
           for (int j = 0; j < 12; j++) {
             MIDILight(j, i * 2);
           }
           delay(20);
         }
         for (int i = 63; i >= 0; i--) {
           for (int j = 0; j < 12; j++) {
             MIDILight(j, i * 2);
           }
           delay(20);
         }
       } else {
         delay(10);
         // FIX THIS. WITHOUT THIS THE CPU USE GOES THROUGH THE ROOF. NEED A WAY
         // TO SLEEP THIS THREAD WHEN IT'S NOT IN USE.
       }
     }
   }
   System.out.println(id + " thread is done!");
 }
Esempio n. 7
0
 private void setHoverLocation(
     org.eclipse.swt.widgets.Shell shell, org.eclipse.swt.graphics.Point position) {
   org.eclipse.swt.graphics.Rectangle displayBounds = shell.getDisplay().getBounds();
   org.eclipse.swt.graphics.Rectangle shellBounds = shell.getBounds();
   shellBounds.x = Math.max(Math.min(position.x, displayBounds.width - shellBounds.width), 0);
   shellBounds.y =
       Math.max(Math.min(position.y + 16, displayBounds.height - shellBounds.height), 0);
   shell.setBounds(shellBounds);
 }
Esempio n. 8
0
  public void testMIRR() {
    double vals[] = {-1000, 50, 50, 50, 50, 50, 1050};
    assertTrue(Math.abs(0.05 - Vba.MIRR(vals, 0.05, 0.05)) < 0.0000001);

    vals = new double[] {-1000, 200, 200, 200, 200, 200, 200};
    assertTrue(Math.abs(0.05263266 - Vba.MIRR(vals, 0.05, 0.05)) < 0.0000001);

    vals = new double[] {-1000, 200, 200, 200, 200, 200, 200};
    assertTrue(Math.abs(0.04490701 - Vba.MIRR(vals, 0.06, 0.04)) < 0.0000001);
  }
Esempio n. 9
0
  private boolean buildNoteSequence() {

    noteSequence = new NoteSequence();

    double quantizeBeatFactor = quantizeBeatSetting * 1000.0 * 60.0 / (double) getBPM();
    double quantizeDurationFactor = quantizeDurationSetting * 1000.0 * 60.0 / (double) getBPM();

    for (int i = 0; i < noteList.size(); i++) {
      noteListElement = noteList.get(i);

      if (noteListElement.underTone == true) {
        continue;
      }

      note = noteListElement.note;

      if (note < getLowPitch()) continue;
      if (note > getHighPitch()) continue;

      double startTime = (double) (noteListElement.startTime);

      if (quantizeBeatFactor != 0.0)
        startTime = Math.floor(startTime / quantizeBeatFactor) * quantizeBeatFactor;
      long startTick = 1 + (long) (startTime * getTickRate() / 1000.0);

      double endTime = (double) (noteListElement.endTime);

      if (quantizeBeatFactor != 0.0)
        endTime = Math.ceil(endTime / quantizeBeatFactor) * quantizeBeatFactor;
      if (quantizeDurationFactor != 0)
        endTime =
            startTime
                + (Math.ceil((endTime - startTime) / quantizeDurationFactor)
                    * quantizeDurationFactor);

      long endTick = 1 + (long) (endTime * getTickRate() / 1000.0);

      if ((endTick - startTick) < 1) endTick = startTick + 1;
      System.out.println(
          "times: " + startTime + ", " + endTime + ", " + getStartTime() + ", " + getEndTime());
      if (endTime < getStartTime()) continue;
      if (startTime > getEndTime()) continue;

      velocity = 64;
      noteSequence.add(new NoteSequenceElement(note, ON, startTick, velocity));
      noteSequence.add(new NoteSequenceElement(note, OFF, endTick, velocity));
    }

    if (noteSequence.size() == 0) {
      return false;
    } else {
      noteSequence.sort();
      return true;
    }
  }
Esempio n. 10
0
  public boolean transform(ProgressListener progressListener) {

    toneMap = toneMapFrame.getToneMap();
    timeSet = toneMap.getTimeSet();
    pitchSet = toneMap.getPitchSet();
    timeRange = timeSet.getRange();
    pitchRange = pitchSet.getRange();

    pitchFreqSet = pitchSet.getFreqSet();
    audioFTPower = new double[timeRange * (pitchRange + 1)];

    int startSample = timeSet.getStartSample();
    int endSample = timeSet.getEndSample();
    int sampleLength = (int) Math.floor((endSample - startSample) / ((double) resolution));
    double[] audioSamples = new double[sampleLength];

    for (int i = 0; i < sampleLength; i++) {
      audioSamples[i] = (double) audioData[startSample + i * resolution];
    }

    int sampleIndexSize =
        (int) Math.floor((double) timeSet.getSampleIndexSize() / (double) resolution);

    double dt = (double) resolution / sampleRate;
    if (transformMode == TRANSFORM_MODE_JAVA) {
      wavelet.convert(
          audioFTPower,
          audioSamples,
          pitchFreqSet,
          dt,
          (double) pFactor,
          (double) tFactor,
          sampleIndexSize,
          sampleLength,
          pitchRange,
          progressListener);
    } else {

      WaveletJNI waveletJNI = new WaveletJNI();

      waveletJNI.waveletConvert(
          audioFTPower,
          audioSamples,
          pitchFreqSet,
          dt,
          (double) pFactor,
          (double) tFactor,
          sampleIndexSize,
          sampleLength,
          pitchRange,
          progressListener);
    }

    return true;
  }
Esempio n. 11
0
 public double getValue(DatanVector x) {
   double result;
   double a = sqrt2pi * x.getElement(1);
   if (a < small) f = big;
   else f = Math.log(a);
   result = (double) y.length * f;
   for (int i = 0; i < y.length; i++) {
     f = Math.pow((y[i] - x.getElement(0)), 2.) / (2. * x.getElement(1) * x.getElement(1));
     result += f;
   }
   return result;
 }
Esempio n. 12
0
  public boolean ManipBoxPattern(int xMin, int yMin, int xMax, int yMax, double amount) {
    int x;
    int y;
    y = yMin;
    while (y < yMax) {
      x = xMin;
      while (x < xMax) {
        Pixel p = this.getPixel(x, y);
        int yOffset = Math.abs(yMin - y);
        int xOffset = Math.abs(xMin - x);

        double ra = normal(x, xMin, xMax);

        if (ra >= 1.0) {

          int R = (int) (p.getRed() * amount);
          int G = (int) (p.getGreen() * amount);
          int B = (int) (255 * amount);

          p.setRed(R);
          p.setGreen(G);
          p.setBlue(B);

          p.getColor().brighter();
        } else {

          int R = (int) (p.getRed() * amount);
          int G = (int) (255 * amount);
          int B = (int) (p.getBlue() * amount);

          p.setRed(R);
          p.setGreen(G);
          p.setBlue(B);
        }

        if (x % 2 == 0) {

          int R = (int) (255 * amount);
          int G = (int) (p.getGreen() * amount);
          int B = (int) (p.getBlue() * amount);

          p.setRed(R);
          p.setGreen(G);
          p.setBlue(B);
        }
        x = x + 1;
      }
      y = y + 1;
    }

    return true;
  }
Esempio n. 13
0
 protected void plotScatterDiagram() {
   // plot sample as one dimensional scatter plot and Gaussian
   double xmax = 5.;
   double xmin = -5.;
   DatanGraphics.openWorkstation(getClass().getName(), "E3Min_1.ps");
   DatanGraphics.setFormat(0., 0.);
   DatanGraphics.setWindowInComputingCoordinates(xmin, xmax, 0., .5);
   DatanGraphics.setViewportInWorldCoordinates(-.15, .9, .16, .86);
   DatanGraphics.setWindowInWorldCoordinates(-.414, 1., 0., 1.);
   DatanGraphics.setBigClippingWindow();
   DatanGraphics.chooseColor(2);
   DatanGraphics.drawFrame();
   DatanGraphics.drawScaleX("y");
   DatanGraphics.drawScaleY("f(y)");
   DatanGraphics.drawBoundary();
   double xpl[] = new double[2];
   double ypl[] = new double[2];
   // plot scatter diagram
   DatanGraphics.chooseColor(1);
   for (int i = 0; i < y.length; i++) {
     xpl[0] = y[i];
     xpl[1] = y[i];
     ypl[0] = 0.;
     ypl[0] = .1;
     DatanGraphics.drawPolyline(xpl, ypl);
   }
   // draw Gaussian corresponding to solution
   int npl = 100;
   xpl = new double[npl];
   ypl = new double[npl];
   double fact = 1. / (Math.sqrt(2. * Math.PI) * x.getElement(1));
   double dpl = (xmax - xmin) / (double) (npl - 1);
   for (int i = 0; i < npl; i++) {
     xpl[i] = xmin + (double) i * dpl;
     ypl[i] = fact * Math.exp(-.5 * Math.pow((xpl[i] - x.getElement(0)) / x.getElement(1), 2.));
   }
   DatanGraphics.chooseColor(5);
   DatanGraphics.drawPolyline(xpl, ypl);
   // draw caption
   String sn = "N = " + nny;
   numForm.setMaximumFractionDigits(3);
   numForm.setMinimumFractionDigits(3);
   String sx1 = ", x_1# = " + numForm.format(x.getElement(0));
   String sx2 = ", x_2# = " + numForm.format(x.getElement(1));
   String sdx1 = ", &D@x_1# = " + numForm.format(Math.sqrt(cx.getElement(0, 0)));
   String sdx2 = ", &D@x_2# = " + numForm.format(Math.sqrt(cx.getElement(1, 1)));
   caption = sn + sx1 + sx2 + sdx1 + sdx2;
   DatanGraphics.setBigClippingWindow();
   DatanGraphics.chooseColor(2);
   DatanGraphics.drawCaption(1., caption);
   DatanGraphics.closeWorkstation();
 }
  public TopicScores getTokenDocumentDiscrepancies() {
    TopicScores scores = new TopicScores("token-doc-diff", numTopics, numTopWords);
    scores.wordScoresDefined = true;

    for (int topic = 0; topic < numTopics; topic++) {
      int[][] matrix = topicCodocumentMatrices[topic];
      TreeSet<IDSorter> sortedWords = topicSortedWords.get(topic);

      double topicScore = 0.0;

      double[] wordDistribution = new double[numTopWords];
      double[] docDistribution = new double[numTopWords];

      double wordSum = 0.0;
      double docSum = 0.0;

      int position = 0;
      Iterator<IDSorter> iterator = sortedWords.iterator();
      while (iterator.hasNext() && position < numTopWords) {
        IDSorter info = iterator.next();

        wordDistribution[position] = info.getWeight();
        docDistribution[position] = matrix[position][position];

        wordSum += wordDistribution[position];
        docSum += docDistribution[position];

        position++;
      }

      for (position = 0; position < numTopWords; position++) {
        double p = wordDistribution[position] / wordSum;
        double q = docDistribution[position] / docSum;
        double meanProb = 0.5 * (p + q);

        double score = 0.0;
        if (p > 0) {
          score += 0.5 * p * Math.log(p / meanProb);
        }
        if (q > 0) {
          score += 0.5 * q * Math.log(q / meanProb);
        }

        scores.setTopicWordScore(topic, position, score);
        topicScore += score;
      }

      scores.setTopicScore(topic, topicScore);
    }

    return scores;
  }
Esempio n. 15
0
 public static BufferedImage scaleImage(BufferedImage bi, double scale) {
   int w1 = (int) (Math.round(scale * bi.getWidth()));
   int h1 = (int) (Math.round(scale * bi.getHeight()));
   BufferedImage image = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_RGB);
   Graphics2D g2 = image.createGraphics();
   g2.setRenderingHint(
       RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
   g2.setPaint(Color.white);
   g2.fillRect(0, 0, w1, h1);
   g2.drawImage(bi, 0, 0, w1, h1, null); // this);
   g2.dispose();
   return image;
 }
Esempio n. 16
0
  /**
   * Returns a partial token.
   *
   * @param token input text
   * @param start start position
   * @param end end position
   * @return resulting text
   */
  public static byte[] subtoken(final byte[] token, final int start, final int end) {
    int s = Math.max(0, start);
    final int e = Math.min(end, token.length);
    if (s == 0 && e == token.length) return token;
    if (s >= e) return EMPTY;

    int t = Math.max(0, s - 4);
    for (; t != s && t < e; t += cl(token, t)) {
      if (t >= s) s = t;
    }
    for (; t < e; t += cl(token, t)) ;
    return Arrays.copyOfRange(token, s, t);
  }
Esempio n. 17
0
  public void testIRR() {
    double vals[] = {-1000, 50, 50, 50, 50, 50, 1050};
    assertTrue(Math.abs(0.05 - Vba.IRR(vals, 0.1)) < 0.0000001);

    vals = new double[] {-1000, 200, 200, 200, 200, 200, 200};
    assertTrue(Math.abs(0.05471796 - Vba.IRR(vals, 0.1)) < 0.0000001);

    // what happens if the numbers are inversed? this may not be
    // accurate

    vals = new double[] {1000, -200, -200, -200, -200, -200, -200};
    assertTrue(Math.abs(0.05471796 - Vba.IRR(vals, 0.1)) < 0.0000001);
  }
Esempio n. 18
0
  /**
   * Конвертация строки типа: 5 Minutes
   *
   * @param str
   * @return
   */
  private static int parseDuration(String str) throws ParseException {
    int idx = str.indexOf(' ');
    float num = DF.parse(str.substring(0, idx)).floatValue();
    switch (str.substring(idx + 1)) {
      case "Seconds":
        return Math.round(num);

      case "Minutes":
        return Math.round(num * 60);

      default:
        throw new ParseException("Неизвестный формат единиц: " + str, idx + 1);
    }
  }
Esempio n. 19
0
  /** Encode the value as a string */
  public String encodeVal() {
    StringBuffer s = new StringBuffer(32);

    s.append(getYear()).append('-');

    int month = getMonth();
    if (month < 10) s.append('0');
    s.append(month).append('-');

    int day = getDay();
    if (day < 10) s.append('0');
    s.append(day).append('T');

    int hour = getHour();
    if (hour < 10) s.append('0');
    s.append(hour).append(':');

    int min = getMinute();
    if (min < 10) s.append('0');
    s.append(min).append(':');

    int sec = getSecond();
    if (sec < 10) s.append('0');
    s.append(sec).append('.');

    int millis = getMillisecond();
    if (millis < 10) s.append('0');
    if (millis < 100) s.append('0');
    s.append(millis);

    int offset = getTimeZoneOffset();
    if (offset == 0) {
      s.append('Z');
    } else {
      int hrOff = Math.abs(offset / (1000 * 60 * 60));
      int minOff = Math.abs((offset % (1000 * 60 * 60)) / (1000 * 60));

      if (offset < 0) s.append('-');
      else s.append('+');

      if (hrOff < 10) s.append('0');
      s.append(hrOff);

      s.append(':');
      if (minOff < 10) s.append('0');
      s.append(minOff);
    }

    return s.toString();
  }
 // BEGIN KAWIGIEDIT TESTING
 // Generated by KawigiEdit-pf 2.3.0
 private static boolean KawigiEdit_RunTest(
     int testNum, int[] p0, int[] p1, boolean hasAnswer, double p2) {
   System.out.print("Test " + testNum + ": [" + "{");
   for (int i = 0; p0.length > i; ++i) {
     if (i > 0) {
       System.out.print(",");
     }
     System.out.print(p0[i]);
   }
   System.out.print("}" + "," + "{");
   for (int i = 0; p1.length > i; ++i) {
     if (i > 0) {
       System.out.print(",");
     }
     System.out.print(p1[i]);
   }
   System.out.print("}");
   System.out.println("]");
   GreaterGame obj;
   double answer;
   obj = new GreaterGame();
   long startTime = System.currentTimeMillis();
   answer = obj.calc(p0, p1);
   long endTime = System.currentTimeMillis();
   boolean res;
   res = true;
   System.out.println("Time: " + (endTime - startTime) / 1000.0 + " seconds");
   if (hasAnswer) {
     System.out.println("Desired answer:");
     System.out.println("\t" + p2);
   }
   System.out.println("Your answer:");
   System.out.println("\t" + answer);
   if (hasAnswer) {
     res = answer == answer && Math.abs(p2 - answer) <= 1e-9 * Math.max(1.0, Math.abs(p2));
   }
   if (!res) {
     System.out.println("DOESN'T MATCH!!!!");
   } else if ((endTime - startTime) / 1000.0 >= 2) {
     System.out.println("FAIL the timeout");
     res = false;
   } else if (hasAnswer) {
     System.out.println("Match :-)");
   } else {
     System.out.println("OK, but is it right?");
   }
   System.out.println("");
   return res;
 }
Esempio n. 21
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;
     }
   }
 }
Esempio n. 22
0
  private Fraction1 reduce() {
    Fraction1 result = new Fraction1();

    int common = 0;
    int numer = Math.abs(num);
    int denomin = Math.abs(denom);

    if (numer > denomin) common = gcd(numer, denomin);
    else if (num < denomin) common = gcd(denomin, numer);
    else common = numer;

    result.num = num / common;
    result.denom = denom / common;
    return result;
  }
Esempio n. 23
0
  public void randomColor() {
    Pixel[][] pixels = this.getPixels2D();
    for (Pixel[] row : pixels) {
      for (Pixel currentPixel : row) {
        int randomRed, randomBlue, randomGreen;
        randomRed = (int) (Math.random() * 256);
        randomBlue = (int) (Math.random() * 256);
        randomGreen = (int) (Math.random() * 256);

        currentPixel.setBlue(randomBlue);
        currentPixel.setRed(randomRed);
        currentPixel.setGreen(randomGreen);
      }
    }
  }
Esempio n. 24
0
  // From: http://forum.java.sun.com/thread.jspa?threadID=378460&tstart=135
  void drawArrow(
      Graphics2D g2d,
      int xCenter,
      int yCenter,
      int x,
      int y,
      float stroke,
      BasicStroke drawStroke) {
    double aDir = Math.atan2(xCenter - x, yCenter - y);
    // Line can be dashed.
    g2d.setStroke(drawStroke);
    g2d.drawLine(x, y, xCenter, yCenter);
    // make the arrow head solid even if dash pattern has been specified
    g2d.setStroke(lineStroke);
    Polygon tmpPoly = new Polygon();
    int i1 = 12 + (int) (stroke * 2);
    // make the arrow head the same size regardless of the length length
    int i2 = 6 + (int) stroke;
    tmpPoly.addPoint(x, y);
    tmpPoly.addPoint(x + xCor(i1, aDir + .5), y + yCor(i1, aDir + .5));
    tmpPoly.addPoint(x + xCor(i2, aDir), y + yCor(i2, aDir));
    tmpPoly.addPoint(x + xCor(i1, aDir - .5), y + yCor(i1, aDir - .5));
    tmpPoly.addPoint(x, y); // arrow tip
    g2d.drawPolygon(tmpPoly);

    // Remove this line to leave arrow head unpainted:
    g2d.fillPolygon(tmpPoly);
  }
  public TopicScores getCoherence() {
    TopicScores scores = new TopicScores("coherence", numTopics, numTopWords);
    scores.wordScoresDefined = true;

    for (int topic = 0; topic < numTopics; topic++) {
      int[][] matrix = topicCodocumentMatrices[topic];

      double topicScore = 0.0;

      for (int row = 0; row < numTopWords; row++) {
        double rowScore = 0.0;
        double minScore = 0.0;
        for (int col = 0; col < row; col++) {
          double score =
              Math.log((matrix[row][col] + model.beta) / (matrix[col][col] + model.beta));
          rowScore += score;
          if (score < minScore) {
            minScore = score;
          }
        }
        topicScore += rowScore;
        scores.setTopicWordScore(topic, row, minScore);
      }

      scores.setTopicScore(topic, topicScore);
    }

    return scores;
  }
  public TopicScores getDistanceFromUniform() {
    int[] tokensPerTopic = model.tokensPerTopic;

    TopicScores scores = new TopicScores("uniform_dist", numTopics, numTopWords);
    scores.wordScoresDefined = true;

    int numTypes = alphabet.size();

    for (int topic = 0; topic < numTopics; topic++) {

      double topicScore = 0.0;
      int position = 0;
      TreeSet<IDSorter> sortedWords = topicSortedWords.get(topic);

      for (IDSorter info : sortedWords) {
        int type = info.getID();
        double count = info.getWeight();

        double score =
            (count / tokensPerTopic[topic]) * Math.log((count * numTypes) / tokensPerTopic[topic]);

        if (position < numTopWords) {
          scores.setTopicWordScore(topic, position, score);
        }

        topicScore += score;
        position++;
      }

      scores.setTopicScore(topic, topicScore);
    }

    return scores;
  }
Esempio n. 27
0
  public static void main(String[] args) throws IOException {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int n = Integer.parseInt(br.readLine());
    int a[] = new int[n];
    int c[] = new int[n];
    for (int i = 0; i < n; i++) {
      a[i] = Integer.parseInt(br.readLine());
    }

    for (int i = 0; i < n; i++) {
      c[i] = 1;
    }

    for (int j = 1; j < n; j++) {
      if (a[j] > a[j - 1]) c[j] = c[j - 1] + 1;
    }

    for (int k = n - 2; k >= 0; k--) {
      if (a[k] > a[k + 1]) c[k] = Math.max(c[k + 1] + 1, c[k]);
    }
    int count = 0;
    for (int i = 0; i < n; i++) {
      count += c[i];
    }

    System.out.println(count);
  }
Esempio n. 28
0
  void run(int maxSteps, double minError) {
    int i;
    // Train neural network until minError reached or maxSteps exceeded
    double error = 1;
    for (i = 0; i < maxSteps && error > minError; i++) {
      error = 0;
      for (int p = 0; p < inputs.length; p++) {
        setInput(inputs[p]);

        activate();

        output = getOutput();
        resultOutputs[p] = output;

        for (int j = 0; j < expectedOutputs[p].length; j++) {
          double err = Math.pow(output[j] - expectedOutputs[p][j], 2);
          error += err;
        }

        applyBackpropagation(expectedOutputs[p]);
      }
    }

    printResult();

    System.out.println("Sum of squared errors = " + error);
    System.out.println("##### EPOCH " + i + "\n");
    if (i == maxSteps) {
      System.out.println("!Error training try again");
    } else {
      printAllWeights();
      printWeightUpdate();
    }
  }
Esempio n. 29
0
  /**
   * Creates a byte array representation from the specified double value; inspired by Xavier Franc's
   * Qizx/open processor.
   *
   * @param dbl double value to be converted
   * @return byte array
   */
  public static byte[] token(final double dbl) {
    final byte[] b = tok(dbl);
    if (b != null) return b;

    final double a = Math.abs(dbl);
    return chopNumber(token(a >= 1e-6 && a < 1e6 ? DD.format(dbl) : SD.format(dbl)));
  }
Esempio n. 30
0
  public synchronized void run() {

    byte[] buffer = new byte[BUFFER_SIZE];

    for (; ; ) {
      try {
        this.wait(100);
      } catch (InterruptedException ie) {
      }

      int len = 0;
      try {
        int noBytes = pin.available();

        if (noBytes > 0) {
          len = pin.read(buffer, 0, Math.min(noBytes, BUFFER_SIZE));
          if (len > 0) {
            jTextArea.append(new String(buffer, 0, len));
            jTextArea.setCaretPosition(jTextArea.getText().length());
          }
        }
      } catch (IOException ioe) {
        throw new UIError("Unable to read from input stream! " + ioe.getMessage());
      }
    }
  }