/** The main loop for the background thread. It is here that most of the work os orchestrated. */
  public void run() {

    double thisCost = 500.0;
    double oldCost = 0.0;
    double dcost = 500.0;
    int countSame = 0;

    map.update(map.getGraphics());

    while (countSame < 100) {

      generation++;

      int ioffset = matingPopulationSize;
      int mutated = 0;

      // Mate the chromosomes in the favoured population
      // with all in the mating population
      for (int i = 0; i < favoredPopulationSize; i++) {
        Chromosome cmother = chromosomes[i];
        // Select partner from the mating population
        int father = (int) (0.999999 * Math.random() * (double) matingPopulationSize);
        Chromosome cfather = chromosomes[father];

        mutated += cmother.mate(cfather, chromosomes[ioffset], chromosomes[ioffset + 1]);
        ioffset += 2;
      }

      // The new generation is in the matingPopulation area
      // move them to the correct area for sort.
      for (int i = 0; i < matingPopulationSize; i++) {
        chromosomes[i] = chromosomes[i + matingPopulationSize];
        chromosomes[i].calculateCost(cities);
      }

      // Now sort the new mating population
      Chromosome.sortChromosomes(chromosomes, matingPopulationSize);

      double cost = chromosomes[0].getCost();
      dcost = Math.abs(cost - thisCost);
      thisCost = cost;
      double mutationRate = 100.0 * (double) mutated / (double) matingPopulationSize;

      NumberFormat nf = NumberFormat.getInstance();
      nf.setMinimumFractionDigits(2);
      nf.setMinimumFractionDigits(2);

      status.setText(
          "Generation "
              + generation
              + " Cost "
              + (int) thisCost
              + " Mutated "
              + nf.format(mutationRate)
              + "%");

      if ((int) thisCost == (int) oldCost) {
        countSame++;
      } else {
        countSame = 0;
        oldCost = thisCost;
      }
      map.update(map.getGraphics());
    }
    status.setText("Solution found after " + generation + " generations.");
  }
Example #2
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);
  }
Example #3
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;
  }
Example #4
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);
  }
Example #5
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;
 }
Example #7
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;
  }
Example #8
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)));
  }
Example #9
0
 private static boolean equalDouble(String param, double d1, double d2) {
   if (Double.isNaN(d1) && Double.isNaN(d2)) return true;
   if (Math.abs(d1 - d2) > 0.001) {
     System.out.println("  " + param + " " + d1 + " != " + d2 + " diff " + (d1 - d2));
     return false;
   }
   return true;
 }
Example #10
0
  public Matrix matrixAccuralize() { // 精确化矩阵
    int i, j;
    Matrix matrix = new Matrix(this);

    for (i = 0; i < matrix.getLine(); i++)
      for (j = 0; j < matrix.getRow(); j++)
        if (Math.abs(matrix.getElement(i, j)) <= matrix.getAccuracy()) matrix.setElement(i, j, 0.0);
    return matrix;
  }
Example #11
0
  /**
   * Called by the paint method to draw the graph and its graph items.
   *
   * @param g the graphics context.
   */
  public void paintComponent(Graphics g) {

    Dimension dim = getSize();
    Insets insets = getInsets();
    dataArea =
        new Rectangle(
            insets.left,
            insets.top,
            dim.width - insets.left - insets.right - 1,
            dim.height - insets.top - insets.bottom - 1);
    // background
    if (isOpaque()) {
      g.setColor(getBackground());
      g.fillRect(0, 0, dim.width, dim.height);
    }
    g.setColor(getForeground());
    // get axis tickmarks
    double xticks[] = xAxis.getTicks();
    double yticks[] = yAxis.getTicks();
    int yb = dataArea.y + dataArea.height;
    // draw grid
    if (showGrid) {
      g.setColor(gridColor != null ? gridColor : getBackground().darker());
      // vertical x grid lines
      for (int i = 0; i < xticks.length; i += 2) {
        int x = dataArea.x + (int) Math.round(xticks[i]);
        g.drawLine(x, dataArea.y, x, dataArea.y + dataArea.height);
      }
      // horizontal y grid lines
      for (int i = 0; i < yticks.length; i += 2) {
        int y = yb - (int) Math.round(yticks[i]);
        g.drawLine(dataArea.x, y, dataArea.x + dataArea.width, y);
      }
    }
    for (int i = 0; i < graphItems.size(); i++) {
      ((GraphItem) graphItems.elementAt(i)).draw(this, g, dataArea, xAxis, yAxis);
    }
    if (sPt != null && ePt != null) {
      g.setColor(getForeground());
      g.drawRect(
          Math.min(sPt.x, ePt.x), Math.min(sPt.y, ePt.y),
          Math.abs(ePt.x - sPt.x), Math.abs(ePt.y - sPt.y));
    }
  }
Example #12
0
 int computeDifference() {
   for (int i = 0; i < elements.length; i++) {
     for (int j = i + 1; j < elements.length; j++) {
       int d = Math.abs(elements[i] - elements[j]);
       if (d >= maximumDifference) {
         this.maximumDifference = d;
       }
     }
   }
   return this.maximumDifference;
 }
Example #13
0
  public void testPPmt() {
    assertEquals(-607.9248252633897, Vba.pPmt(0.10, 1, 30, 100000, 0, false));
    assertEquals(-8422.451500705567, Vba.pPmt(0.10, 15, 30, 100000, 0, false));
    assertEquals(-10547.13234273705, Vba.pPmt(0.10, 30, 30, 100000, 0, false));

    // verify that pmt, ipmt, and ppmt add up
    double pmt = Vba.pmt(0.10, 30, 100000, 0, false);
    double ipmt = Vba.iPmt(0.10, 15, 30, 100000, 0, false);
    double ppmt = Vba.pPmt(0.10, 15, 30, 100000, 0, false);
    assertTrue(Math.abs(pmt - (ipmt + ppmt)) < 0.0000001);
  }
Example #14
0
 /**
  * Checks if the specified value equals a constant token.
  *
  * @param dbl value to be converted
  * @return byte array or zero, or {@code null}
  */
 private static byte[] tok(final double dbl) {
   if (dbl == Double.POSITIVE_INFINITY) return INF;
   if (dbl == Double.NEGATIVE_INFINITY) return NINF;
   if (dbl == 0) return 1 / dbl > 0 ? ZERO : MZERO;
   if (Double.isNaN(dbl)) return NAN;
   final double a = Math.abs(dbl);
   if (a < 1e6) {
     final int i = (int) dbl;
     if (i == dbl) return token(i);
   }
   return null;
 }
Example #15
0
 /**
  * returns in the form " X hours and Y minutes from now/ago" or " RIGHT NOW!" it returns nothing
  * if the difference is > 1 day
  */
 private String getTimeDifference(int mins) {
   if (Math.abs(mins) > 60 * 24) {
     return "";
   }
   boolean neg = mins < 0;
   mins = Math.abs(mins);
   if (mins < 5) {
     return " ****THAT'S RIGHT NOW!****";
   }
   String ret = " (";
   int hrs = mins / 60;
   mins = mins % 60;
   if (hrs > 0) {
     ret = ret + hrs + " hours and ";
   }
   ret = ret + mins + " minutes ";
   if (neg) {
     ret = ret + "ago)";
   } else ret = ret + "from now)";
   return ret;
 }
Example #16
0
  public void testRate() {
    double nPer, pmt, PV, fv, guess, result;
    boolean type = false;
    nPer = 12 * 30;
    pmt = -877.57;
    PV = 100000;
    fv = 0;
    guess = 0.10 / 12;
    result = Vba.rate(nPer, pmt, PV, fv, type, guess);

    // compare rate to pV calculation
    double expRate = 0.0083333;
    double expPV = Vba.pV(expRate, 12 * 30, -877.57, 0, false);
    result = Vba.rate(12 * 30, -877.57, expPV, 0, false, 0.10 / 12);
    assertTrue(Math.abs(expRate - result) < 0.0000001);

    // compare rate to fV calculation
    double expFV = Vba.fV(expRate, 12, -100, 0, false);
    result = Vba.rate(12, -100, 0, expFV, false, 0.10 / 12);
    assertTrue(Math.abs(expRate - result) < 0.0000001);
  }
