Example #1
0
  public static boolean validateOverhangs(ArrayList<RGraph> graphs) {

    boolean valid = true;

    for (RGraph graph : graphs) {
      ArrayList<RNode> queue = new ArrayList<RNode>();
      HashSet<RNode> seenNodes = new HashSet<RNode>();
      RNode root = graph.getRootNode();
      queue.add(root);
      while (!queue.isEmpty()) {
        RNode current = queue.get(0);
        queue.remove(0);
        seenNodes.add(current);

        if (!("EX".equals(current.getLOverhang()) && "SP".equals(current.getROverhang()))) {
          return false;
        }

        ArrayList<RNode> neighbors = current.getNeighbors();
        for (RNode neighbor : neighbors) {
          if (!seenNodes.contains(neighbor)) {
            queue.add(neighbor);
          }
        }
      }
    }

    return valid;
  }
Example #2
0
  /** Determine overhang scars * */
  private void assignScars(ArrayList<RGraph> optimalGraphs) {

    // Loop through each optimal graph and grab the root node to prime for the traversal
    for (RGraph graph : optimalGraphs) {

      RNode root = graph.getRootNode();
      ArrayList<RNode> children = root.getNeighbors();
      assignScarsHelper(root, children);
    }
  }
Example #3
0
 private void visualize(RNode n, java.io.PrintWriter pw, int x0, int y0, int w, int h) {
   pw.printf(
       "<div style=\"position:absolute; left: %d; top: %d; width: %d; height: %d; border: 1px dashed\">\n",
       x0, y0, w, h);
   pw.println("<pre>");
   pw.println("Node: " + n.toString() + " \n(root==" + (n == root) + ") \n");
   pw.println("Coords start: " + Arrays.toString(n.getMbr().getP_start()) + "\n");
   pw.println("coords end: " + Arrays.toString(n.getMbr().getP_end()) + "\n");
   pw.println("# Children: " + ((n.children() == null) ? 0 : n.children().size()) + "\n");
   if (n instanceof REntry) {
     REntry n1 = (REntry) n;
     pw.println("Content: " + n1.getContent());
   }
   pw.println("isLeaf: " + n.isLeaf() + "\n");
   pw.println("</pre>");
   int numChildren = (n.children() == null) ? 0 : n.children().size();
   for (int i = 0; i < numChildren; i++) {
     visualize(
         n.children().get(i),
         pw,
         (int) (x0 + (i * w / (float) numChildren)),
         y0 + elemHeight,
         (int) (w / (float) numChildren),
         h - elemHeight);
   }
   pw.println("</div>");
 }
Example #4
0
 private RNode getMinimalAreaNode(List<RNode> nodes) {
   RNode minimal = null;
   double minArea = Double.MAX_VALUE;
   for (RNode e : nodes) {
     double eArea = e.getMbr().getArea();
     if (eArea < minArea) {
       minArea = eArea;
       minimal = e;
     }
   }
   return minimal;
 }
Example #5
0
 private double getDistance(RNode e1, RNode e2) {
   double[] a1 = e1.getMbr().getP_start();
   double[] a2 = e1.getMbr().getP_end();
   double[] b1 = e2.getMbr().getP_start();
   double[] b2 = e2.getMbr().getP_end();
   double dist = 0;
   for (int i = 0; i < dimension; i++) {
     /*suma los cuadrados de la resta de los puntos medios de los 2 mbr's para cada coordenada*/
     dist += Math.pow(Math.abs(a1[i] - a2[i]) / 2.0 - Math.abs(b1[i] - b2[i]) / 2.0, 2);
   }
   dist = Math.sqrt(dist);
   return dist;
 }
Example #6
0
 private void refresh(RNode part1, RNode part2) throws DimensionalException {
   if (part1 == root) {
     if (part2 != null) {
       // build new root and add children.
       root = makeRoot(false);
       root.addChild(part1);
       part1.setParent(root);
       root.addChild(part2);
       part2.setParent(root);
     }
     update(root);
     return;
   }
   update(part1);
   if (part2 != null) {
     update(part2);
     if (part1.getParent().getChildren().size() > M_order) {
       RNode[] splits = makePartition(part1.getParent());
       refresh(splits[0], splits[1]);
     }
   }
   if (part1.getParent() != null) {
     refresh(part1.getParent(), null);
   }
 }
