Пример #1
0
 public void toggleShowMeasurements() {
   if (showMeasurements.isSelected()) {
     measurements.setStructures(currentNucId, currentStructureIdx);
     measurements.setObjects(list.getSelectedValues());
     this.container.add(measurements);
   } else this.container.remove(measurements);
   core.refreshDisplay();
 }
Пример #2
0
 public void hide(boolean refresh) {
   container.remove(layout);
   if (showMeasurements.isSelected()) {
     container.remove(measurements);
     showMeasurements.setSelected(false);
   }
   if (refresh) core.refreshDisplay();
 }
Пример #3
0
 private void setSortKeys() {
   if (currentChannels != null && currentChannels.length == 1) {
     MeasurementKey mkey =
         new MeasurementKey(new int[] {currentChannels[0].getIdx()}, MeasurementObject.Number);
     System.out.println("Query:" + mkey.toString());
     ((ObjectManagerLayout) layout).setKeys(Core.getExperiment().getKeys().get(mkey));
   } else {
     ((ObjectManagerLayout) layout).unableSortKeys();
   }
 }
Пример #4
0
 public void startThreads() {
   directTransferThread.start();
   persistentQueue.startThreads();
   final TimerTask task =
       new TimerTask() {
         @Override
         public void run() {
           maybeStartRequests();
         }
       };
   Core.schedule(task, 3000, 3000);
 }
  public void templateMatching() {
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    int match_method = 5;
    int max_Trackbar = 5;
    Mat data = Highgui.imread("images/training_data/1" + "/data (" + 1 + ").jpg");
    Mat temp = Highgui.imread("images/template.jpg");
    Mat img = data.clone();

    int result_cols = img.cols() - temp.cols() + 1;
    int result_rows = img.rows() - temp.rows() + 1;
    Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);

    Imgproc.matchTemplate(img, temp, result, match_method);
    Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());

    double minVal;
    double maxVal;
    Point minLoc;
    Point maxLoc;
    Point matchLoc;
    // minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
    Core.MinMaxLocResult res = Core.minMaxLoc(result);

    if (match_method == Imgproc.TM_SQDIFF || match_method == Imgproc.TM_SQDIFF_NORMED) {
      matchLoc = res.minLoc;
    } else {
      matchLoc = res.maxLoc;
    }

    // / Show me what you got
    Core.rectangle(
        img,
        matchLoc,
        new Point(matchLoc.x + temp.cols(), matchLoc.y + temp.rows()),
        new Scalar(0, 255, 0));

    // Save the visualized detection.
    Highgui.imwrite("images/samp.jpg", img);
  }
Пример #6
0
 @Subroutine("read-from-string")
 public static LispList readFromString(
     LispString string,
     @Optional @Nullable LispObject start,
     @Optional @Nullable LispObject finish) {
   int begin = getInt(start, 0);
   int end = getInt(finish, string.size());
   try {
     String code = string.getData().substring(begin, end);
     ForwardParser forwardParser = new ForwardParser();
     LispObject read = Core.thisOrNil(forwardParser.parseLine(code));
     return LispList.cons(read, new LispInteger(begin + forwardParser.getCurrentIndex()));
   } catch (StringIndexOutOfBoundsException e) {
     throw new ArgumentOutOfRange(string, begin, end);
   }
 }
  public static Mat getCCH(Mat image) {
    ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Mat hierarchy = new Mat();
    Imgproc.findContours(
        image, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);

    Mat chainHistogram = Mat.zeros(1, 8, CvType.CV_32F);
    int n = 0;
    MatOfPoint2f approxCurve = new MatOfPoint2f();
    for (MatOfPoint contour : contours) {

      // get the freeman chain code from the contours
      int rows = contour.rows();
      // System.out.println("\nrows"+rows+"\n"+contour.dump());
      int direction = 7;
      Mat prevPoint = contours.get(0).row(0);
      n += rows - 1;
      for (int i = 1; i < rows; i++) {
        // get the current point
        double x1 = contour.get(i - 1, 0)[1];
        double y1 = contour.get(i - 1, 0)[0];

        // get the second point
        double x2 = contour.get(i, 0)[1];
        double y2 = contour.get(i, 0)[0];

        if (x2 == x1 && y2 == y1 + 1) direction = 0;
        else if (x2 == x1 - 1 && y2 == y1 + 1) direction = 1;
        else if (x2 == x1 - 1 && y2 == y1) direction = 2;
        else if (x2 == x1 - 1 && y2 == y1 - 1) direction = 3;
        else if (x2 == x1 && y2 == y1 - 1) direction = 4;
        else if (x2 == x1 + 1 && y2 == y1 - 1) direction = 5;
        else if (x2 == x1 + 1 && y2 == y1) direction = 6;
        else if (x2 == x1 + 1 && y2 == y1 + 1) direction = 7;
        else System.out.print("err");
        double counter = chainHistogram.get(0, direction)[0];
        chainHistogram.put(0, direction, ++counter);
        System.out.print(direction);
      }
    }
    System.out.println("\n" + chainHistogram.dump());
    Scalar alpha = new Scalar(n); // the factor
    Core.divide(chainHistogram, alpha, chainHistogram);
    System.out.println("\nrows=" + n + " " + chainHistogram.dump());
    return chainHistogram;
  }