Example #17
0
  /**
   * Creates a byte array representation from the specified float value.
   *
   * @param flt float value to be converted
   * @return byte array
   */
  public static byte[] token(final float flt) {
    final byte[] b = tok(flt);
    if (b != null) return b;

    // not that brilliant here.. no chance for elegant code either
    // due to the nifty differences between Java and XQuery
    for (int i = 0; i < FLT.length; ++i) if (flt == FLT[i]) return FLTSTR[i];
    final float a = Math.abs(flt);
    final boolean small = a >= 1e-6f && a < 1e6f;
    String s1 = small ? DF.format(flt) : SF.format(flt);
    final String s2 = Float.toString(flt);
    if (s2.length() < s1.length() && (!s2.contains("E") || !small)) s1 = s2;
    return chopNumber(token(s1));
  }
  /* CALCULATE VALUES QUADRANTS: Calculate x-y values where direction is not
  parallel to eith x or y axis. */
  public static void calcValuesQuad(int x1, int y1, int x2, int y2) {
    double arrowAng = Math.toDegrees(Math.atan((double) haw / (double) al));
    double dist = Math.sqrt(al * al + aw);
    double lineAng =
        Math.toDegrees(Math.atan(((double) Math.abs(x1 - x2)) / ((double) Math.abs(y1 - y2))));

    // Adjust line angle for quadrant
    if (x1 > x2) {
      // South East
      if (y1 > y2) lineAng = 180.0 - lineAng;
    } else {
      // South West
      if (y1 > y2) lineAng = 180.0 + lineAng;
      // North West
      else lineAng = 360.0 - lineAng;
    }

    // Calculate coords
    xValues[0] = x2;
    yValues[0] = y2;
    calcCoords(1, x2, y2, dist, lineAng - arrowAng);
    calcCoords(2, x2, y2, dist, lineAng + arrowAng);
  }
Example #19
0
  public int matrixRank() // 矩阵的秩
      {
    int rank = 0, i, j;
    Matrix matrix = new Matrix();

    matrix = matrixLineSimplify();
    for (i = 0; i < matrix.getLine(); i++)
      for (j = 0; j < matrix.getRow(); j++)
        if (Math.abs(matrix.getElement(i, j)) > matrix.getAccuracy()) {
          rank++;
          break;
        }
    return rank;
  }
Example #20
0
  /** Insert the method's description here. Creation date: (16/01/2002 9.53.37) */
  public static boolean xor_evaluate(Organism organism) {

    Network _net = null;
    boolean success = false;
    double errorsum = 0.0;
    double[] out = new double[4]; // The four outputs

    //   int numnodes = 0;
    int net_depth = 0; // The max depth of the network to be activated
    int count = 0;

    // The four possible input combinations to xor
    // The first number is for biasing

    double in[][] = {{1.0, 0.0, 0.0}, {1.0, 0.0, 1.0}, {1.0, 1.0, 0.0}, {1.0, 1.0, 1.0}};

    _net = organism.net;
    //   numnodes = organism.genome.nodes.size();

    net_depth = _net.max_depth();

    // for each example , 'count', propagate signal .... and compute results
    for (count = 0; count <= 3; count++) {

      // first activation from sensor to first next levelof neurons
      _net.load_sensors(in[count]);
      success = _net.activate();

      // next activation while last level is reached !
      // use depth to ensure relaxation

      for (int relax = 0; relax <= net_depth; relax++) success = _net.activate();

      // ok : the propagation is completed : repeat until all examples are presented
      out[count] = ((NNode) _net.getOutputs().firstElement()).getActivation();
      _net.flush();
    }

    // control the result
    if (success) {
      errorsum =
          (double)
              (Math.abs(out[0])
                  + Math.abs(1.0 - out[1])
                  + Math.abs(1.0 - out[2])
                  + Math.abs(out[3]));
      organism.setFitness(Math.pow((4.0 - errorsum), 2));
      organism.setError(errorsum);
    } else {
      errorsum = 999.0;
      organism.setFitness(0.001);
      organism.setError(errorsum);
    }
    String mask03 = "0.000";
    DecimalFormat fmt03 = new DecimalFormat(mask03);

    if ((out[0] < 0.5) && (out[1] >= 0.5) && (out[2] >= 0.5) && (out[3] < 0.5)) {
      organism.setWinner(true);
      return true;
    } else {
      organism.setWinner(false);
      return false;
    }
  }
  /**
   * creates a new image
   *
   * @param svgHandle a svg handle
   * @param resourceId the id of the resource from which the image will be created
   */
  protected void createNewImage(SVGHandle svgHandle, String resourceId) {

    if (svgHandle != null && resourceId != null && !resourceId.equals("")) {

      Element resourceElement = null;

      resourceElement =
          svgHandle.getScrollPane().getSVGCanvas().getDocument().getElementById(resourceId);

      final String fresourceId = resourceId;

      if (resourceElement != null) {

        final SVGHandle fhandle = svgHandle;

        // creating the canvas and setting its properties
        final JSVGCanvas canvas =
            new JSVGCanvas() {

              @Override
              public void dispose() {

                removeKeyListener(listener);
                removeMouseMotionListener(listener);
                removeMouseListener(listener);
                disableInteractions = true;
                selectableText = false;
                userAgent = null;

                bridgeContext.dispose();
                super.dispose();
              }
            };

        // the element to be added
        Element elementToAdd = null;

        canvas.setDocumentState(JSVGComponent.ALWAYS_STATIC);
        canvas.setDisableInteractions(true);

        // creating the new document
        final String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
        final SVGDocument doc = (SVGDocument) resourceElement.getOwnerDocument().cloneNode(false);

        // creating the root element
        final Element root =
            (Element)
                doc.importNode(resourceElement.getOwnerDocument().getDocumentElement(), false);
        doc.appendChild(root);

        // removing all the attributes of the root element
        NamedNodeMap attributes = doc.getDocumentElement().getAttributes();

        for (int i = 0; i < attributes.getLength(); i++) {

          if (attributes.item(i) != null) {

            doc.getDocumentElement().removeAttribute(attributes.item(i).getNodeName());
          }
        }

        // adding the new attributes for the root
        root.setAttributeNS(null, "width", imageSize.width + "");
        root.setAttributeNS(null, "height", imageSize.height + "");
        root.setAttributeNS(null, "viewBox", "0 0 " + imageSize.width + " " + imageSize.height);

        // the defs element that will contain the cloned resource node
        final Element defs = (Element) doc.importNode(resourceElement.getParentNode(), true);
        root.appendChild(defs);

        if (resourceElement.getNodeName().equals("linearGradient")
            || resourceElement.getNodeName().equals("radialGradient")
            || resourceElement.getNodeName().equals("pattern")) {

          // the rectangle that will be drawn
          final Element rect = doc.createElementNS(svgNS, "rect");
          rect.setAttributeNS(null, "x", "0");
          rect.setAttributeNS(null, "y", "0");
          rect.setAttributeNS(null, "width", imageSize.width + "");
          rect.setAttributeNS(null, "height", imageSize.height + "");

          elementToAdd = rect;

          // setting that the rectangle uses the resource
          String id = resourceElement.getAttribute("id");

          if (id == null) {

            id = "";
          }

          rect.setAttributeNS(null, "style", "fill:url(#" + id + ");");

          // getting the cloned resource node
          Node cur = null;
          Element clonedResourceElement = null;
          String id2 = "";

          for (cur = defs.getFirstChild(); cur != null; cur = cur.getNextSibling()) {

            if (cur instanceof Element) {

              id2 = ((Element) cur).getAttribute("id");

              if (id2 != null && id.equals(id2)) {

                clonedResourceElement = (Element) cur;
              }
            }
          }

          if (clonedResourceElement != null) {

            // getting the root element of the initial resource
            // element
            Element initialRoot = resourceElement.getOwnerDocument().getDocumentElement();

            // getting the width and height of the initial root
            // element
            double initialWidth = 0, initialHeight = 0;

            try {
              initialWidth =
                  EditorToolkit.getPixelledNumber(initialRoot.getAttributeNS(null, "width"));
              initialHeight =
                  EditorToolkit.getPixelledNumber(initialRoot.getAttributeNS(null, "height"));
            } catch (DOMException ex) {
              ex.printStackTrace();
            }

            if (resourceElement.getNodeName().equals("linearGradient")) {

              if (resourceElement.getAttributeNS(null, "gradientUnits").equals("userSpaceOnUse")) {

                double x1 = 0, y1 = 0, x2 = 0, y2 = 0;

                // normalizing the values for the vector to fit
                // the rectangle
                try {
                  x1 = Double.parseDouble(resourceElement.getAttributeNS(null, "x1"));
                  y1 = Double.parseDouble(resourceElement.getAttributeNS(null, "y1"));
                  x2 = Double.parseDouble(resourceElement.getAttributeNS(null, "x2"));
                  y2 = Double.parseDouble(resourceElement.getAttributeNS(null, "y2"));

                  x1 = x1 / initialWidth * imageSize.width;
                  y1 = y1 / initialHeight * imageSize.height;
                  x2 = x2 / initialWidth * imageSize.width;
                  y2 = y2 / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "x1", format.format(x1));
                clonedResourceElement.setAttributeNS(null, "y1", format.format(y1));
                clonedResourceElement.setAttributeNS(null, "x2", format.format(x2));
                clonedResourceElement.setAttributeNS(null, "y2", format.format(y2));
              }

            } else if (resourceElement.getNodeName().equals("radialGradient")) {

              if (resourceElement.getAttributeNS(null, "gradientUnits").equals("userSpaceOnUse")) {

                double cx = 0, cy = 0, r = 0, fx = 0, fy = 0;

                // normalizing the values for the circle to fit
                // the rectangle
                try {
                  cx = Double.parseDouble(resourceElement.getAttributeNS(null, "cx"));
                  cy = Double.parseDouble(resourceElement.getAttributeNS(null, "cy"));
                  r = Double.parseDouble(resourceElement.getAttributeNS(null, "r"));
                  fx = Double.parseDouble(resourceElement.getAttributeNS(null, "fx"));
                  fy = Double.parseDouble(resourceElement.getAttributeNS(null, "fy"));

                  cx = cx / initialWidth * imageSize.width;
                  cy = cy / initialHeight * imageSize.height;

                  r =
                      r
                          / (Math.abs(
                              Math.sqrt(Math.pow(initialWidth, 2) + Math.pow(initialHeight, 2))))
                          * Math.abs(
                              Math.sqrt(
                                  Math.pow(imageSize.width, 2) + Math.pow(imageSize.width, 2)));

                  fx = fx / initialWidth * imageSize.width;
                  fy = fy / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "cx", format.format(cx));
                clonedResourceElement.setAttributeNS(null, "cy", format.format(cy));
                clonedResourceElement.setAttributeNS(null, "r", format.format(r));
                clonedResourceElement.setAttributeNS(null, "fx", format.format(fx));
                clonedResourceElement.setAttributeNS(null, "fy", format.format(fy));
              }

            } else if (resourceElement.getNodeName().equals("pattern")) {

              if (resourceElement.getAttributeNS(null, "patternUnits").equals("userSpaceOnUse")) {

                double x = 0, y = 0, w = 0, h = 0;

                // normalizing the values for the vector to fit
                // the rectangle
                try {
                  String xString = resourceElement.getAttributeNS(null, "x");
                  if (!xString.equals("")) {
                    x = Double.parseDouble(xString);
                  }
                  String yString = resourceElement.getAttributeNS(null, "y");
                  if (!yString.equals("")) {
                    y = Double.parseDouble(yString);
                  }
                  String wString = resourceElement.getAttributeNS(null, "w");
                  if (!wString.equals("")) {
                    w = Double.parseDouble(wString);
                  }
                  String hString = resourceElement.getAttributeNS(null, "h");
                  if (!hString.equals("")) {
                    h = Double.parseDouble(hString);
                  }

                  x = x / initialWidth * imageSize.width;
                  y = y / initialHeight * imageSize.height;
                  w = w / initialWidth * imageSize.width;
                  h = h / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "x", format.format(x));
                clonedResourceElement.setAttributeNS(null, "y", format.format(y));
                clonedResourceElement.setAttributeNS(null, "width", format.format(w));
                clonedResourceElement.setAttributeNS(null, "height", format.format(h));
              }
            }
          }

        } else if (resourceElement.getNodeName().equals("marker")) {

          // the line that will be drawn
          final Element line = doc.createElementNS(svgNS, "line");
          line.setAttributeNS(null, "x1", (((double) imageSize.width) / 2) + "");
          line.setAttributeNS(null, "y1", (((double) imageSize.height) / 2) + "");
          line.setAttributeNS(null, "x2", ((double) imageSize.width / 2) + "");
          line.setAttributeNS(null, "y2", imageSize.height + "");

          elementToAdd = line;

          // setting that the line uses the resource
          String id = resourceElement.getAttribute("id");
          if (id == null) id = "";
          line.setAttributeNS(
              null, "style", "stroke:none;fill:none;marker-start:url(#" + id + ");");
        }

        root.appendChild(elementToAdd);

        // adding a rendering listener to the canvas
        GVTTreeRendererAdapter gVTTreeRendererAdapter =
            new GVTTreeRendererAdapter() {

              @Override
              public void gvtRenderingCompleted(GVTTreeRendererEvent evt) {

                Image bufferedImage = canvas.getOffScreen();

                if (bufferedImage != null) {

                  Graphics g = bufferedImage.getGraphics();
                  Color borderColor = MetalLookAndFeel.getSeparatorForeground();

                  g.setColor(borderColor);
                  g.drawRect(0, 0, imageSize.width - 1, imageSize.height - 1);
                }

                setImage(fhandle, fresourceId, bufferedImage);

                // refreshing the panels that have been created when no
                // image was available for them
                Image image = null;

                for (ResourceRepresentation resourceRepresentation :
                    new LinkedList<ResourceRepresentation>(resourceRepresentationList)) {

                  if (resourceRepresentation != null) {

                    resourceRepresentation.refreshRepresentation();
                    image = resourceRepresentation.getImage();

                    if (image != null) {

                      resourceRepresentationList.remove(resourceRepresentation);
                    }
                  }
                }

                canvas.removeGVTTreeRendererListener(this);
                canvas.stopProcessing();
                canvas.dispose();
              }
            };

        canvas.addGVTTreeRendererListener(gVTTreeRendererAdapter);

        // setting the document for the canvas
        canvas.setSVGDocument(doc);

        canvas.setBackground(Color.white);
        canvas.setBounds(1, 1, imageSize.width, imageSize.height);
      }
    }
  }