Example #7
0
    @Override
    public Object execute(Frame frame) {

      RAny lhsVal = (RAny) lhs.execute(frame);
      RAny rowVal = (RAny) rowExpr.execute(frame);
      boolean dropVal =
          dropExpr.executeLogical(frame)
              != RLogical.FALSE; // FIXME: what is the correct execution order of these args?
      int exactVal = exactExpr.executeLogical(frame);

      if (!(lhsVal instanceof RArray)) {
        throw RError.getObjectNotSubsettable(ast, lhsVal.typeOf());
      }
      RArray array = (RArray) lhsVal;
      int[] dim = array.dimensions();
      if (dim == null || dim.length != 2) {
        throw RError.getIncorrectDimensions(getAST());
      }
      int m = dim[0];
      int n = dim[1];

      try {
        int row;
        if (rowVal instanceof ScalarIntImpl) {
          row = ((ScalarIntImpl) rowVal).getInt();
        } else if (rowVal instanceof ScalarDoubleImpl) {
          row = Convert.double2int(((ScalarDoubleImpl) rowVal).getDouble());
        } else {
          throw new UnexpectedResultException(null);
        }
        if (row > n || row <= 0) {
          throw new UnexpectedResultException(null);
        }

        int[] ndim;
        if (dropVal) {
          ndim = null;
        } else {
          ndim = new int[] {1, n};
        }

        // note: also could be lazy here
        RArray res = Utils.createArray(array, n, ndim, null, null); // drop attributes
        int offset = row - 1;
        for (int i = 0; i < n; i++) {
          res.set(i, array.getRef(offset));
          offset += m;
        }
        return res;
      } catch (UnexpectedResultException e) {
        SelectorNode selIExpr = Selector.createSelectorNode(ast, true, rowExpr);
        SelectorNode selJExpr = Selector.createSelectorNode(ast, true, null);
        MatrixRead nn = new MatrixRead(ast, true, lhs, selIExpr, selJExpr, dropExpr, exactExpr);
        replace(nn, "install MatrixRead from MatrixRowSubset");
        Selector selI = selIExpr.executeSelector(rowVal);
        Selector selJ = selJExpr.executeSelector(frame);
        return nn.executeLoop(array, selI, selJ, dropVal, exactVal);
      }
    }
Example #8
0
  public void insert(REntry e) throws DimensionalException {

    if (e.getDimension() != dimension)
      throw new DimensionalException(
          "Can only insert n-dimensional objects in n-dimensional RTree");
    RNode theLeaf = findFittingLeaf(root, e);
    theLeaf.children().add(e);
    e.setParent(theLeaf);
    size++;
    // numOfNodes++;
    if (theLeaf.children().size() > M_order) {
      RNode[] parts = makePartition(theLeaf);
      refresh(parts[0], parts[1]);
    } else {
      refresh(theLeaf, null);
    }
  }
Example #9
0
 private int countLeafs(RNode n) {
   if (n.isLeaf()) return 1;
   int res = 0;
   for (RNode c : n.children) {
     res += countLeafs(c);
   }
   return res;
 }
Example #10
0
 private double getEnlargement(RNode host, RNode guest) throws DimensionalException {
   double[] p1Host = host.getMbr().getP_start();
   double[] p2Host = host.getMbr().getP_end();
   double[] p1Guest = guest.getMbr().getP_start();
   double[] p2Guest = guest.getMbr().getP_end();
   double[] minRes = new double[dimension];
   double[] maxRes = new double[dimension];
   for (int i = 0; i < dimension; i++) {
     double minH = Math.min(p1Host[i], p2Host[i]);
     double maxH = Math.max(p1Host[i], p2Host[i]);
     double minG = Math.min(p1Guest[i], p2Guest[i]);
     double maxG = Math.max(p1Guest[i], p2Guest[i]);
     if (minG < minH) minRes[i] = minG;
     else minRes[i] = minH;
     if (maxG > maxH) maxRes[i] = maxG;
     else maxRes[i] = maxH;
   }
   return new MBR(minRes, maxRes, dimension).getArea() - host.getMbr().getArea();
 }
Example #11
0
 private RNode findFittingLeaf(RNode n, REntry e) throws DimensionalException {
   if (n.isLeaf()) return n;
   double min = Double.MAX_VALUE;
   List<RNode> minNodes = new ArrayList<RNode>();
   for (RNode nc : n.children()) {
     double d = getEnlargement(nc, e);
     if (d < min) {
       min = d;
       minNodes.clear();
       minNodes.add(nc);
     } else if (d == min) {
       minNodes.add(nc);
     }
   }
   RNode next;
   if (minNodes.size() > 1) next = getMinimalAreaNode(minNodes);
   else next = minNodes.get(0);
   return findFittingLeaf(next, e);
 }
Example #12
0
 public List<REntry> search(double[] point, double ratio) throws DimensionalException {
   List<REntry> resultados = new LinkedList<REntry>();
   StringBuilder sb = new StringBuilder();
   if (point.length != dimension)
     throw new DimensionalException("Can only search for n-dimensional points");
   root.search(point, ratio, resultados, sb);
   visitedNodes =
       visitedNodes.add(
           new BigInteger(
               ""
                   + sb.toString()
                       .length())); // visitedNodes.add(root.visitedNodes.add(BigInteger.ONE));
   return resultados;
 }