Пример #8
0
 private void sort(String key, Object3DGui[] objectsGui, int structureIdx) {
   Object3DGui.setAscendingOrger(((ObjectManagerLayout) layout).getAscendingOrder());
   HashMap<Integer, BasicDBObject> objects =
       Core.getExperiment().getConnector().getObjects(currentNucId, structureIdx);
   boolean notFound = false;
   for (Object3DGui o : objectsGui) {
     BasicDBObject dbo = objects.get(o.getLabel());
     if (dbo != null) {
       if (dbo.containsField(key)) o.setValue(dbo.getDouble(key));
       else {
         o.setValue(-1);
         notFound = true;
       }
     }
   }
   if (notFound)
     ij.IJ.log("Warning measurement: " + key + " not found for one or several objects");
   Arrays.sort(objectsGui);
 }
Пример #9
0
  public void rejudgeProblem(String problemID) {
    SubmissionManager submissionManager = new SubmissionManager();

    for (Map<String, String> ent : submissionManager.rejudge(problemID)) {
      try {
        ProblemManager problemManager = new ProblemManager();
        Map<String, String> pb = problemManager.getProblemById(problemID);
        JSONObject msg = new JSONObject();
        msg.put("msg_type", "submit");
        msg.put("submission_id", ent.get("submission_id"));
        msg.put("problem_id", ent.get("problem_id"));
        msg.put("language", ent.get("language"));
        msg.put("source_code", ent.get("source_code"));
        msg.put("time_stamp", ent.get("submission_time_stamp"));
        msg.put("testdata_time_stamp", pb.get("time_stamp"));
        Core.getInstance().getScheduler().add(msg);
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }
Пример #10
0
 @Subroutine("current-message")
 public static LispObject currentMessage() {
   return Core.thisOrNil(myCurrentMessage);
 }
Пример #11
0
  /**
   * Determines where captured pieces are
   *
   * @param in Mat image of the board
   */
  public void findCaptured(Mat in) {
    int vsegment = in.rows() / 8; // only accounts 8 playable
    int hsegment = in.cols() / 12; // 8 playable, 2 capture, 2 extra
    int offset; // offset for playable board

    int capSquares = 12; // number of capture squares
    int rowNum = 1; // starting row number for capture squares
    int rightdx = 48;
    int leftdx = 0;
    offset = hsegment;
    int count = 0;
    // keep track of captured squares
    // left: end user, right: system
    for (int i = 0; i < capSquares; i++) {
      // find where roi should be
      Point p1 =
          new Point(
              offset + count * hsegment, rowNum * vsegment); // top left point of rectangle (x,y)
      Point p2 =
          new Point(
              offset + (count + 1) * hsegment,
              (rowNum + 1) * vsegment); // bottom right point of rectangle (x,y)
      // create rectangle that is board square
      Rect bound = new Rect(p1, p2);

      char color;

      // frame only includes rectangle
      Mat roi = new Mat(in, bound);

      // get the color
      color = identifyColor(roi);

      switch (color) {
        case COLOR_BLUE:
          // Imgproc.rectangle(in, p1, p2, new Scalar(255, 0, 0), 3);
          Core.rectangle(in, p1, p2, new Scalar(255, 0, 0), 2);
          captured[i] = 1;
          break;
        case COLOR_ORANGE:
          // Imgproc.rectangle(in, p1, p2, new Scalar(0, 128, 255), 3);
          Core.rectangle(in, p1, p2, new Scalar(0, 128, 255), 2);
          captured[i] = 1;
          break;
        case COLOR_WHITE:
          // Imgproc.rectangle(in, p1, p2, new Scalar(255, 255, 255), 3);
          Core.rectangle(in, p1, p2, new Scalar(255, 255, 255), 2);
          captured[i] = 0;
          break;
        case COLOR_BLACK:
          // Imgproc.rectangle(in, p1, p2, new Scalar(0, 0, 0), 3);
          Core.rectangle(in, p1, p2, new Scalar(255, 255, 255), 2);
          captured[i] = 0;
          break;
      }

      count++;
      if (count == 1) {
        offset = hsegment * 10 - rightdx;
      } else if (count == 2) {
        count = 0;
        rightdx -= 6;
        leftdx += 6;
        offset = hsegment - leftdx;
        rowNum++;
      }
    }
  }
Пример #12
0
  /**
   * Identifies the color in the frame
   *
   * @param in the Mat image in the region of interest
   * @return the color
   */
  public char identifyColor(Mat in) {
    // Mat blue = new Mat(in.rows(), in.cols(), CvType.CV_8UC1);
    // Mat green = new Mat(in.rows(), in.cols(), CvType.CV_8UC1);
    // Mat red = new Mat(in.rows(), in.cols(), CvType.CV_8UC1);

    // split the channels of the image
    Mat blue = new Mat(); // default is CV_8UC3
    Mat green = new Mat();
    Mat red = new Mat();
    List<Mat> channels = new ArrayList<Mat>(3);
    Core.split(in, channels);
    blue = channels.get(0); // makes all 3 CV_8UC1
    green = channels.get(1);
    red = channels.get(2);
    // System.out.println(blue.toString());

    // add the intensities
    Mat intensity = new Mat(in.rows(), in.cols(), CvType.CV_32F);
    // Mat mask = new Mat();
    Core.add(blue, green, intensity); // , mask, CvType.CV_32F);
    Core.add(intensity, red, intensity); // , mask, CvType.CV_32F);

    // not sure if correct from here to ...

    Mat inten = new Mat();
    Core.divide(intensity, Scalar.all(3.0), inten);
    // System.out.println(intensity.toString());
    // Core.divide(3.0, intensity, inten);
    // if intensity = intensity / 3.0; means element-wise division
    // use intensity.muls(Mat m)
    // so make new Mat m of same size that has each element of 1/3

    /*
    * or
    * About per-element division you can use Core.divide()

    Core.divide(A,Scalar.all(d), B);

    It's equivalent to B=A/d
    */

    // find normalized values
    Mat bnorm = new Mat();
    Mat gnorm = new Mat();
    Mat rnorm = new Mat();
    // blue.convertTo(blue, CvType.CV_32F);
    // green.convertTo(green, CvType.CV_32F);
    // red.convertTo(red, CvType.CV_32F);

    Core.divide(blue, inten, bnorm);
    Core.divide(green, inten, gnorm);
    Core.divide(red, inten, rnorm);

    // find average norm values
    Scalar val = new Scalar(0);
    val = Core.mean(bnorm);
    String value[] = val.toString().split(",");
    String s = value[0].substring(1);
    double bavg = Double.parseDouble(s);
    val = Core.mean(gnorm);
    String value1[] = val.toString().split(",");
    String s1 = value1[0].substring(1);
    double gavg = Double.parseDouble(s1);
    val = Core.mean(rnorm);
    String value2[] = val.toString().split(",");
    String s2 = value2[0].substring(1);
    double ravg = Double.parseDouble(s2);

    // ... here

    // original values
    /*
    // define the reference color values
    //double RED[] = {0.4, 0.5, 1.8};
    //double GREEN[] = {1.0, 1.2, 1.0};
    double BLUE[] = {1.75, 1.0, 0.5};
    //double YELLOW[] = {0.82, 1.7, 1.7};
    double ORANGE[] = {0.2, 1.0, 2.0};
    double WHITE[] = {2.0, 1.7, 1.7};
    //double BLACK[] = {0.0, 0.3, 0.3};
    */

    // define the reference color values
    // double RED[] = {0.4, 0.5, 1.8};
    // double GREEN[] = {1.0, 1.2, 1.0};
    double BLUE[] = {1.75, 1.0, 0.5};
    // double YELLOW[] = {0.82, 1.7, 1.7};
    double ORANGE[] = {0.2, 1.0, 2.0};
    double WHITE[] = {2.0, 1.7, 1.7};
    // double BLACK[] = {0.0, 0.3, 0.3};

    // compute the square error relative to the reference color values
    // double minError = 3.0;
    double minError = 2.0;
    double errorSqr;
    char bestFit = 'x';

    // test++;
    // System.out.print("\n\n" + test + "\n\n");

    // check BLUE fitness
    errorSqr = normSqr(BLUE[0], BLUE[1], BLUE[2], bavg, gavg, ravg);
    System.out.println("Blue: " + errorSqr);
    if (errorSqr < minError) {
      minError = errorSqr;
      bestFit = COLOR_BLUE;
    }
    // check ORANGE fitness
    errorSqr = normSqr(ORANGE[0], ORANGE[1], ORANGE[2], bavg, gavg, ravg);
    System.out.println("Orange: " + errorSqr);
    if (errorSqr < minError) {
      minError = errorSqr;
      bestFit = COLOR_ORANGE;
    }
    // check WHITE fitness
    errorSqr = normSqr(WHITE[0], WHITE[1], WHITE[2], bavg, gavg, ravg);
    System.out.println("White: " + errorSqr);
    if (errorSqr < minError) {
      minError = errorSqr;
      bestFit = COLOR_WHITE;
    }
    // check BLACK fitness
    /*errorSqr = normSqr(BLACK[0], BLACK[1], BLACK[2], bavg, gavg, ravg);
    System.out.println("Black: " + errorSqr);
    if(errorSqr < minError)
    {
    	minError = errorSqr;
    	bestFit = COLOR_BLACK;
    }*/

    // return the best fit color label
    return bestFit;
  }
Пример #13
0
  public void processWithContours(Mat in, Mat out) {
    int playSquares = 32; // number of playable game board squares

    // keep track of starting row square
    int parity = 0; // 0 is even, 1 is odd, tied to row number
    int count = 0; // row square
    int rowNum = 0; // row number, starting at 0

    int vsegment = in.rows() / 8; // only accounts 8 playable
    int hsegment = in.cols() / 10; // 8 playable, 2 capture
    int hOffset = hsegment * 2; // offset for playable board
    int vOffset = vsegment + 40;

    // For angle of camera
    int dx = 80;
    int ddx = 0;
    hsegment -= 16;

    int dy = 20;
    vsegment -= 24;
    int ddy = 0;

    // Go through all playable squares
    for (int i = 0; i < playSquares; i++) {
      // change offset depending on the row
      if (parity == 0) // playable squares start on 2nd square from left
      {
        if (rowNum >= 5) dx -= 3;
        hOffset = hsegment * 2 + dx;
      } else // playable squares start on immediate left
      {
        if (rowNum >= 5) dx -= 3;
        hOffset = hsegment + dx;
      }

      if (rowNum == 0) ddy = 5;
      if (rowNum == 4) if (count == 6) ddx = 10;
      if (rowNum == 5) {
        if (count == 0) ddx = -6;
        else if (count == 2) ddx = 6;
        else if (count == 4) ddx = 12;
        else if (count == 6) ddx = 20;
      }
      if (rowNum == 6) {
        if (count == 0) ddx = 0;
        else if (count == 2) ddx = 16;
        else if (count == 4) ddx = 32;
        else if (count == 6) ddx = 40;
      }
      if (rowNum == 7) {
        if (count == 0) ddx = 6;
        else if (count == 2) ddx = 24;
        else if (count == 4) ddx = 40;
        else ddx = 52;
      }

      // find where roi should be
      // System.out.println("" + vOffset);
      Point p1 =
          new Point(
              hOffset + count * hsegment + ddx + 5,
              vOffset + rowNum * vsegment - dy - 5 - ddy); // top left point of rectangle (x,y)
      Point p2 =
          new Point(
              hOffset + (count + 1) * hsegment + ddx - 5,
              vOffset
                  + (rowNum + 1) * vsegment
                  - dy
                  - 5
                  - ddy); // bottom right point of rectangle (x,y)

      // create rectangle that is board square
      Rect bound = new Rect(p1, p2);

      Mat roi;
      char color;
      if (i == 0) {
        // frame only includes rectangle
        roi = new Mat(in, bound);

        // get the color
        color = identifyColor(roi);

        // copy input image to output image
        in.copyTo(out);
      } else {
        // frame only includes rectangle
        roi = new Mat(out, bound);

        // get the color
        color = identifyColor(roi);
      }

      Imgproc.cvtColor(roi, roi, Imgproc.COLOR_BGR2GRAY); // change to single color

      Mat canny = new Mat();
      Imgproc.Canny(roi, canny, 20, 40); // make image a canny image that is only edges; 2,4
      // lower threshold values find more edges
      List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
      Mat hierarchy = new Mat(); // holds nested contour information
      Imgproc.findContours(
          canny,
          contours,
          hierarchy,
          Imgproc.RETR_LIST,
          Imgproc.CHAIN_APPROX_SIMPLE); // Imgproc.RETR_LIST, TREE

      System.out.println(++test + "\t" + contours.size());

      if (contours.size() > 3) // or error value for color is below 1
      {
        switch (color) {
          case COLOR_BLUE:
            // Imgproc.rectangle(out, p1, p2, new Scalar(255, 0, 0), 2);
            Core.rectangle(out, p1, p2, new Scalar(255, 0, 0), 2);
            board[i] = CheckersBoard.BLACK; // end user's piece
            break;
          case COLOR_ORANGE:
            // Imgproc.rectangle(out, p1, p2, new Scalar(0, 128, 255), 2);
            Core.rectangle(out, p1, p2, new Scalar(0, 128, 255), 2);
            board[i] = CheckersBoard.WHITE; // system's piece
            break;
          case COLOR_WHITE:
            // Imgproc.rectangle(out, p1, p2, new Scalar(255, 255, 255), 2);
            Core.rectangle(out, p1, p2, new Scalar(255, 255, 255), 2);
            board[i] = CheckersBoard.EMPTY;
            break;
          case COLOR_BLACK: // this is black
            // Imgproc.rectangle(out, p1, p2, new Scalar(0, 0, 0), 2);
            Core.rectangle(
                out,
                p1,
                p2,
                new Scalar(0, 0, 0),
                2); // maybe add 8, 0 as line type and fractional bits
            board[i] = CheckersBoard.EMPTY;
            break;
        }
      }

      System.out.println("in color switch " + board[i]);
      count += 2;
      if (count == 8) {
        parity = ++parity % 2; // change odd or even
        count = 0;
        rowNum++;
        hsegment += 2;
        dx -= 10;
        dy += 10;
        vsegment += 3;
        ddy = 0;
      }
    }
  }
Пример #14
0
  /**
   * Processes the board image
   *
   * @param in image captured of board
   * @param out processed image of board
   */
  public void processFrame(Mat in, Mat out) {
    // multiple regions of interest

    int playSquares = 32; // number of playable game board squares

    // keep track of starting row square
    int parity = 0; // 0 is even, 1 is odd, tied to row number
    int count = 0; // row square
    int rowNum = 0; // row number, starting at 0

    int vsegment = in.rows() / 8; // only accounts 8 playable
    int hsegment = in.cols() / 10; // 8 playable, 2 capture
    int hOffset = hsegment * 2; // offset for playable board
    int vOffset = vsegment + 40;

    // For angle of camera
    int dx = 80;
    int ddx = 0;
    hsegment -= 16;

    int dy = 20;
    vsegment -= 24;

    // Go through all playable squares
    for (int i = 0; i < playSquares; i++) {
      // change offset depending on the row
      if (parity == 0) // playable squares start on 2nd square from left
      {
        if (rowNum >= 5) dx -= 3;
        hOffset = hsegment * 2 + dx;
      } else // playable squares start on immediate left
      {
        if (rowNum >= 5) dx -= 3;
        hOffset = hsegment + dx;
      }

      if (rowNum == 4) if (count == 6) ddx = 10;
      if (rowNum == 5) {
        if (count == 0) ddx = -6;
        else if (count == 2) ddx = 6;
        else if (count == 4) ddx = 12;
        else if (count == 6) ddx = 20;
      }
      if (rowNum == 6) {
        if (count == 0) ddx = 0;
        else if (count == 2) ddx = 16;
        else if (count == 4) ddx = 32;
        else if (count == 6) ddx = 40;
      }
      if (rowNum == 7) {
        if (count == 0) ddx = 0;
        else if (count == 2) ddx = 24;
        else if (count == 4) ddx = 40;
        else ddx = 52;
      }

      // find where roi should be
      // System.out.println("" + vOffset);
      Point p1 =
          new Point(
              hOffset + count * hsegment + ddx,
              vOffset + rowNum * vsegment - dy); // top left point of rectangle (x,y)
      Point p2 =
          new Point(
              hOffset + (count + 1) * hsegment + ddx,
              vOffset + (rowNum + 1) * vsegment - dy); // bottom right point of rectangle (x,y)

      // create rectangle that is board square
      Rect bound = new Rect(p1, p2);

      char color;
      if (i == 0) {
        // frame only includes rectangle
        Mat roi = new Mat(in, bound);

        // get the color
        color = identifyColor(roi);

        // copy input image to output image
        in.copyTo(out);
      } else {
        // frame only includes rectangle
        Mat roi = new Mat(out, bound);

        // get the color
        color = identifyColor(roi);
      }

      // annotate the output image
      // scalar values as (blue, green, red)
      switch (color) {
        case COLOR_BLUE:
          // Imgproc.rectangle(out, p1, p2, new Scalar(255, 0, 0), 2);
          Core.rectangle(out, p1, p2, new Scalar(255, 0, 0), 2);
          board[i] = CheckersBoard.BLACK; // end user's piece
          break;
        case COLOR_ORANGE:
          // Imgproc.rectangle(out, p1, p2, new Scalar(0, 128, 255), 2);
          Core.rectangle(out, p1, p2, new Scalar(0, 128, 255), 2);
          board[i] = CheckersBoard.WHITE; // system's piece
          break;
        case COLOR_WHITE:
          // Imgproc.rectangle(out, p1, p2, new Scalar(255, 255, 255), 2);
          Core.rectangle(out, p1, p2, new Scalar(255, 255, 255), 2);
          board[i] = CheckersBoard.EMPTY;
          break;
        case COLOR_BLACK: // this is black
          // Imgproc.rectangle(out, p1, p2, new Scalar(0, 0, 0), 2);
          Core.rectangle(
              out,
              p1,
              p2,
              new Scalar(0, 0, 0),
              2); // maybe add 8, 0 as line type and fractional bits
          board[i] = CheckersBoard.EMPTY;
          break;
      }

      count += 2;
      if (count == 8) {
        parity = ++parity % 2; // change odd or even
        count = 0;
        rowNum++;
        hsegment += 2;
        dx -= 10;
        dy += 10;
        vsegment += 3;
      }
    }
  }
Пример #15
0
 public void show(boolean refresh) {
   container.add(layout);
   if (refresh) core.refreshDisplay();
 }
Пример #16
0
  public static void run(
      SIRStream str,
      JInterfaceDeclaration[] interfaces,
      SIRInterfaceTable[] interfaceTables,
      SIRStructure[] structs,
      SIRHelper[] helpers,
      SIRGlobal global) {
    System.out.println("Entry to SMP Backend...");

    checkArguments();
    setScheduler();

    if (KjcOptions.smp > 16) {
      setupLargeConfig();
    }

    // create cores in desired amount and order
    int[] cores = new int[KjcOptions.smp];
    for (int x = 0; x < KjcOptions.smp; x++) cores[x] = coreOrder[x];
    chip = new SMPMachine(cores);

    // create a new structs.h file for typedefs etc.
    structs_h = new Structs_h(structs);

    // The usual optimizations and transformation to slice graph
    CommonPasses commonPasses = new CommonPasses();
    // perform standard optimizations, use the number of cores the user wants to target
    commonPasses.run(str, interfaces, interfaceTables, structs, helpers, global, chip.size());
    // perform some standard cleanup on the slice graph.
    commonPasses.simplifySlices();
    // dump slice graph to dot file
    commonPasses.getSlicer().dumpGraph("traces.dot", null);

    // partition the slice graph based on the scheduling policy
    SpaceTimeScheduleAndSlicer graphSchedule =
        new SpaceTimeScheduleAndSlicer(commonPasses.getSlicer());
    scheduler.setGraphSchedule(graphSchedule);
    scheduler.run(chip.size());
    FilterInfo.reset();

    // generate schedules for initialization, primepump and steady-state
    scheduleSlices(graphSchedule);

    // generate layout for filters
    scheduler.runLayout();

    // dump final slice graph to dot file
    graphSchedule.getSlicer().dumpGraph("after_slice_partition.dot", scheduler);
    graphSchedule.getSlicer().dumpGraph("slice_graph.dot", scheduler, false);

    // if load balancing, find candidiate fission groups to load balance
    if (KjcOptions.loadbalance) {
      LoadBalancer.findCandidates();
      LoadBalancer.instrumentMainMethods();
    }

    // create all buffers and set the rotation lengths
    RotatingBuffer.createBuffers(graphSchedule);

    // now convert to Kopi code plus communication commands
    backEndBits = new SMPBackEndFactory(chip, scheduler);
    backEndBits.getBackEndMain().run(graphSchedule, backEndBits);

    // generate code for file writer
    CoreCodeStore.generatePrintOutputCode();

    if (KjcOptions.numbers > 0) chip.getNthComputeNode(0).getComputeCode().generateNumbersCode();

    // emit c code for all cores
    EmitSMPCode.doit(backEndBits);

    // dump structs.h file
    structs_h.writeToFile();

    // display final assignment of filters to cores
    System.out.println("Final filter assignments:");
    System.out.println("========================================");
    for (int x = 0; x < KjcOptions.smp; x++) {
      Core core = chip.getNthComputeNode(x);
      Set<FilterSliceNode> filters = core.getComputeCode().getFilters();
      long totalWork = 0;

      System.out.println("Core " + core.getCoreID() + ": ");
      for (FilterSliceNode filter : filters) {
        long work = SliceWorkEstimate.getWork(filter.getParent());
        System.out.format("%16d | " + filter + "\n", work);
        totalWork += work;
      }
      System.out.format("%16d | Total\n", totalWork);
    }

    // calculate computation to communication ratio
    if (KjcOptions.sharedbufs) {
      LinkedList<Slice> slices =
          DataFlowOrder.getTraversal(graphSchedule.getSlicer().getTopSlices());
      HashSet<Slice> compProcessed = new HashSet<Slice>();
      HashSet<Slice> commProcessed = new HashSet<Slice>();

      long comp = 0;
      long comm = 0;

      for (Slice slice : slices) {
        if (compProcessed.contains(slice)) continue;

        comp += SliceWorkEstimate.getWork(slice);
        compProcessed.add(slice);
      }

      /*
                  for(Slice slice : slices) {
                      if(commProcessed.contains(slice))
                          continue;

                      FilterInfo info = FilterInfo.getFilterInfo(slice.getFirstFilter());
                      int totalItemsReceived = info.totalItemsReceived(SchedulingPhase.STEADY);

                      if(totalItemsReceived == 0)
                          continue;

                      InputSliceNode input = slice.getHead();
                      Set<InterSliceEdge> sources = input.getSourceSet(SchedulingPhase.STEADY);
                      int numInputRots = totalItemsReceived / input.totalWeights(SchedulingPhase.STEADY);

                      if(!FissionGroupStore.isFizzed(slice)) {
                          for(InterSliceEdge source : sources) {
                              Slice srcSlice = source.getSrc().getParent();

      //                         if(srcSlice.getFirstFilter().isFileInput())
      //                             continue;

                              if(FissionGroupStore.isFizzed(srcSlice)) {
                                  // Filter is not fizzed, source is fizzed
                                  // Filter must receive (N-1)/N of inputs from different cores
                                  comm += numInputRots *
                                      input.getWeight(source, SchedulingPhase.STEADY) /
                                      KjcOptions.smp * (KjcOptions.smp - 1);
                              }
                              else {
                                  // Filter is not fizzed, source is not fizzed
                                  // Check to see if on same core
                                  // If not, must communicate all elements
                                  if(!scheduler.getComputeNode(slice.getFirstFilter()).equals(
                                         scheduler.getComputeNode(srcSlice.getFirstFilter()))) {
                                      comm += numInputRots *
                                          input.getWeight(source, SchedulingPhase.STEADY);
                                  }
                              }
                          }
                      }
                      else {
                          for(InterSliceEdge source : sources) {
                              Slice srcSlice = source.getSrc().getParent();

      //                         if(srcSlice.getFirstFilter().isFileInput())
      //                             continue;

                              if(FissionGroupStore.isFizzed(srcSlice)) {
                                  // Filter is fizzed, source is also fizzed
                                  int totalItemsReceivedPerFizzed = totalItemsReceived /
                                      FissionGroupStore.getFissionGroup(slice).fizzedSlices.length;
                                  int numInputRotsPerFizzed = numInputRots /
                                      FissionGroupStore.getFissionGroup(slice).fizzedSlices.length;

                                  System.out.println("totalItemsReceivedPerFizzed: " + totalItemsReceivedPerFizzed);
                                  System.out.println("numInputRotsPerFizzed: " + numInputRotsPerFizzed);

                                  int inputWeightBeforeSrc =
                                      input.weightBefore(source, SchedulingPhase.STEADY);
                                  int inputWeightSrc = input.getWeight(source, SchedulingPhase.STEADY);
                                  int inputTotalWeight = input.totalWeights(SchedulingPhase.STEADY);

                                  System.out.println("inputWeightBeforeSrc: " + inputWeightBeforeSrc);
                                  System.out.println("inputWeightSrc: " + inputWeightSrc);
                                  System.out.println("copyDown: " + info.copyDown);

                                  int numXmit = 0;

                                  for(int rot = 0 ; rot < numInputRotsPerFizzed ; rot++) {
                                      numXmit += Math.min(inputWeightSrc,
                                                          Math.max(0,
                                                                   info.copyDown +
                                                                   rot * inputTotalWeight +
                                                                   inputWeightBeforeSrc + inputWeightSrc -
                                                                   totalItemsReceivedPerFizzed));
                                  }

                                  System.out.println("numXmit: " + numXmit);

                                  comm += KjcOptions.smp * numXmit;
                              }
                              else {
                                  // Filter is fizzed, source is not fizzed
                                  // Source must send (N-1)/N of outputs to different cores
                                  comm += numInputRots *
                                      input.getWeight(source, SchedulingPhase.STEADY) /
                                      KjcOptions.smp * (KjcOptions.smp - 1);
                              }
                          }
                      }

                      commProcessed.add(slice);
                  }
                  */

      // Simple communication estimation
      for (Slice slice : slices) {
        if (commProcessed.contains(slice)) continue;

        FilterInfo info = FilterInfo.getFilterInfo(slice.getFirstFilter());
        int totalItemsReceived = info.totalItemsReceived(SchedulingPhase.STEADY);

        if (totalItemsReceived == 0) continue;

        comm += totalItemsReceived;

        if (FissionGroupStore.isFizzed(slice)) {
          assert info.peek >= info.pop;
          comm += (info.peek - info.pop) * KjcOptions.smp;
        }

        commProcessed.add(slice);
      }

      // Simple communication estimation 2
      /*
      for(Slice slice : slices) {
          if(commProcessed.contains(slice))
              continue;

          FilterInfo info = FilterInfo.getFilterInfo(slice.getFirstFilter());
          int totalItemsReceived = info.totalItemsReceived(SchedulingPhase.STEADY);
          int totalItemsSent = info.totalItemsSent(SchedulingPhase.STEADY);

          comm += totalItemsReceived;
          comm += totalItemsSent;

          if(totalItemsReceived == 0)
              continue;

          if(FissionGroupStore.isFizzed(slice)) {
              assert info.peek >= info.pop;
              comm += (info.peek - info.pop) * KjcOptions.smp;
          }

          commProcessed.add(slice);
      }
      */

      System.out.println("Final Computation: " + comp);
      System.out.println("Final Communication: " + comm);
      System.out.println("Final Comp/Comm Ratio: " + (float) comp / (float) comm);
    }

    System.exit(0);
  }