Example #22
0
  ///////////////////////////////////
  ////                          ////
  //// Valor por Extenso       ////
  ////                        ////
  ///////////////////////////////
  public static String valorPorExtenso(double vlr) {
    if (vlr == 0) {
      return ("zero");
    }

    long inteiro = (long) Math.abs(vlr); // parte inteira do valor
    double resto = vlr - inteiro; // parte fracionária do valor

    String vlrS = String.valueOf(inteiro);
    if (vlrS.length() > 15) {
      return ("Erro: valor superior a 999 trilhões.");
    }

    String s = "", saux, vlrP;
    String centavos = String.valueOf((int) Math.round(resto * 100));

    String[] unidade = {
      "",
      "um",
      "dois",
      "três",
      "quatro",
      "cinco",
      "seis",
      "sete",
      "oito",
      "nove",
      "dez",
      "onze",
      "doze",
      "treze",
      "quatorze",
      "quinze",
      "dezesseis",
      "dezessete",
      "dezoito",
      "dezenove"
    };
    String[] centena = {
      "",
      "cento",
      "duzentos",
      "trezentos",
      "quatrocentos",
      "quinhentos",
      "seiscentos",
      "setecentos",
      "oitocentos",
      "novecentos"
    };
    String[] dezena = {
      "",
      "",
      "vinte",
      "trinta",
      "quarenta",
      "cinquenta",
      "sessenta",
      "setenta",
      "oitenta",
      "noventa"
    };
    String[] qualificaS = {"", "mil", "milhão", "bilhão", "trilhão"};
    String[] qualificaP = {"", "mil", "milhões", "bilhões", "trilhões"};

    // definindo o extenso da parte inteira do valor
    int n, unid, dez, cent, tam, i = 0;
    boolean umReal = false, tem = false;
    while (!vlrS.equals("0")) {
      tam = vlrS.length();
      if (tam > 3) {
        vlrP = vlrS.substring(tam - 3, tam);
        vlrS = vlrS.substring(0, tam - 3);
      } else { // última parte do valor
        vlrP = vlrS;
        vlrS = "0";
      }
      if (!vlrP.equals("000")) {
        saux = "";
        if (vlrP.equals("100")) {
          saux = "cem";
        } else {
          n = Integer.parseInt(vlrP, 10); // para n = 371, tem-se:
          cent = n / 100; // cent = 3 (centena trezentos)
          dez = (n % 100) / 10; // dez  = 7 (dezena setenta)
          unid = (n % 100) % 10; // unid = 1 (unidade um)
          if (cent != 0) {
            saux = centena[cent];
          }
          if ((dez != 0) || (unid != 0)) {
            if ((n % 100) <= 19) {
              if (saux.length() != 0) {
                saux = saux + " e " + unidade[n % 100];
              } else {
                saux = unidade[n % 100];
              }
            } else {
              if (saux.length() != 0) {
                saux = saux + " e " + dezena[dez];
              } else {
                saux = dezena[dez];
              }
              if (unid != 0) {
                if (saux.length() != 0) {
                  saux = saux + " e " + unidade[unid];
                } else {
                  saux = unidade[unid];
                }
              }
            }
          }
        }
        if (vlrP.equals("1") || vlrP.equals("001")) {
          if (i == 0) // 1a. parte do valor (um real)
          {
            umReal = true;
          } else {
            saux = saux + " " + qualificaS[i];
          }
        } else if (i != 0) {
          saux = saux + " " + qualificaP[i];
        }
        if (s.length() != 0) {
          s = saux + ", " + s;
        } else {
          s = saux;
        }
      }
      if (((i == 0) || (i == 1)) && s.length() != 0) {
        tem = true; // tem centena ou mil no valor
      }
      i = i + 1; // próximo qualificador: 1- mil, 2- milhão, 3- bilhão, ...
    }

    if (s.length() != 0) {
      if (umReal) {
        s = s + " real";
      } else if (tem) {
        s = s + " reais";
      } else {
        s = s + " de reais";
      }
    }

    // definindo o extenso dos centavos do valor
    if (!centavos.equals("0")) { // valor com centavos
      if (s.length() != 0) // se não é valor somente com centavos
      {
        s = s + " e ";
      }
      if (centavos.equals("1")) {
        s = s + "um centavo";
      } else {
        n = Integer.parseInt(centavos, 10);
        if (n <= 19) {
          s = s + unidade[n];
        } else { // para n = 37, tem-se:
          unid = n % 10; // unid = 37 % 10 = 7 (unidade sete)
          dez = n / 10; // dez  = 37 / 10 = 3 (dezena trinta)
          s = s + dezena[dez];
          if (unid != 0) {
            s = s + " e " + unidade[unid];
          }
        }
        s = s + " centavos";
      }
    }
    return (s);
  }