Example #13
0
 private RNode[] makePartition(RNode n) throws DimensionalException {
   numOfPartitions++;
   numOfNodes += 2;
   RNode[] parts = new RNode[] {n, new RNode(n.getMbr(), n.isLeaf(), M_order)};
   parts[1].setParent(n.getParent());
   if (parts[1].getParent() != null) {
     parts[1].getParent().children().add(parts[1]);
   }
   List<RNode> cpyc = new LinkedList<RNode>(n.children());
   n.children().clear();
   RNode[] seeds = getSeeds(cpyc);
   parts[0].children().add(seeds[0]);
   parts[1].children().add(seeds[1]);
   update(parts[0]);
   update(parts[1]);
   while (!cpyc.isEmpty()) {
     if (parts[0].missingEntries(m_order) == 0
         && parts[1].missingEntries(m_order) + cpyc.size() == m_order) {
       parts[1].children().addAll(cpyc);
       cpyc.clear();
       update(parts[0]);
       update(parts[1]);
       return parts;
     } else if (parts[1].missingEntries(m_order) == 0
         && parts[0].missingEntries(m_order) + cpyc.size() == m_order) {
       parts[0].children().addAll(cpyc);
       cpyc.clear();
       update(parts[0]);
       update(parts[1]);
       return parts;
     }
     RNode next = chooseNext(cpyc, seeds), chosen;
     double enl1 = getEnlargement(parts[0], next);
     double enl2 = getEnlargement(parts[1], next);
     if (enl1 < enl2) chosen = parts[0];
     else if (enl2 < enl1) chosen = parts[1];
     else {
       double ar1 = parts[0].getMbr().getArea();
       double ar2 = parts[1].getMbr().getArea();
       if (ar1 < ar2) chosen = parts[0];
       else if (ar2 < ar1) chosen = parts[1];
       else {
         if (parts[0].children().size() < parts[1].children().size()) chosen = parts[0];
         else if (parts[0].children().size() > parts[1].children().size()) chosen = parts[1];
         else chosen = parts[new Random().nextInt(2)];
       }
     }
     chosen.children().add(next);
     update(chosen);
   }
   return parts;
 }
Example #14
0
 /**
  * Administrador de memoria para guardar un nodo, guarda en el bloque que corresponde el nodo que
  * recibe como parametro, si el bloque esta en memoria principal lo guarda directamente, de lo
  * contrario lo carga desde memoria secundaria y el bloque completo queda en memoria.
  *
  * @param nodo nodo que queremos guardar, sera guardado de acuerdo a sus paremetros getFilePos y
  *     getPagePos
  * @throws IOException
  */
 private void writeAdmin(RNode nodo) throws IOException {
   long fPos = nodo.getMyfPos();
   int i;
   for (i = 0; i < numOfBuffers; i++) {
     if (fPos == thisBlock[i]) {
       writeNode(nodo, i);
       return;
     }
   }
   // Guardo el bloque con peor prioridad a memoria secundaria si fue modificado,
   // si no lo fue solo lo sobreescribo
   i = bufferPrior[numOfBuffers - 1];
   if (bufModified[i]) writeBlock(i);
   readBlock(fPos, i);
   writeNode(nodo, i);
 }
Example #15
0
 /**
  * shrinks the mbr area to the just necessary
  *
  * @param n
  */
 private void update(RNode n) throws DimensionalException {
   double[] minCoords = new double[dimension];
   double[] maxCoords = new double[dimension];
   for (int i = 0; i < dimension; i++) {
     minCoords[i] = Double.MAX_VALUE;
     maxCoords[i] = -Double.MAX_VALUE;
     for (RNode c : n.children()) {
       c.setParent(n);
       double minp = Math.min(c.getMbr().getP_start()[i], c.getMbr().getP_end()[i]);
       double maxp = Math.max(c.getMbr().getP_end()[i], c.getMbr().getP_start()[i]);
       if (minp < minCoords[i]) {
         minCoords[i] = minp;
       }
       if (maxp > maxCoords[i]) {
         maxCoords[i] = maxp;
       }
     }
   }
   n.setMbr(new MBR(minCoords, maxCoords, dimension));
 }
Example #16
0
  /**
   * This helper method executes the loops necessary to enforce overhangs for each graph in
   * enforceOverhangRules *
   */
  private void assignBioBricksOverhangsHelper(
      RNode parent,
      ArrayList<RNode> children,
      RNode root,
      HashMap<Integer, RVector> stageRVectors) {

    // Loop through each one of the children to assign rule-instructed overhangs... enumerated
    // numbers currently
    for (int i = 0; i < children.size(); i++) {

      RNode child = children.get(i);

      // Give biobricks overhangs
      RVector vector = stageRVectors.get(child.getStage() % stageRVectors.size());
      RVector newVector = new RVector("EX", "SP", -1, vector.getName(), null);
      child.setVector(newVector);
      child.setLOverhang("EX");
      child.setROverhang("SP");

      // Make recursive call
      if (child.getStage() > 0) {
        ArrayList<RNode> grandChildren = new ArrayList<RNode>();
        grandChildren.addAll(child.getNeighbors());

        // Remove the current parent from the list
        if (grandChildren.contains(parent)) {
          grandChildren.remove(parent);
        }
        assignBioBricksOverhangsHelper(child, grandChildren, root, stageRVectors);

        // Or record the level zero parts
      } else {
        ArrayList<RNode> l0nodes = _rootBasicNodeHash.get(root);
        l0nodes.add(child);
        _rootBasicNodeHash.put(root, l0nodes);
      }
    }
  }
Example #17
0
 private RNode[] quadSeeds(List<RNode> cc) throws DimensionalException {
   RNode e1;
   RNode e2;
   RNode s1 = null;
   RNode s2 = null;
   double maxDeadSpace = -Double.MAX_VALUE;
   for (int i = 0; i < dimension; i++) {
     for (int k = i + 1; k < dimension; k++) {
       e1 = cc.get(i);
       e2 = cc.get(k);
       double areae1 = e1.getMbr().getArea();
       double areae2 = e2.getMbr().getArea();
       double[] p1Host = e1.getMbr().getP_start();
       double[] p2Host = e1.getMbr().getP_end();
       double[] p1Guest = e2.getMbr().getP_start();
       double[] p2Guest = e2.getMbr().getP_end();
       double[] minRes = new double[dimension];
       double[] maxRes = new double[dimension];
       for (int j = 0; j < dimension; j++) {
         double minH = Math.min(p1Host[j], p2Host[j]);
         double maxH = Math.max(p1Host[j], p2Host[j]);
         double minG = Math.min(p1Guest[j], p2Guest[j]);
         double maxG = Math.max(p1Guest[j], p2Guest[j]);
         if (minG < minH) minRes[j] = minG;
         else minRes[j] = minH;
         if (maxG > maxH) maxRes[j] = maxG;
         else maxRes[j] = maxH;
       }
       MBR ambr = new MBR(minRes, maxRes, dimension);
       double totarea = ambr.getArea();
       if (maxDeadSpace < totarea - areae1 - areae2) {
         maxDeadSpace = totarea - areae1 - areae2;
         s1 = e1;
         s2 = e2;
       }
     }
   }
   RNode[] seeds = new RNode[] {s1, s2};
   cc.removeAll(Arrays.asList(seeds));
   return seeds;
 }
Example #18
0
 /**
  * Guarda un Node en un buffer en memoria principal
  *
  * @param nodo Node que queremos guardar en el buffer
  * @param pPos posicion en el buffer donde guardaremos el nodo
  * @param i numero de buffer donde guardaremos el nodo (buffer[i]).
  * @throws IOException
  */
 private void writeNode(RNode nodo, int i) throws IOException {
   nodo.writeToBuffer(buffer[i]);
   bufModified[i] = true;
   improvePriority(i);
 }
Example #19
0
    @Override
    public Object execute(Frame frame) {

      RAny lhsVal = (RAny) lhs.execute(frame);
      Object rowFromVal = rowFromExpr.execute(frame);
      Object rowToVal = rowToExpr.execute(frame);
      Object colFromVal = colFromExpr.execute(frame);
      Object colToVal = colToExpr.execute(frame);
      boolean dropVal =
          dropExpr.executeLogical(frame)
              != RLogical.FALSE; // FIXME: what is the correct execution order of these args?
      int exactVal = exactExpr.executeLogical(frame);
      if (!(lhsVal instanceof RArray)) {
        throw RError.getObjectNotSubsettable(ast, lhsVal.typeOf());
      }
      RArray array = (RArray) lhsVal;

      try {

        int rowFrom = extractLimit(rowFromVal); // zero-based
        int rowTo = extractLimit(rowToVal);
        int colFrom = extractLimit(colFromVal);
        int colTo = extractLimit(colToVal);

        int[] dim = array.dimensions();
        if (dim == null || dim.length != 2) {
          throw RError.getIncorrectDimensions(getAST());
        }
        int m = dim[0];
        int n = dim[1];

        int rowStep;
        int rowSize;
        if (rowFrom <= rowTo) {
          rowStep = 1;
          if (rowTo > m) {
            throw new UnexpectedResultException(null);
          }
          rowSize = rowTo - rowFrom + 1;
        } else {
          rowStep = -1;
          if (rowFrom > m) {
            throw new UnexpectedResultException(null);
          }
          rowSize = rowFrom - rowTo + 1;
        }

        int colStep;
        int colSize;
        if (colFrom <= colTo) {
          colStep = 1;
          if (colTo > n) {
            throw new UnexpectedResultException(null);
          }
          colSize = colTo - colFrom + 1;
        } else {
          colStep = -1;
          if (colFrom > n) {
            throw new UnexpectedResultException(null);
          }
          colSize = colFrom - colTo + 1;
        }

        int[] ndim;
        if (!dropVal || (rowSize > 1 && colSize > 1)) {
          ndim = new int[] {rowSize, colSize};
        } else {
          ndim = null;
        }

        int size = rowSize * colSize;
        RArray res = Utils.createArray(array, size, ndim, null, null); // drop attributes

        if (colStep == 1 && rowStep == 1) {
          int j = colFrom * m + rowFrom; // j - index to source matrix
          int jmax = j + rowSize;
          int jadvance = m - rowSize;
          for (int i = 0; i < size; i++) {
            res.set(i, array.getRef(j++)); // i - index to target matrix
            if (j == jmax) {
              j += jadvance;
              jmax += m;
            }
          }
        } else {
          int i = 0;
          // NOTE: here we know that colFrom != colTo and rowFrom != rowTo
          for (int col = colFrom; col != colTo + colStep; col += colStep) {
            for (int row = rowFrom; row != rowTo + rowStep; row += rowStep) {
              res.set(i++, array.getRef(col * m + row));
            }
          }
        }
        return res;
      } catch (UnexpectedResultException e) {
        // FIXME: clean this up; does Colon need to be package-private?
        ASTNode rowAST = rowFromExpr.getAST().getParent();
        Builtin rowColon =
            (Builtin)
                Primitives.getCallFactory(RSymbol.getSymbol(":"), null)
                    .create(rowAST, rowFromExpr, rowToExpr);
        SelectorNode selIExpr = Selector.createSelectorNode(rowAST, true, rowColon);
        ASTNode colAST = colFromExpr.getAST().getParent();
        Builtin colColon =
            (Builtin)
                Primitives.getCallFactory(RSymbol.getSymbol(":"), null)
                    .create(colAST, colFromExpr, colToExpr);
        SelectorNode selJExpr = Selector.createSelectorNode(ast, true, colColon);
        MatrixRead nn = new MatrixRead(ast, true, lhs, selIExpr, selJExpr, dropExpr, exactExpr);
        replace(nn, "install MatrixRead from MatrixSequenceSubset");
        Selector selI =
            selIExpr.executeSelector(
                rowColon.doBuiltIn(frame, new RAny[] {(RAny) rowFromVal, (RAny) rowToVal}));
        Selector selJ =
            selJExpr.executeSelector(
                colColon.doBuiltIn(frame, new RAny[] {(RAny) colFromVal, (RAny) colToVal}));
        return nn.executeLoop(array, selI, selJ, dropVal, exactVal);
      }
    }