Example #23
0
 /**
  * @param y data
  * @param k parameter giving the length 2 * k + 1 of the averaging interval
  * @param l oder of the averaging polynomial
  * @param p probability defining confidence limits
  */
 public TimeSeries(double[] y, int k, int l, double p) {
   this.y = y;
   this.k = k;
   this.l = l;
   this.p = p;
   n = y.length;
   eta = new double[n + 2 * k];
   coneta = new double[n + 2 * k];
   // quantile of Student's distribution
   pprime = 0.5 * (p + 1.);
   nf = 2 * k - l;
   talpha = StatFunct.quantileStudent(pprime, nf);
   // compute matrices depending on k and l
   k21 = 2 * k + 1;
   l1 = l + 1;
   a = new DatanMatrix(k21, l1);
   for (int i = 0; i < k21; i++) {
     for (int j = 0; j < l1; j++) {
       if (j == 0) a.setElement(i, j, -1.);
       else a.setElement(i, j, a.getElement(i, j - 1) * (double) (i - k));
     }
   }
   ata1 = a.multiplyTransposedWith(a);
   ata1.choleskyInversion();
   ata1at = ata1.multiplyWithTransposed(a);
   ata1at = ata1at.multiply(-1.);
   // moving averages and confidence limits for inner part
   ymat = new DatanMatrix(y);
   for (int i = 2 * k; i < n; i++) {
     ytmp = ymat.getSubmatrix(k21, 1, i - 2 * k, 0);
     x = ata1at.multiply(ytmp);
     eta[i] = x.getElement(0, 0);
     etatmp = a.multiply(x);
     etatmp = etatmp.add(ytmp);
     sy2 = etatmp.multiplyTransposedWith(etatmp);
     double s = sy2.getElement(0, 0) / (double) nf;
     double a0 = Math.sqrt(Math.abs(ata1.getElement(0, 0)));
     coneta[i] = a0 * Math.sqrt(s) * talpha;
     // moving averages and confidence limits for end sections
     if (i == 2 * k || i == n - 1) {
       tt = new double[l + 1];
       if (i == 2 * k) {
         iadd = 2 * k;
         is = -1;
       } else {
         iadd = n - 1;
         is = 1;
       }
       for (int i1 = 1; i1 <= 2 * k; i1++) {
         j = is * i1;
         for (int i2 = 0; i2 < l + 1; i2++) {
           for (int i3 = 0; i3 <= i2; i3++) {
             if (i3 == 0) tt[i2] = 1.;
             else tt[i2] = tt[i2] * (double) j;
           }
         }
         tmat = new DatanMatrix(tt);
         seta2 = tmat.multiplyTransposedWith(ata1.multiply(tmat));
         double se2 = s * seta2.getElement(0, 0);
         etai = tmat.multiplyTransposedWith(x);
         eta[iadd + j] = etai.getElement(0, 0);
         coneta[iadd + j] = Math.sqrt(Math.abs(se2)) * talpha;
       }
     }
   }
 }