Example #20
0
  /**
   * First step of overhang assignment - enforce numeric place holders for overhangs, ie no overhang
   * redundancy in any step *
   */
  private void assignBioBricksOverhangs(
      ArrayList<RGraph> optimalGraphs, HashMap<Integer, Vector> stageVectors) {

    // Initialize fields that record information to save complexity for future steps
    _rootBasicNodeHash = new HashMap<RNode, ArrayList<RNode>>();
    HashMap<Integer, RVector> stageRVectors = new HashMap<Integer, RVector>();
    for (Integer stage : stageVectors.keySet()) {
      RVector vec = ClothoReader.vectorImportClotho(stageVectors.get(stage));
      stageRVectors.put(stage, vec);
    }

    // If the stageVector hash is empty, make a new default vector
    if (stageRVectors.size() == 1) {
      if (stageRVectors.get(1) == null) {
        stageRVectors.put(0, new RVector("EX", "SP", -1, "pSK1A2", null));
      }
    }

    // Loop through each optimal graph and grab the root node to prime for the traversal
    for (RGraph graph : optimalGraphs) {

      RNode root = graph.getRootNode();
      RVector vector = stageRVectors.get(root.getStage() % stageRVectors.size());
      RVector rootVector = new RVector("EX", "SP", -1, vector.getName(), null);
      root.setVector(rootVector);
      root.setLOverhang("EX");
      root.setROverhang("SP");
      ArrayList<RNode> l0nodes = new ArrayList<RNode>();
      _rootBasicNodeHash.put(root, l0nodes);
      ArrayList<RNode> neighbors = root.getNeighbors();
      assignBioBricksOverhangsHelper(root, neighbors, root, stageRVectors);
    }

    // Determine which nodes impact which level to form the stageDirectionAssignHash
    for (RGraph graph : optimalGraphs) {
      RNode root = graph.getRootNode();
      ArrayList<String> rootDir = new ArrayList<String>();
      ArrayList<String> direction = root.getDirection();
      rootDir.addAll(direction);
      ArrayList<RNode> l0Nodes = _rootBasicNodeHash.get(root);

      // Determine which levels each basic node impacts
      for (int i = 0; i < l0Nodes.size(); i++) {

        // Determine direction of basic level 0 nodes
        RNode l0Node = l0Nodes.get(i);
        String l0Direction = rootDir.get(0);
        if (l0Node.getComposition().size() == 1) {
          ArrayList<String> l0Dir = new ArrayList<String>();
          l0Dir.add(l0Direction);
          l0Node.setDirection(l0Dir);
        }
        int size = l0Node.getDirection().size();
        rootDir.subList(0, size).clear();
      }
    }
  }