Example #24
0
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.WHITE);
    // Draws a white arrow and the principal axis
    g.drawLine(0, 200, 700, 200);
    g.drawLine(arrow_x, 200, arrow_x, arrow_y2);

    // Show coordinates of arrow tip
    arrowCoordinate_x = arrow_x - startingPosition;
    arrowCoordinate_x /= 10;
    arrowCoordinate_y = 200 - arrow_y2;
    arrowCoordinate_y /= 10;

    // Coordinates
    Optics.lbl_arrowCoordinates.setText(
        "<html>(d<sub>o</sub>, h<sub>o</sub>) = ("
            + arrowCoordinate_x
            + ", "
            + arrowCoordinate_y
            + ")</html>");

    if (arrow_y2 < 200) // if arrow is above principal axis
    {
      g.drawLine(arrow_x, arrow_y2, arrow_x - 7, arrow_y2 + 7);
      g.drawLine(arrow_x, arrow_y2, arrow_x + 7, arrow_y2 + 7);
    } else if (arrow_y2 > 200) // if arrow is below principal axis
    {
      g.drawLine(arrow_x, arrow_y2, arrow_x - 7, arrow_y2 - 7);
      g.drawLine(arrow_x, arrow_y2, arrow_x + 7, arrow_y2 - 7);
    }
    // Draws lines for the grid
    if (lenses) startingPosition = 350;
    else {
      radiusOfCurvature = 20 * focalLength;
      if (type == 0) startingPosition = 500;
      else startingPosition = 350;
    }
    {
      for (int i = startingPosition; i <= 700; i += 10) {
        if ((i - startingPosition) % (10 * focalLength) == 0) {
          g.setColor(Color.ORANGE);
          g.drawLine(i, 195, i, 205);
        } else {
          g.setColor(Color.WHITE);
          g.drawLine(i, 197, i, 203);
        }
      }
      for (int i = startingPosition; i >= 0; i -= 10) {
        if ((i - startingPosition) % (10 * focalLength) == 0 && i != 0) {
          g.setColor(Color.ORANGE);
          g.drawLine(i, 195, i, 205);
        } else {
          g.setColor(Color.WHITE);
          g.drawLine(i, 197, i, 203);
        }
      }
    }
    g.setColor(Color.WHITE);

    if (lenses) {
      if (type == 0) // If Converging
      {
        // Draws a converging lens
        g.drawArc(340, 50, 40, 300, 120, 120);
        g.drawArc(320, 50, 40, 300, 60, -120);
        // draws horizontal line from the tip of the arrow to the lens (line 1/3)
        g.setColor(Color.RED);
        g.drawLine(arrow_x, arrow_y2, 350, arrow_y2);
        // calculates necessary information to form equation of line from lens to focal point (line
        // 2/3)

        dy_1 = 200 - arrow_y2;

        if (arrow_x > 350) dx_1 = -10 * focalLength;
        else dx_1 = 10 * focalLength;
        slope_1 = dy_1 / dx_1;

        if (arrow_x > 350) y_intercept_1 = 200 - slope_1 * (350 - 10 * focalLength);
        else y_intercept_1 = 200 - slope_1 * (10 * focalLength + 350);
        // Calculates coordinates of points on the edge of screen (endpoints)
        if (arrow_x <= 350)
          y_screenIntersection_1 = (int) (Math.round(slope_1 * 700 + y_intercept_1));
        else y_screenIntersection_1 = (int) (Math.round(y_intercept_1));
        if (slope_1 != 0)
          if (arrow_y2 <= 200)
            x_screenIntersection_1 = (int) (Math.round((400 - y_intercept_1) / slope_1));
          else x_screenIntersection_1 = (int) (Math.round(-y_intercept_1 / slope_1));
        if (x_screenIntersection_1 >= 0
            && x_screenIntersection_1 <= 700) // If endpoint is on the x-edge
        if (arrow_y2 <= 200) g.drawLine(350, arrow_y2, x_screenIntersection_1, 400);
          else g.drawLine(350, arrow_y2, x_screenIntersection_1, 0);
        else if (arrow_x > 350) g.drawLine(350, arrow_y2, 0, y_screenIntersection_1);
        else
          g.drawLine(350, arrow_y2, 700, y_screenIntersection_1); // Else: endpoint is on the y-edge
      } else // Else: Diverging
      {
        // Draws a diverging lens
        g.drawArc(360, 50, 40, 300, 120, 120);
        g.drawArc(300, 50, 40, 300, 60, -120);
        g.drawLine(330, 68, 370, 68);
        g.drawLine(330, 330, 370, 330);

        // draws horizontal line from the tip of the arrow to the lens (line 1/3)
        g.setColor(Color.RED);
        g.drawLine(arrow_x, arrow_y2, 350, arrow_y2);

        // calculates necessary information to form equation of line from lens to focal point (line
        // 2/3)

        dy_1 = arrow_y2 - 200;

        if (arrow_x > 350) dx_1 = -10 * focalLength;
        else dx_1 = 10 * focalLength;
        slope_1 = dy_1 / dx_1;

        if (arrow_x > 350) y_intercept_1 = 200 - slope_1 * (10 * focalLength + 350);
        else y_intercept_1 = 200 - slope_1 * (350 - 10 * focalLength);
        // Calculates coordinates of points on the edge of screen (endpoints)
        if (arrow_x <= 350)
          y_screenIntersection_1 = (int) (Math.round(slope_1 * 700 + y_intercept_1));
        else y_screenIntersection_1 = (int) (Math.round(y_intercept_1));
        if (slope_1 != 0)
          if (arrow_y2 <= 200)
            x_screenIntersection_1 = (int) (Math.round(-y_intercept_1 / slope_1));
          else x_screenIntersection_1 = (int) (Math.round((400 - y_intercept_1) / slope_1));
        if (x_screenIntersection_1 >= 0
            && x_screenIntersection_1 <= 700) // If endpoint is on the x-edge
        if (arrow_y2 <= 200) g.drawLine(350, arrow_y2, x_screenIntersection_1, 0);
          else g.drawLine(350, arrow_y2, x_screenIntersection_1, 400);
        else // Else: endpoint is on the y-edge
        if (arrow_x > 350) g.drawLine(350, arrow_y2, 0, y_screenIntersection_1);
        else g.drawLine(350, arrow_y2, 700, y_screenIntersection_1);
      }
      // Line 3/3
      dy_2 = 200 - arrow_y2;
      dx_2 = 350 - arrow_x;
      slope_2 = dy_2 / dx_2;
      y_intercept_2 = 200 - slope_2 * 350;
      if (arrow_x <= 350)
        y_screenIntersection_2 = (int) (Math.round(slope_2 * 700 + y_intercept_2));
      else y_screenIntersection_2 = (int) (Math.round(y_intercept_2));
      if (slope_2 != 0)
        if (arrow_y2 <= 200)
          x_screenIntersection_2 = (int) (Math.round((400 - y_intercept_2) / slope_2));
        else x_screenIntersection_2 = (int) (Math.round(-y_intercept_2 / slope_2));

      if (x_screenIntersection_2 >= 0
          && x_screenIntersection_2 <= 700) // If endpoint is on the x-edge
      if (arrow_y2 <= 200) g.drawLine(arrow_x, arrow_y2, x_screenIntersection_2, 400);
        else g.drawLine(arrow_x, arrow_y2, x_screenIntersection_2, 0);
      else if (arrow_x <= 350)
        g.drawLine(
            arrow_x, arrow_y2, 700, y_screenIntersection_2); // Else: endpoint is on the y-edge
      else g.drawLine(arrow_x, arrow_y2, 0, y_screenIntersection_2);

      // POI between Line 2 & Line 3
      x_pointOfIntersection = (int) ((y_intercept_2 - y_intercept_1) / (slope_1 - slope_2));
      y_pointOfIntersection = (int) (slope_1 * x_pointOfIntersection + y_intercept_1);
      // Draw image
      g.setColor(Color.ORANGE);
      g.drawLine(x_pointOfIntersection, 200, x_pointOfIntersection, y_pointOfIntersection);
      if (y_pointOfIntersection < 200) {
        g.drawLine(
            x_pointOfIntersection,
            y_pointOfIntersection,
            x_pointOfIntersection - 7,
            y_pointOfIntersection + 7);
        g.drawLine(
            x_pointOfIntersection,
            y_pointOfIntersection,
            x_pointOfIntersection + 7,
            y_pointOfIntersection + 7);
      } else {
        g.drawLine(
            x_pointOfIntersection,
            y_pointOfIntersection,
            x_pointOfIntersection - 7,
            y_pointOfIntersection - 7);
        g.drawLine(
            x_pointOfIntersection,
            y_pointOfIntersection,
            x_pointOfIntersection + 7,
            y_pointOfIntersection - 7);
      }
      // Same side image line continuation
      if (((x_pointOfIntersection > 350 && arrow_x > 350)
              || (x_pointOfIntersection < 350 && arrow_x < 350))
          && (arrow_x != 350 - 10 * focalLength && arrow_x != 350 + 10 * focalLength
              || type == 1)) {
        g.setColor(Color.YELLOW);
        g.drawLine(x_pointOfIntersection, y_pointOfIntersection, 350, arrow_y2);
        if (type == 0) g.drawLine(x_pointOfIntersection, y_pointOfIntersection, arrow_x, arrow_y2);
      }

      // Mag calculations
      height_image = 200 - y_pointOfIntersection;
      height_object = 200 - arrow_y2;
      if (height_object != 0) magnification = height_image / height_object;

      if (magnification <= 9999 && magnification >= -9999)
        Optics.txt_magnification.setText("" + roundTwoDecimals(magnification));
      else if (magnification > 9999) {
        magnification = Double.POSITIVE_INFINITY;
        Optics.txt_magnification.setText("N/A");
      } else {
        magnification = Double.NEGATIVE_INFINITY;
        Optics.txt_magnification.setText("N/A");
      }
      // Characteristics
      g.setColor(Color.ORANGE);
      g.drawString("Image Characteristics:", 20, 300);
      if (type == 0) {
        if ((Math.abs(magnification) > 1 && Math.abs(magnification) < 9999))
          g.drawString("Magnification:  Enlarged", 20, 320);
        else if (arrow_x == 350 - 20 * focalLength
            || arrow_x == 350 + 20 * focalLength
            || (int) (Math.abs(magnification)) == 1) g.drawString("Magnification:  None", 20, 320);
        else if (Math.abs(magnification) < 1 && Math.abs(magnification) > 0)
          g.drawString("Magnification:  Diminished", 20, 320);
        else g.drawString("Magnification:  N/A", 20, 320);
        if (arrow_x == 350 - 10 * focalLength || arrow_x == 350 + 10 * focalLength)
          g.drawString("Orientation:      N/A", 20, 335);
        else if ((arrow_y2 < 200 && y_pointOfIntersection < 200)
            || (arrow_y2 > 200 && y_pointOfIntersection > 200))
          g.drawString("Orientation:      Upright", 20, 335);
        else g.drawString("Orientation:      Inverted", 20, 335);
        if (arrow_x == 350 - 10 * focalLength || arrow_x == 350 + 10 * focalLength)
          g.drawString("Type:                 N/A", 20, 350);
        else if ((x_pointOfIntersection < 350 && arrow_x < 350)
            || (x_pointOfIntersection > 350 && arrow_x > 350))
          g.drawString("Type:                 Virtual", 20, 350);
        else g.drawString("Type:                 Real", 20, 350);
      } else {
        g.drawString("Magnification:  Diminished", 20, 320);
        g.drawString("Orientation:      Upright", 20, 335);
        g.drawString("Type:                 Virtual", 20, 350);
      }

      height_image /= 10;

      if (height_image > 9999 || height_image < -9999)
        Optics.lbl_heightImage.setText("<html>h<sub>i</sub>= N/A</html>");
      else Optics.lbl_heightImage.setText("<html>h<sub>i</sub>= " + height_image + "</html>");

      distance_image = x_pointOfIntersection - 350;
      distance_image /= 10;
      if (distance_image > 9999 || distance_image < -9999)
        Optics.lbl_distanceImage.setText("<html>d<sub>i</sub>= N/A</html>");
      else Optics.lbl_distanceImage.setText("<html>d<sub>i</sub>= " + distance_image + "</html>");
    } else // Else: mirrors
    {

      if (type == 0) // If converging
      {
        // draws converging mirror
        g.drawArc(
            500 - 2 * radiusOfCurvature,
            200 - radiusOfCurvature,
            2 * radiusOfCurvature,
            2 * radiusOfCurvature,
            60,
            -120);
        // draws horizontal line from the tip of the arrow to the lens (line 1/4)
        g.setColor(Color.RED);
        x_arcIntersection_1 =
            (int)
                ((Math.sqrt(Math.abs(Math.pow(radiusOfCurvature, 2) - Math.pow(arrow_y2 - 200, 2))))
                    + (500 - radiusOfCurvature));
        g.drawLine(arrow_x, arrow_y2, x_arcIntersection_1, arrow_y2);

        // line 2/4
        dy_1 = arrow_y2 - 200;
        dx_1 = x_arcIntersection_1 - (500 - focalLength * 10);
        slope_1 = dy_1 / dx_1;
        y_intercept_1 = 200 - slope_1 * (500 - focalLength * 10);

        // Calculates coordinates of points on the edge of screen (endpoints)
        y_screenIntersection_1 = (int) (Math.round(y_intercept_1));
        if (slope_1 != 0)
          if (arrow_y2 <= 200)
            x_screenIntersection_1 = (int) (Math.round((400 - y_intercept_1) / slope_1));
          else x_screenIntersection_1 = (int) (Math.round(-y_intercept_1 / slope_1));
        if (x_screenIntersection_1 >= 0
            && x_screenIntersection_1 <= 700) // If endpoint is on the x-edge
        if (arrow_y2 <= 200) g.drawLine(x_arcIntersection_1, arrow_y2, x_screenIntersection_1, 400);
          else g.drawLine(x_arcIntersection_1, arrow_y2, x_screenIntersection_1, 0);
        else
          g.drawLine(
              x_arcIntersection_1,
              arrow_y2,
              0,
              y_screenIntersection_1); // Else: endpoint is on the y-edge
        // line 3/4
        if (!(arrow_x > 495 - focalLength * 10 && arrow_x < 505 - focalLength * 10)) {
          dy_2 = 200 - arrow_y2;
          dx_2 = (500 - 10 * focalLength) - arrow_x;
          slope_2 = dy_2 / dx_2;
          y_intercept_2 = arrow_y2 - slope_2 * arrow_x;
          quadratic_a = (float) (Math.pow(slope_2, 2) + 1);
          quadratic_b =
              (float)
                  (((2 * slope_2 * y_intercept_2)
                      - (400 * slope_2)
                      + ((radiusOfCurvature - 500) * 2)));
          quadratic_c =
              (float)
                  ((Math.pow(y_intercept_2, 2)
                      - Math.pow(radiusOfCurvature, 2)
                      - (400 * y_intercept_2)
                      + 40000
                      + Math.pow((radiusOfCurvature - 500), 2)));
          discriminant = (float) (Math.pow(quadratic_b, 2) - (4 * quadratic_a * quadratic_c));
          if (discriminant >= 0)
            x_arcIntersection_2 =
                (int)
                    (Math.max(
                        ((-quadratic_b + Math.sqrt(discriminant)) / (2 * quadratic_a)),
                        ((-quadratic_b - Math.sqrt(discriminant)) / (2 * quadratic_a))));
          else System.out.println("Error, imaginary root!");
          y_arcIntersection_2 = (int) (slope_2 * x_arcIntersection_2 + y_intercept_2);
          g.drawLine(arrow_x, arrow_y2, x_arcIntersection_2, y_arcIntersection_2);
          // System.out.println ("slope: " + slope_2 + "\n yintercept: " + y_intercept_2 + "\n
          // quadratic-a: " + quadratic_a + "\n quadratic-b: " + quadratic_b + "\n quadratic_c: " +
          // quadratic_c + "\n discriminant: " + discriminant + "\n xarcintersection2: " +
          // x_arcIntersection_2 + "\n yarcintersection2: " + y_arcIntersection_2);
          // line 4/4
          g.drawLine(x_arcIntersection_2, y_arcIntersection_2, 0, y_arcIntersection_2);

          // POI between line 2 and line 4
          x_pointOfIntersection = (int) ((y_arcIntersection_2 - y_intercept_1) / slope_1);
          y_pointOfIntersection = y_arcIntersection_2;
          g.setColor(Color.ORANGE);
          g.drawLine(x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection, 200);

          if (y_pointOfIntersection < 200) {
            g.drawLine(
                x_pointOfIntersection,
                y_pointOfIntersection,
                x_pointOfIntersection - 7,
                y_pointOfIntersection + 7);
            g.drawLine(
                x_pointOfIntersection,
                y_pointOfIntersection,
                x_pointOfIntersection + 7,
                y_pointOfIntersection + 7);
          } else {
            g.drawLine(
                x_pointOfIntersection,
                y_pointOfIntersection,
                x_pointOfIntersection - 7,
                y_pointOfIntersection - 7);
            g.drawLine(
                x_pointOfIntersection,
                y_pointOfIntersection,
                x_pointOfIntersection + 7,
                y_pointOfIntersection - 7);
          }
          // Same side image line continuation
          if (arrow_x > 500 - 10 * focalLength) {
            g.setColor(Color.YELLOW);
            g.drawLine(x_pointOfIntersection, y_pointOfIntersection, x_arcIntersection_1, arrow_y2);
            g.drawLine(
                x_pointOfIntersection,
                y_pointOfIntersection,
                x_arcIntersection_2,
                y_arcIntersection_2);
          }
        }
      } else // Diverging
      {
        // draws converging mirror
        g.drawArc(
            350, 200 - radiusOfCurvature, 2 * radiusOfCurvature, 2 * radiusOfCurvature, 120, 120);
        // draws horizontal line from the tip of the arrow to the lens (line 1/4)
        g.setColor(Color.RED);
        x_arcIntersection_1 =
            (int)
                (-(Math.sqrt(Math.pow(radiusOfCurvature, 2) - Math.pow(arrow_y2 - 200, 2)))
                    + (350 + radiusOfCurvature));
        g.drawLine(arrow_x, arrow_y2, x_arcIntersection_1, arrow_y2);

        // line 2/4
        dy_1 = arrow_y2 - 200;
        dx_1 = x_arcIntersection_1 - (350 + focalLength * 10);
        slope_1 = dy_1 / dx_1;
        y_intercept_1 = 200 - slope_1 * (350 + focalLength * 10);

        // Calculates coordinates of points on the edge of screen (endpoints)
        y_screenIntersection_1 = (int) (Math.round(y_intercept_1));
        if (slope_1 != 0)
          if (arrow_y2 <= 200)
            x_screenIntersection_1 = (int) (Math.round(-y_intercept_1 / slope_1));
          else if (arrow_y2 > 200)
            x_screenIntersection_1 = (int) (Math.round(400 - y_intercept_1 / slope_1));
        if (x_screenIntersection_1 >= 0
            && x_screenIntersection_1 <= 700) // If endpoint is on the x-edge
        if (arrow_y2 <= 200) g.drawLine(x_arcIntersection_1, arrow_y2, x_screenIntersection_1, 0);
          else g.drawLine(x_arcIntersection_1, arrow_y2, x_screenIntersection_1, 400);
        else
          g.drawLine(
              x_arcIntersection_1,
              arrow_y2,
              0,
              y_screenIntersection_1); // Else: endpoint is on the y-edge
        // line 3/4

        dy_2 = 200 - arrow_y2;
        dx_2 = (350 + 10 * focalLength) - arrow_x;
        slope_2 = dy_2 / dx_2;
        y_intercept_2 = arrow_y2 - slope_2 * arrow_x;
        quadratic_a = (float) (Math.pow(slope_2, 2) + 1);
        quadratic_b =
            (float)
                ((2 * slope_2 * y_intercept_2) - (400 * slope_2) - (2 * radiusOfCurvature + 700));
        quadratic_c =
            (float)
                ((Math.pow(y_intercept_2, 2)
                    - Math.pow(radiusOfCurvature, 2)
                    - (400 * y_intercept_2)
                    + 40000
                    + Math.pow((radiusOfCurvature + 350), 2)));
        discriminant = (float) (Math.pow(quadratic_b, 2) - (4 * quadratic_a * quadratic_c));
        if (discriminant >= 0)
          x_arcIntersection_2 =
              (int)
                  (Math.min(
                      ((-quadratic_b + Math.sqrt(discriminant)) / (2 * quadratic_a)),
                      ((-quadratic_b - Math.sqrt(discriminant)) / (2 * quadratic_a))));
        else System.out.println("Error, imaginary root!");
        y_arcIntersection_2 = (int) (slope_2 * x_arcIntersection_2 + y_intercept_2);
        g.drawLine(arrow_x, arrow_y2, x_arcIntersection_2, y_arcIntersection_2);
        // System.out.println ("slope: " + slope_2 + "\n yintercept: " + y_intercept_2 + "\n
        // quadratic-a: " + quadratic_a + "\n quadratic-b: " + quadratic_b + "\n quadratic_c: " +
        // quadratic_c + "\n discriminant: " + discriminant + "\n xarcintersection2: " +
        // x_arcIntersection_2 + "\n yarcintersection2: " + y_arcIntersection_2);
        // line 4/4
        g.drawLine(x_arcIntersection_2, y_arcIntersection_2, 0, y_arcIntersection_2);

        // POI between line 2 and line 4
        x_pointOfIntersection = (int) ((y_arcIntersection_2 - y_intercept_1) / slope_1);
        y_pointOfIntersection = y_arcIntersection_2;
        g.setColor(Color.ORANGE);
        g.drawLine(x_pointOfIntersection, y_pointOfIntersection, x_pointOfIntersection, 200);

        if (y_pointOfIntersection < 200) {
          g.drawLine(
              x_pointOfIntersection,
              y_pointOfIntersection,
              x_pointOfIntersection - 7,
              y_pointOfIntersection + 7);
          g.drawLine(
              x_pointOfIntersection,
              y_pointOfIntersection,
              x_pointOfIntersection + 7,
              y_pointOfIntersection + 7);
        } else {
          g.drawLine(
              x_pointOfIntersection,
              y_pointOfIntersection,
              x_pointOfIntersection - 7,
              y_pointOfIntersection - 7);
          g.drawLine(
              x_pointOfIntersection,
              y_pointOfIntersection,
              x_pointOfIntersection + 7,
              y_pointOfIntersection - 7);
        }
        // Same side image line continuation
        g.setColor(Color.YELLOW);
        g.drawLine(x_pointOfIntersection, y_pointOfIntersection, x_arcIntersection_1, arrow_y2);
        g.drawLine(
            x_pointOfIntersection, y_pointOfIntersection, x_arcIntersection_2, y_arcIntersection_2);
      }

      // Mag calculations
      height_image = 200 - y_pointOfIntersection;
      height_object = 200 - arrow_y2;
      if (height_object != 0) magnification = height_image / height_object;

      if (magnification <= 9999 && magnification >= -9999)
        Optics.txt_magnification.setText("" + roundTwoDecimals(magnification));
      else if (magnification > 9999) {
        magnification = Double.POSITIVE_INFINITY;
        Optics.txt_magnification.setText("N/A");
      } else {
        magnification = Double.NEGATIVE_INFINITY;
        Optics.txt_magnification.setText("N/A");
      }
      // Characteristics
      g.setColor(Color.ORANGE);
      g.drawString("Image Characteristics:", 20, 300);
      if (type == 0) {

        if ((Math.abs(magnification) > 1 && Math.abs(magnification) < 9999)
            && arrow_x != 500 - 10 * focalLength) g.drawString("Magnification:  Enlarged", 20, 320);
        else if ((int) (Math.abs(magnification)) == 1)
          g.drawString("Magnification:  None", 20, 320);
        else if (Math.abs(magnification) < 1 && Math.abs(magnification) > 0)
          g.drawString("Magnification:  Diminished", 20, 320);
        else {
          g.drawString("Magnification:  N/A", 20, 320);
          Optics.txt_magnification.setText("N/A");
          Optics.lbl_distanceImage.setText("<html>d<sub>i</sub>= N/A</html>");
          Optics.lbl_heightImage.setText("<html>h<sub>i</sub>= N/A</html>");
        }
        if (arrow_x == 500 - 10 * focalLength) g.drawString("Orientation:      N/A", 20, 335);
        else if ((arrow_y2 < 200 && y_pointOfIntersection < 200)
            || (arrow_y2 > 200 && y_pointOfIntersection > 200))
          g.drawString("Orientation:      Upright", 20, 335);
        else g.drawString("Orientation:      Inverted", 20, 335);
        if (arrow_x == 500 - 10 * focalLength) g.drawString("Type:                 N/A", 20, 350);
        else if (x_pointOfIntersection < 500 && arrow_x < 500)
          g.drawString("Type:                 Real", 20, 350);
        else if (x_pointOfIntersection > 500 && arrow_x < 500)
          g.drawString("Type:                 Virtual", 20, 350);
      } else {
        g.drawString("Magnification:  Diminished", 20, 320);
        g.drawString("Orientation:      Upright", 20, 335);
        g.drawString("Type:                 Virtual", 20, 350);
      }

      height_image /= 10;

      if (height_image > 9999 || height_image < -9999 || arrow_x == 500 - 10 * focalLength)
        Optics.lbl_heightImage.setText("<html>h<sub>i</sub>= N/A</html>");
      else Optics.lbl_heightImage.setText("<html>h<sub>i</sub>= " + height_image + "</html>");
      if (type == 0) distance_image = x_pointOfIntersection - 500;
      else distance_image = x_pointOfIntersection - 350;
      distance_image /= 10;
      if (distance_image > 9999 || distance_image < -9999 || arrow_x == 500 - 10 * focalLength)
        Optics.lbl_distanceImage.setText("<html>d<sub>i</sub>= N/A</html>");
      else Optics.lbl_distanceImage.setText("<html>d<sub>i</sub>= " + distance_image + "</html>");
    }
  }