Example #21
0
    @Override
    public Object execute(Frame frame) {

      RAny lhsVal = (RAny) lhs.execute(frame);
      RAny colVal = (RAny) columnExpr.execute(frame);
      boolean dropVal =
          dropExpr.executeLogical(frame)
              != RLogical.FALSE; // FIXME: what is the correct execution order of these args?
      int exactVal = exactExpr.executeLogical(frame);

      // TODO: GNU-R has different behavior when selecting from arrays that have some dimension zero

      if (!(lhsVal instanceof RArray)) {
        throw RError.getObjectNotSubsettable(ast, lhsVal.typeOf());
      }
      RArray array = (RArray) lhsVal;
      int[] dim = array.dimensions();
      if (dim == null || dim.length != nSelectors) {
        throw RError.getIncorrectDimensions(getAST());
      }
      int n = dim[nSelectors - 1]; // limit for the column (last dimension)

      try {
        int col;
        if (colVal instanceof ScalarIntImpl) {
          col = ((ScalarIntImpl) colVal).getInt();
        } else if (colVal instanceof ScalarDoubleImpl) {
          col = Convert.double2int(((ScalarDoubleImpl) colVal).getDouble());
        } else {
          throw new UnexpectedResultException(null);
        }
        if (col > n || col <= 0) {
          throw new UnexpectedResultException(null);
        }

        int[] ndim;
        int m; // size of the result

        if (dropVal) {
          boolean hasNonTrivialDimension = false;
          boolean resultIsVector = true;
          m = 1;
          for (int i = 0; i < nSelectors - 1; i++) {
            int d = dim[i];
            if (d != 1) {
              if (hasNonTrivialDimension) {
                resultIsVector = false;
              } else {
                hasNonTrivialDimension = true;
              }
            }
            m *= d;
          }
          if (resultIsVector) {
            ndim = null;
          } else {
            ndim = new int[nSelectors - 1];
            System.arraycopy(dim, 0, ndim, 0, ndim.length);
          }
        } else {
          ndim = new int[nSelectors];
          ndim[nSelectors - 1] = 1;

          m = 1;
          for (int i = 0; i < ndim.length - 1; i++) {
            int d = dim[i];
            ndim[i] = d;
            m *= d;
          }
        }

        // note: also could be lazy here
        RArray res = Utils.createArray(array, m, ndim, null, null); // drop attributes
        int offset = (col - 1) * m; // note: col is 1-based
        for (int i = 0; i < m; i++) {
          res.set(i, array.getRef(offset + i));
        }
        return res;
      } catch (UnexpectedResultException e) {
        SelectorNode[] selectorExprs = new SelectorNode[nSelectors];
        for (int i = 0; i < nSelectors - 1; i++) {
          selectorExprs[i] = Selector.createSelectorNode(ast, true, null);
        }
        selectorExprs[nSelectors - 1] = Selector.createSelectorNode(ast, true, columnExpr);
        GenericRead gr = new GenericRead(ast, true, lhs, selectorExprs, dropExpr, exactExpr);
        replace(gr, "install GenericRead from ArrayColumnSubset");
        for (int i = 0; i < nSelectors - 1; i++) {
          gr.selectorVals[i] = selectorExprs[i].executeSelector(frame);
        }
        gr.selectorVals[nSelectors - 1] = selectorExprs[nSelectors - 1].executeSelector(colVal);
        return gr.executeLoop(array, dropVal, exactVal);
      }
    }
Example #22
0
        public RAny outer(Frame frame, RAny xarg, RAny yarg, RAny farg) {
            // LICENSE: transcribed code from GNU R, which is licensed under GPL

            if (!(xarg instanceof RArray && yarg instanceof RArray)) {
                Utils.nyi("unsupported type");
                return null;
            }

            RArray x = (RArray) xarg;
            RArray y = (RArray) yarg;

            int xsize = x.size();
            int ysize = y.size();

            RArray expy;
            RArray expx;

            if (EAGER) {
                x = x.materialize(); // FIXME: probably unnecessary (both x and y), could be done on-the-fly in the expansion methods
                y = y.materialize();
                if (y instanceof DoubleImpl) {
                    expy = expandYVector((DoubleImpl) y, ysize, xsize);
                } else if (y instanceof IntImpl) {
                    expy = expandYVector((IntImpl) y, ysize, xsize);
                } else {
                    expy = expandYVector(y, ysize, xsize);
                }

                if (xsize > 0) {
                    if (x instanceof DoubleImpl) {
                        expx = expandXVector((DoubleImpl) x, xsize, ysize);
                    } else if (x instanceof IntImpl) {
                        expx = expandXVector((IntImpl) x, xsize, ysize);
                    } else {
                        expx = expandXVector(x, xsize, ysize);
                    }
                } else {
                    expx = x;
                }
            } else {
                if (y instanceof RInt) {
                    expy = lazyExpandYVector((RInt) y, ysize, xsize);
                } else {
                    throw Utils.nyi();
                }
                if (xsize > 0) {
                    if (x instanceof RInt) {
                        expx = lazyExpandXVector((RInt) x, xsize, ysize);
                    } else {
                        throw Utils.nyi();
                    }
                } else {
                    expx = x;
                }
            }

            xArgProvider.setValue(expx);
            yArgProvider.setValue(expy);
            callableProvider.matchAndSet(frame, farg);
            RArray res = (RArray) callNode.execute(frame);

            int[] dimx = x.dimensions();
            int[] dimy = y.dimensions();

            int[] dim;
            if (dimx == null) {
                if (dimy == null) {
                    dim = new int[]{xsize, ysize};
                } else {
                    dim = new int[1 + dimy.length];
                    dim[0] = xsize;
                    System.arraycopy(dimy, 0, dim, 1, dimy.length);
                }
            } else {
                if (dimy == null) {
                    dim = new int[dimx.length + 1];
                    System.arraycopy(dimx, 0, dim, 0, dimx.length);
                    dim[dimx.length] = ysize;
                } else {
                    dim = new int[dimx.length + dimy.length];
                    System.arraycopy(dimx, 0, dim, 0, dimx.length);
                    System.arraycopy(dimy, 0, dim, dimx.length, dimy.length);
                }
            }
            return res.setDimensions(dim); // triggers materialization of the result
        }
Example #23
0
 public int countNodes() {
   return root.countNodes();
 }
Example #24
0
 public void cleanVisitedNodes() {
   root.cleanVisitedNodes();
   visitedNodes = BigInteger.ZERO;
 }
Example #25
0
  /** Overhang scars helper * */
  private ArrayList<String> assignScarsHelper(RNode parent, ArrayList<RNode> children) {

    ArrayList<String> scars = new ArrayList<String>();

    // Loop through each one of the children to assign rule-instructed overhangs... enumerated
    // numbers currently
    for (int i = 0; i < children.size(); i++) {

      RNode child = children.get(i);

      if (i > 0) {
        if (child.getLOverhang().isEmpty()) {
          scars.add("_");
        }
        scars.add("BB");
      }

      // Make recursive call
      if (child.getStage() > 0) {

        // Remove the current parent from the list
        ArrayList<RNode> grandChildren = new ArrayList<RNode>();
        grandChildren.addAll(child.getNeighbors());
        if (grandChildren.contains(parent)) {
          grandChildren.remove(parent);
        }

        ArrayList<String> childScars = assignScarsHelper(child, grandChildren);
        scars.addAll(childScars);
      } else {

        ArrayList<String> childScars = new ArrayList<String>();
        if (child.getComposition().size() > 1) {
          if (!child.getScars().isEmpty()) {
            childScars.addAll(child.getScars());
          } else {

            for (int j = 0; j < child.getComposition().size() - 1; j++) {
              childScars.add("_");
            }
            child.setScars(childScars);
          }
        }
        scars.addAll(childScars);
      }
    }

    // Keep scars for re-used parts with scars
    if (!scars.isEmpty()) {
      parent.setScars(scars);
      return scars;
    } else {
      return parent.getScars();
    }
  }
Example #26
0
  /** Generation of new BioBricks primers for parts * */
  public static String[] generatePartPrimers(
      RNode node,
      Collector coll,
      Double meltingTemp,
      Integer targetLength,
      Integer minPCRLength,
      Integer maxPrimerLength) {

    // initialize primer parameters
    String[] oligos = new String[2];
    String partPrimerPrefix = "gaattcgcggccgcttctagag";
    String partPrimerSuffix = "tactagtagcggccgctgcag";
    String partPrimerPrefixAlt = "gaattcgcggccgcttctag";
    String forwardOligoSequence;
    String reverseOligoSequence;

    Part currentPart = coll.getPart(node.getUUID(), true);
    String seq = currentPart.getSeq();
    ArrayList<String> type = node.getType();
    String fwdHomology;
    String revHomology;

    // If the part is sufficiently large
    if (seq.length() > minPCRLength) {

      // Special case primers for coding sequences
      if (type.get(0).equals("gene") || type.get(0).equals("reporter")) {
        fwdHomology =
            seq.substring(
                0,
                Math.min(
                    seq.length(),
                    PrimerDesign.getPrimerHomologyLength(
                        meltingTemp, targetLength, maxPrimerLength - 20, minPCRLength, seq, true)));
        revHomology =
            seq.substring(
                Math.max(
                    0,
                    currentPart.getSeq().length()
                        - PrimerDesign.getPrimerHomologyLength(
                            meltingTemp,
                            targetLength,
                            maxPrimerLength - 21,
                            minPCRLength,
                            PrimerDesign.reverseComplement(seq),
                            true)));
        forwardOligoSequence = partPrimerPrefixAlt + fwdHomology;
        reverseOligoSequence = PrimerDesign.reverseComplement(revHomology + partPrimerSuffix);

      } else {
        if (seq.equals("")) {
          fwdHomology = "[ PART " + currentPart.getName() + " HOMOLOGY REGION ]";
          revHomology = "[ PART " + currentPart.getName() + " HOMOLOGY REGION ]";
        } else {
          fwdHomology =
              seq.substring(
                  0,
                  Math.min(
                      seq.length(),
                      PrimerDesign.getPrimerHomologyLength(
                          meltingTemp,
                          targetLength,
                          maxPrimerLength - 22,
                          minPCRLength,
                          seq,
                          true)));
          revHomology =
              seq.substring(
                  Math.max(
                      0,
                      currentPart.getSeq().length()
                          - PrimerDesign.getPrimerHomologyLength(
                              meltingTemp,
                              targetLength,
                              maxPrimerLength - 21,
                              minPCRLength,
                              PrimerDesign.reverseComplement(seq),
                              true)));
        }
        forwardOligoSequence = partPrimerPrefix + fwdHomology;
        reverseOligoSequence = PrimerDesign.reverseComplement(revHomology + partPrimerSuffix);
      }

      // Otherwise make annealing primers or synthesize
    } else {
      if (type.get(0).equals("gene") || type.get(0).equals("reporter")) {

        if (seq.equals("")) {
          fwdHomology = "[ PART " + currentPart.getName() + " HOMOLOGY REGION ]";
          revHomology = "[ PART " + currentPart.getName() + " HOMOLOGY REGION ]";
          forwardOligoSequence = partPrimerPrefixAlt + fwdHomology;
          reverseOligoSequence = PrimerDesign.reverseComplement(partPrimerSuffix) + revHomology;
        } else {
          fwdHomology = seq;
          forwardOligoSequence = partPrimerPrefixAlt + fwdHomology + partPrimerSuffix;
          reverseOligoSequence = PrimerDesign.reverseComplement(forwardOligoSequence);
        }

      } else {

        if (seq.equals("")) {
          fwdHomology = "[ PART " + currentPart.getName() + " HOMOLOGY REGION ]";
          revHomology = "[ PART " + currentPart.getName() + " HOMOLOGY REGION ]";
          forwardOligoSequence = partPrimerPrefix + fwdHomology;
          reverseOligoSequence = PrimerDesign.reverseComplement(partPrimerSuffix) + revHomology;
        } else {
          fwdHomology = seq;
          forwardOligoSequence = partPrimerPrefix + fwdHomology + partPrimerSuffix;
          reverseOligoSequence = PrimerDesign.reverseComplement(forwardOligoSequence);
        }
      }
    }

    oligos[0] = forwardOligoSequence;
    oligos[1] = reverseOligoSequence;

    return oligos;
  }