Example #25
0
  private void geterrors() {
    GenericDialog gd = new GenericDialog("Options");
    float conf = 0.67f;
    gd.addNumericField("Confidence Limit", (int) (conf * 100.0f), 5, 10, null);
    gd.addChoice("Error Parameter", paramsnames, paramsnames[0]);
    double spacing = 0.01;
    gd.addNumericField("Chi^2 plot spacing (% of value)?", spacing * 100.0, 2, 10, null);
    boolean globalerror = false;
    gd.addCheckbox("Global Fit Error?", globalerror);
    int dataset = 0;
    gd.addNumericField("Data Set (for Global Error)", dataset, 0);
    gd.showDialog();
    if (gd.wasCanceled()) {
      return;
    }
    conf = 0.01f * (float) gd.getNextNumber();
    int paramindex = (int) gd.getNextChoiceIndex();
    spacing = 0.01 * gd.getNextNumber();
    globalerror = gd.getNextBoolean();
    dataset = (int) gd.getNextNumber();

    if (globalerror) {
      support_plane_errors erclass = new support_plane_errors(this, 0.0001, 50, true, 0.1);
      int[] erindeces = {paramindex, dataset};
      // need to set up all the matrices
      int nsel = 0;
      int nparams = 11;
      for (int i = 0; i < ncurves; i++) {
        if (include[i]) {
          nsel++;
        }
      }
      double[][] params = new double[nsel][nparams];
      String[][] tempformulas = new String[nsel][nparams];
      double[][][] constraints = new double[2][nsel][nparams];
      int[][] vflmatrix = new int[nsel][nparams];

      float[][] tempdata = new float[nsel][xpts * ypts];
      float[][] tempweights = new float[nsel][xpts * ypts];

      int nfit = 0;
      int counter = 0;
      for (int i = 0; i < ncurves; i++) {
        if (include[i]) {
          for (int j = 0; j < nparams; j++) {
            params[counter][j] = globalparams[i][j];
            tempformulas[counter][j] = globalformulas[i][j];
            constraints[0][counter][j] = globalconstraints[0][i][j];
            constraints[1][counter][j] = globalconstraints[1][i][j];
            vflmatrix[counter][j] = globalvflmatrix[i][j];
            if (vflmatrix[counter][j] == 0 || (j == 0 && vflmatrix[counter][j] == 2)) {
              nfit++;
            }
          }
          for (int j = 0; j < xpts; j++) {
            for (int k = 0; k < ypts; k++) {
              tempdata[counter][j + k * xpts] = (float) ((double) pch[i][j][k] / (double) nmeas[i]);
              tempweights[counter][j + k * xpts] = weights[i][j][k];
            }
          }
          counter++;
        }
      }
      int dofnum = xpts * ypts * nsel - (nfit - 1) - 1;
      int dofden = xpts * ypts * nsel - nfit - 1;
      // double flim=FLimit(dofnum,dofden,(double)conf);
      double flim = (new jdist()).FLimit(dofnum, dofden, (double) conf);
      IJ.log("FLimit = " + (float) flim);
      if (flim == Double.NaN && flim < 1.0) {
        IJ.showMessage("Invalid Limiting F Value");
        return;
      }
      double truespacing = Math.abs(params[erindeces[1]][erindeces[0]] * spacing);
      double[][] c2plot =
          erclass.geterrorsglobal(
              params,
              vflmatrix,
              tempformulas,
              paramsnames,
              constraints,
              tempdata,
              tempweights,
              flim,
              truespacing,
              erindeces);
      IJ.log("upper limit = " + c2plot[1][0] + " lower limit = " + c2plot[0][0]);
      int templength = c2plot[0].length;
      float[][] c2plotf = new float[2][templength - 1];
      for (int i = 0; i < (templength - 1); i++) {
        c2plotf[0][i] = (float) c2plot[0][i + 1];
        c2plotf[1][i] = (float) c2plot[1][i + 1];
      }
      new PlotWindow4(
              "c2 plot",
              paramsnames[paramindex] + "[" + dataset + "]",
              "Chi^2",
              c2plotf[0],
              c2plotf[1])
          .draw();
    } else {
      support_plane_errors erclass = new support_plane_errors(this, 0.0001, 50, false, 0.1);
      int errindex = paramindex;

      float[] tempdata = new float[xpts * ypts];
      float[] tempweights = new float[xpts * ypts];
      for (int i = 0; i < xpts; i++) {
        for (int j = 0; j < ypts; j++) {
          tempdata[i + j * xpts] = (float) ((double) avg[i][j] / (double) nmeas[ncurves]);
          tempweights[i + j * xpts] = avgweights[i][j];
        }
      }

      int nfit = 0;
      for (int i = 0; i < 7; i++) {
        if (avgfixes[i] == 0) {
          nfit++;
        }
      }
      int dofnum = xpts * ypts - (nfit - 1) - 1;
      int dofden = xpts * ypts - nfit - 1;
      double flim = (new jdist()).FLimit(dofnum, dofden, (double) conf);
      IJ.log("FLimit = " + (float) flim);
      if (flim == Double.NaN && flim < 1.0) {
        IJ.showMessage("Invalid Limiting F Value");
        return;
      }
      double truespacing = Math.abs(avgparams[errindex] * spacing);
      double[][] c2plot =
          erclass.geterrors(
              avgparams,
              avgfixes,
              avgconstraints,
              tempdata,
              tempweights,
              flim,
              truespacing,
              errindex);
      IJ.log("upper limit = " + c2plot[1][0] + " lower limit = " + c2plot[0][0]);
      int templength = c2plot[0].length;
      float[][] c2plotf = new float[2][templength - 1];
      for (int i = 0; i < (templength - 1); i++) {
        c2plotf[0][i] = (float) c2plot[0][i + 1];
        c2plotf[1][i] = (float) c2plot[1][i + 1];
      }
      new PlotWindow4("c2 plot", paramsnames[errindex], "Chi^2", c2plotf[0], c2plotf[1]).draw();
    }
  }
Example #26
0
  /** main method - entry point for the entire program */
  public static void main(String[] args)
      throws IOException // just let IOExceptions terminate the program
      {
    // initialize loan variables from constants
    final double principal = PRINCIPAL;
    final double rate = RATE / 100; // convert rate into decimal form
    final double numPayments = TERM * MONTHS_PER_YEAR;

    // create output and input objects
    final PrintStream out = System.out;
    final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    // display the header for this assignment
    out.println("Name            : David C. Gibbons   ");
    out.println("Assignment      : Workshop 3         ");
    out.println("-------------------------------------");

    // determine interest rate per month
    final double monthlyRate = (rate / MONTHS_PER_YEAR);

    // calculate monthly payment
    final double monthlyPayment =
        principal * (monthlyRate / (1 - Math.pow(1 + monthlyRate, -numPayments)));

    // fetch needed decimal formatters needed for output
    final DecimalFormat numberFmt = new DecimalFormat("#0");
    final DecimalFormat currencyFmt = new DecimalFormat("$0.00");
    final DecimalFormat percentFmt = new DecimalFormat("0.00 %");

    // display overall loan information
    out.println("Principal       : " + currencyFmt.format(principal));
    out.println("Interest Rate   : " + percentFmt.format(rate));
    out.println("# of payments   : " + numberFmt.format(numPayments));
    out.println("Monthly payment : " + currencyFmt.format(monthlyPayment));

    // wait for the user to continue and then display the
    // details of all the payments
    out.println();
    out.println("Hit Enter to list Payment Detail");
    in.readLine();

    // calculate the payment detail in yearly blocks
    double currentPrincipal = principal;
    for (int month = 0; month < numPayments; month++) {
      // display header to match the benchmark at the start of the year
      if (month == 0 || (month % MONTHS_PER_YEAR) == 0) {
        // display a pause prompt if this isn't the first year
        if (month > 0) {
          out.println();
          out.println(" Hit Enter to continue");
          in.readLine();
        }
        out.println();
        out.println("\tInterest  Principal     Principal");
        out.println("Months\tPayment   Payment       Balance");
        out.println();
      }

      // calculate this month's interest payment and then the
      // principal payment and remaining principal balance
      double interestPayment = rate / MONTHS_PER_YEAR * currentPrincipal;
      double principalPayment = monthlyPayment - interestPayment;

      // always get the absolute value of the current principal as
      // sometimes the final value of 0 can be -0.0
      currentPrincipal = Math.abs(currentPrincipal - principalPayment);

      // format the fields and display to match benchmark
      out.print(numberFmt.format(month + 1) + " \t");
      out.print(currencyFmt.format(interestPayment) + "\t  ");
      out.print(currencyFmt.format(principalPayment) + "\t");
      out.println(currencyFmt.format(currentPrincipal));
    }
  }
  private double test(List baseline, List preferred, List gold) {
    double bs = 0, ps = 0;
    if (stat.toUpperCase().equals("F1")) {
      bs = new Evaluator(gold, baseline).getF1();
      ps = new Evaluator(gold, preferred).getF1();
    } else if (stat.toUpperCase().equals("P")) {
      bs = new Evaluator(gold, baseline).getPrecision();
      ps = new Evaluator(gold, preferred).getPrecision();
    } else if (stat.toUpperCase().equals("R")) {
      bs = new Evaluator(gold, baseline).getRecall();
      ps = new Evaluator(gold, preferred).getRecall();
    }
    double d = Math.abs(ps - bs);
    double mean = 0;
    double variance = 0;
    double sum = 0;
    double ssum = 0;
    logger.info(
        stat
            + ": original score bs, ps,d: "
            + formatter.format(bs * 100)
            + "%, "
            + formatter.format(ps * 100)
            + "%, "
            + formatter.format(d * 100)
            + "%");

    // p - p-value. In general, the lowest the p-value,
    // the less probable it is that that the null
    // hypothesis holds. That is, the two systems are
    // are significantly different.

    double p = 0;

    // c - number of times that the pseudostatistic is
    // greater or equal to the true statistic
    int c = 0;
    for (int i = 0; i < iterations; i++) {
      List baselineCopy = copy(baseline);
      List preferredCopy = copy(preferred);

      swap(baselineCopy, preferredCopy, new Random(i * 27));

      if (stat.toUpperCase().equals("F1")) {
        bs = new Evaluator(gold, baselineCopy).getF1();
        ps = new Evaluator(gold, preferredCopy).getF1();
      } else if (stat.toUpperCase().equals("P")) {
        bs = new Evaluator(gold, baselineCopy).getPrecision();
        ps = new Evaluator(gold, preferredCopy).getPrecision();
      } else if (stat.toUpperCase().equals("R")) {
        bs = new Evaluator(gold, baselineCopy).getRecall();
        ps = new Evaluator(gold, preferredCopy).getRecall();
      }

      double di = Math.abs(ps - bs);
      sum += di;
      ssum += Math.pow(di, 2);
      if (di >= d) {
        c++;

        // logger.info("score at " + i + " c, bs, ps,d: " + c + ", " + formatter.format(bs * 100) +
        // "%, " + formatter.format(ps * 100) + "%, " + formatter.format(di * 100) + "%, (" +
        // formatter.format(d * 100) + "%)");
      }
    } // end for i

    mean = sum / iterations;
    variance = (iterations * ssum - Math.pow(sum, 2)) / iterations * (iterations - 1);

    p = (double) (c + 1) / (iterations + 1);
    logger.info("mean " + formatter.format(mean) + ", " + formatter.format(Math.sqrt(variance)));
    logger.info(p + " = (" + c + " + 1) / (" + iterations + " +  1)");

    return p;
  } // end test