Example #27
0
    @Override public RNode create(ASTNode call, RSymbol[] names, RNode[] exprs) {
        ArgumentInfo ia = check(call, names, exprs);
        boolean product = false;
        if (ia.provided("FUN")) {
            RNode fnode = exprs[ia.position("FUN")];
            if (fnode instanceof Constant) {
                RAny value = ((Constant) fnode).execute(null);
                if (value instanceof RString) {
                    RString str = (RString) value;
                    if (str.size() == 1) {
                        if (str.getString(0).equals("*")) {
                            product = true;
                        }
                    }
                }
            }
        } else {
            product = true;
        }
        if (product) {
            return new MatrixOperation.OuterProduct(call, exprs[ia.position("X")], exprs[ia.position("Y")]);
        }

        int cnArgs = 2 + names.length - 3; // "-2" because both FUN, X, Y
        RSymbol[] cnNames = new RSymbol[cnArgs];
        RNode[] cnExprs = new RNode[cnArgs];
        cnNames[0] = null;
        ValueProvider xArgProvider = new ValueProvider(call);
        cnExprs[0] = xArgProvider;
        ValueProvider yArgProvider = new ValueProvider(call);
        cnExprs[1] = yArgProvider;
        ValueProvider[] constantArgProviders = new ValueProvider[cnArgs];
        int j = 0;
        for (int i = 0; i < names.length; i++) {
            if (ia.position("X") == i || ia.position("Y") == i || ia.position("FUN") == i) {
                continue;
            }
            cnNames[2 + j] = names[i];
            ValueProvider vp = new ValueProvider(call);
            cnExprs[2 + j] = vp;
            constantArgProviders[j] = vp;
            j++;
        }

        RNode funExpr = exprs[ia.position("FUN")];
        final CallableProvider callableProvider = new CallableProvider(funExpr.getAST(), funExpr);
        final RNode callNode = FunctionCall.getFunctionCall(call, callableProvider, cnNames, cnExprs);
        final int posX = ia.position("X");
        final int posY = ia.position("Y");
        final int posFUN = ia.position("FUN");

        return new OuterBuiltIn(call, names, exprs, callNode, callableProvider, xArgProvider, yArgProvider, constantArgProviders) {
            @Override public RAny doBuiltIn(Frame frame, RAny[] args) {
                RAny argx = null;
                RAny argy = null;
                RAny argfun = null;
                int k = 0;
                for (int i = 0; i < args.length; i++) {
                    if (i == posX) {
                        argx = args[i];
                    } else if (i == posY) {
                        argy = args[i];
                    } else if (i == posFUN) {
                        argfun = args[i];
                    } else {
                        constantArgProviders[k].setValue(args[i]);
                        k++;
                    }
                }
                return outer(frame, argx, argy, argfun);
            }
        };
    }
 @Override
 public final Object execute(Frame frame) {
   RAny leftValue = (RAny) left.execute(frame);
   RAny rightValue = (RAny) right.execute(frame);
   return execute(leftValue, rightValue);
 }