@Test
  public void replaceColumnDetectedCorrectly() throws StructureGraphComparisonException {
    ISqlSchemaFrontend frontend1 = new H2SchemaFrontend(DATABASE_FILE_PATH);
    ISqlSchemaFrontend frontend2 = new H2SchemaFrontend(REPLACE_COLUMN_DATABASE_FILE_PATH);
    DirectedGraph<IStructureElement, DefaultEdge> schema1 = frontend1.createSqlSchema();
    DirectedGraph<IStructureElement, DefaultEdge> schema2 = frontend2.createSqlSchema();
    SqlSchemaComparer comparer = new SqlSchemaComparer(schema1, schema2);
    SqlSchemaComparisonResult result = comparer.comparisonResult;

    assertEquals(
        29,
        SqlElementFactory.getSqlElementsOfType(SqlColumnVertex.class, schema1.vertexSet()).size());
    assertEquals(
        29,
        SqlElementFactory.getSqlElementsOfType(SqlColumnVertex.class, schema2.vertexSet()).size());

    Entry<ISqlElement, SchemaModification> renameColumnEntry =
        TestHelper.getModificationOfType(result, SchemaModification.RENAME_COLUMN);
    Entry<ISqlElement, SchemaModification> replaceColumnTypeEntry =
        TestHelper.getModificationOfType(result, SchemaModification.CHANGE_COLUMN_TYPE);

    assertNotNull(renameColumnEntry);
    assertEquals(REPLACE_COLUMN_NAME, renameColumnEntry.getKey().getName());
    assertNotNull(replaceColumnTypeEntry);
    assertEquals(
        REPLACE_COLUMN_TYPE, ((ColumnTypeVertex) replaceColumnTypeEntry.getKey()).getColumnType());
  }
  @Test
  public void databaseConnectionEstablishedCorrectly() {
    ISqlSchemaFrontend frontend = new H2SchemaFrontend(DATABASE_FILE_PATH);
    DirectedGraph<IStructureElement, DefaultEdge> schema = frontend.createSqlSchema();
    Set<ISqlElement> tables =
        SqlElementFactory.getSqlElementsOfType(SqlTableVertex.class, schema.vertexSet());
    Set<ISqlElement> columns =
        SqlElementFactory.getSqlElementsOfType(SqlColumnVertex.class, schema.vertexSet());
    ArrayList<ISqlElement> mandatoryColumns = new ArrayList<>();
    int tableCount = tables.size();
    int columnCount = columns.size();

    for (ISqlElement column : columns) {
      if (column.isMandatory() && !isPrimaryKey(schema, column)) {
        mandatoryColumns.add(column);
      }
    }

    assertNotNull(schema);
    assertEquals(7, tableCount);
    assertEquals(29, columnCount);
    assertEquals(
        7,
        TestHelper.getColumnWithConstraint(schema, IColumnConstraint.ConstraintType.PRIMARY_KEY)
            .size());
    assertEquals(1, mandatoryColumns.size());
    assertEquals("[Column] DEPARTMENTS.NAME", mandatoryColumns.get(0).toString());
  }
  /*
   * Creates a VertexData object for every vertex in the graph and stores
   * them
   * in a HashMap.
   */
  private void createVertexData() {
    vertexToVertexData = new HashMap<V, VertexData<V>>(graph.vertexSet().size());

    for (V vertex : graph.vertexSet()) {
      vertexToVertexData.put(vertex, new VertexData2<V>(vertex, false, false));
    }
  }
  @Test
  public void replaceLobWithTable() throws StructureGraphComparisonException {
    ISqlSchemaFrontend frontend1 = new H2SchemaFrontend(DATABASE_FILE_PATH);
    ISqlSchemaFrontend frontend2 = new H2SchemaFrontend(REPLACE_LOB_WITH_TABLE_DATABASE_FILE_PATH);
    DirectedGraph<IStructureElement, DefaultEdge> schema1 = frontend1.createSqlSchema();
    DirectedGraph<IStructureElement, DefaultEdge> schema2 = frontend2.createSqlSchema();
    SqlSchemaComparer comparer = new SqlSchemaComparer(schema1, schema2);
    SqlSchemaComparisonResult result = comparer.comparisonResult;

    assertEquals(
        29,
        SqlElementFactory.getSqlElementsOfType(SqlColumnVertex.class, schema1.vertexSet()).size());
    assertEquals(
        33,
        SqlElementFactory.getSqlElementsOfType(SqlColumnVertex.class, schema2.vertexSet()).size());

    for (Entry<ISqlElement, SchemaModification> entry : result.getModifications().entrySet()) {
      if (entry.getValue() == SchemaModification.CREATE_TABLE) {
        assertEquals(REPLACE_LOB_WITH_TABLE, entry.getKey().getName());
      }

      if (entry.getValue() == SchemaModification.DELETE_COLUMN) {
        assertEquals(REPLACE_LOB_WITH_COLUMN, entry.getKey().getName());
      }
    }
  }
  /** HG: measures time needed to check a pair of huge random graphs */
  @Test
  public void testHugeGraph() {
    int n = 700;
    long time = System.currentTimeMillis();

    DirectedGraph<Integer, DefaultEdge>
        g1 = SubgraphIsomorphismTestUtils.randomGraph(n, n * n / 50, 12345),
        g2 = SubgraphIsomorphismTestUtils.randomSubgraph(g1, n / 2, 54321);

    VF2SubgraphIsomorphismInspector<Integer, DefaultEdge> vf2 =
        new VF2SubgraphIsomorphismInspector<>(g1, g2);

    assertEquals(true, vf2.isomorphismExists());

    SubgraphIsomorphismTestUtils.showLog(
        "|V1| = "
            + g1.vertexSet().size()
            + ", |E1| = "
            + g1.edgeSet().size()
            + ", |V2| = "
            + g2.vertexSet().size()
            + ", |E2| = "
            + g2.edgeSet().size()
            + " - "
            + (System.currentTimeMillis() - time)
            + "ms");
  }
  private void specifyMinimalSignatureValues() {
    vertSet = graph.vertexSet();
    tops = getTopObjects(children, parents);
    bottoms = getBottomObjects(children, parents);
    setTopsAndBottoms();
    completeGraphWithTopAndBottom();
    System.out.println("--------------------------------------------");

    // depth-search
    // results of deph-search save as depthResult
    depthSearch();

    // breadth-search
    // results of breadth-search save as resultTuple
    // results as a node- signatures, in the form of ArrayList<Integer>
    breadthSearch();

    // positions, wich contain only zero-values have to be removed
    // array with max positions- value is saved as max_values_array

    maxValuesArray = new int[length];

    removeMaxZeroPositions();

    System.out.println("Signatures: ");
    for (Object s : signatures.keySet()) {
      System.out.println(s + " :" + signatures.get(s).toString());
    }
    System.out.println("\n ################################################################");

    signatureLength = signatureLength + combinedSignatureLength();
  }
 public void testZeroNodes() {
   GraphGenerator<Integer, DefaultEdge, Integer> gen =
       new GnpRandomBipartiteGraphGenerator<>(0, 0, 0.5);
   DirectedGraph<Integer, DefaultEdge> g = new DirectedPseudograph<>(DefaultEdge.class);
   gen.generateGraph(g, new IntegerVertexFactory(), null);
   assertEquals(0, g.vertexSet().size());
   assertEquals(0, g.edgeSet().size());
 }
 private JavaClass findClass(String classname) {
   for (JavaClass jClass : graph.vertexSet()) {
     if (jClass.getName().equals(classname)) {
       return jClass;
     }
   }
   return null;
 }
 public Set<String> getIndexedClasses() {
   Set<String> classes = newHashSet();
   Set<JavaClass> vertexSet = graph.vertexSet();
   for (JavaClass each : vertexSet) {
     classes.add(each.getName());
   }
   return classes;
 }
  public void testDirectedGraphGnp2() {
    GraphGenerator<Integer, DefaultEdge, Integer> gen =
        new GnpRandomBipartiteGraphGenerator<>(4, 4, 1.0, SEED);
    DirectedGraph<Integer, DefaultEdge> g = new DirectedPseudograph<>(DefaultEdge.class);
    gen.generateGraph(g, new IntegerVertexFactory(), null);

    assertEquals(4 + 4, g.vertexSet().size());
    assertEquals(32, g.edgeSet().size());
  }
Exemple #11
0
  public static <V, E> void write(DirectedGraph<V, E> g, String fileName, EdgeFilter<E> filter)
      throws FileNotFoundException {
    PrintWriter out = new PrintWriter(fileName);

    // System.out.println("Writing '" + fileName + "'");

    out.print("digraph \"DirectedGraph\" { \n graph [label=\"");
    out.print(g.toString());
    out.print("\", labelloc=t, concentrate=true]; ");
    out.print("center=true;fontsize=12;node [fontsize=12];edge [fontsize=12]; \n");

    for (V node : g.vertexSet()) {
      out.print("   \"");
      out.print(getId(node));
      out.print("\" ");
      out.print("[label=\"");
      out.print(node.toString());
      out.print("\" shape=\"box\" color=\"blue\" ] \n");
    }

    for (V src : g.vertexSet()) {
      for (E e : g.outgoingEdgesOf(src)) {
        if (!filter.accept(e)) {
          continue;
        }

        V tgt = g.getEdgeTarget(e);

        out.print(" \"");
        out.print(getId(src));
        out.print("\" -> \"");
        out.print(getId(tgt));
        out.print("\" ");
        out.print("[label=\"");
        out.print(e.toString());
        out.print("\"]\n");
      }
    }

    out.print("\n}");

    out.flush();
    out.close();
  }
  @Test
  public void droppedColumnDetectedCorrectly() throws StructureGraphComparisonException {
    ISqlSchemaFrontend frontend1 = new H2SchemaFrontend(DATABASE_FILE_PATH);
    ISqlSchemaFrontend frontend2 = new H2SchemaFrontend(DROPPED_COLUMN_DATABASE_FILE_PATH);
    DirectedGraph<IStructureElement, DefaultEdge> schema1 = frontend1.createSqlSchema();
    DirectedGraph<IStructureElement, DefaultEdge> schema2 = frontend2.createSqlSchema();
    SqlSchemaComparer comparer = new SqlSchemaComparer(schema1, schema2);
    SqlSchemaComparisonResult result = comparer.comparisonResult;

    assertEquals(
        29,
        SqlElementFactory.getSqlElementsOfType(SqlColumnVertex.class, schema1.vertexSet()).size());
    assertEquals(
        28,
        SqlElementFactory.getSqlElementsOfType(SqlColumnVertex.class, schema2.vertexSet()).size());

    Entry<ISqlElement, SchemaModification> entry =
        TestHelper.getModificationOfType(result, SchemaModification.DELETE_COLUMN);

    assertNotNull(entry);
    assertEquals(DROPPED_COLUMN_NAME, entry.getKey().getName());
  }
  public void testDirectedGraphGnp3() {
    GraphGenerator<Integer, DefaultEdge, Integer> gen =
        new GnpRandomBipartiteGraphGenerator<>(4, 4, 0.1, SEED);
    DirectedGraph<Integer, DefaultEdge> g = new DirectedPseudograph<>(DefaultEdge.class);
    gen.generateGraph(g, new IntegerVertexFactory(), null);

    int[][] edges = {{5, 1}, {7, 3}, {3, 8}, {8, 4}};

    assertEquals(4 + 4, g.vertexSet().size());
    for (int[] e : edges) {
      assertTrue(g.containsEdge(e[0], e[1]));
    }
    assertEquals(edges.length, g.edgeSet().size());
  }
  @Test
  public void droppedTableDetectedCorrectly() throws StructureGraphComparisonException {
    ISqlSchemaFrontend frontend1 = new H2SchemaFrontend(DATABASE_FILE_PATH);
    ISqlSchemaFrontend frontend2 = new H2SchemaFrontend(DROPPED_TABLE_DATABASE_FILE_PATH);
    DirectedGraph<IStructureElement, DefaultEdge> schema1 = frontend1.createSqlSchema();
    DirectedGraph<IStructureElement, DefaultEdge> schema2 = frontend2.createSqlSchema();
    SqlSchemaComparer comparer = new SqlSchemaComparer(schema1, schema2);
    SqlSchemaComparisonResult result = comparer.comparisonResult;

    assertEquals(
        7,
        SqlElementFactory.getSqlElementsOfType(SqlTableVertex.class, schema1.vertexSet()).size());
    assertEquals(
        6,
        SqlElementFactory.getSqlElementsOfType(SqlTableVertex.class, schema2.vertexSet()).size());

    for (Entry<ISqlElement, SchemaModification> entry : result.getModifications().entrySet()) {
      if (entry.getValue() == SchemaModification.DELETE_TABLE) {
        assertEquals(SchemaModification.DELETE_TABLE, entry.getValue());
        assertEquals(DROPPED_TABLE_NAME, entry.getKey().getName());
      }
    }
  }
Exemple #15
0
  /** string graph representations */
  @SuppressWarnings("unused")
  private static String toCustomRepr(DirectedGraph<String, DefaultEdge> g) {

    StringBuffer sb = new StringBuffer();
    sb.append("Vertex set:");
    sb.append(g.vertexSet());

    Set<DefaultEdge> edges = g.edgeSet();
    sb.append("\nEdge set:");
    for (DefaultEdge e : edges) {
      sb.append(e);
    }

    return sb.toString();
  }
  private void buildStandardGraph() {
    ArrayList<OrderedPair> orderedpairList = orderedPairOrder.getListOfPairs();
    for (int i = 0; i < orderedpairList.size(); i++) {

      // if the nodes do not exists --> add them
      if (orderedpairList.get(i).getChild() != null
          && !(graph.containsVertex(orderedpairList.get(i).getChild()))) {

        graph.addVertex(orderedpairList.get(i).getChild());
      }

      if (orderedpairList.get(i).getChild() != null) {
        if (orderedpairList.get(i).getParent() == null) {
        } else if (!children.contains(orderedpairList.get(i).getChild())) {
          children.add(orderedpairList.get(i).getChild());
        }
      }
      if (orderedpairList.get(i).getParent() != null
          && !(graph.containsVertex(orderedpairList.get(i).getParent()))) {

        graph.addVertex(orderedpairList.get(i).getParent());
      }
      if (orderedpairList.get(i).getParent() != null
          && !parents.contains(orderedpairList.get(i).getParent())) {
        parents.add(orderedpairList.get(i).getParent());
      }

      // fuegt Kante hinzu, falls beide Knoten nicht NULL sind
      if (orderedpairList.get(i).getParent() != null && orderedpairList.get(i).getChild() != null) {
        graph.addEdge(orderedpairList.get(i).getParent(), orderedpairList.get(i).getChild());
        System.out.println(
            orderedpairList.get(i).getParent() + " -> " + orderedpairList.get(i).getChild());
      }
    }
    DirectedGraph<Object, DefaultEdge> temp_gr = new DefaultDirectedGraph<>(DefaultEdge.class);
    for (Object o : graph.vertexSet()) {
      temp_gr.addVertex(o);
    }
    for (DefaultEdge e : graph.edgeSet()) {
      temp_gr.addEdge(graph.getEdgeSource(e), graph.getEdgeTarget(e));
    }
    originalGraph.add(temp_gr);
  }
  private CModel CreateBiochemicalReactions(
      DirectedGraph<Object, ObjectEdge> circuitGraph, String inputFileBase) {
    CCopasiDataModel dataModel = CCopasiRootContainer.addDatamodel();
    CModel model = dataModel.getModel();
    // set the units for the model
    model.setTimeUnit(CModel.s);
    model.setVolumeUnit(CModel.microl);
    model.setQuantityUnit(CModel.nMol);
    /* we have to keep a set of all the initial values that are changed during the model building process.
    They are needed after the model has been built to make sure all initialvalues are set to the correct initial value */
    ObjectStdVector changedObjects = new ObjectStdVector();
    CCompartment compartment = model.createCompartment("tube", 10.0);
    CCopasiObject object = compartment.getInitialValueReference();
    changedObjects.add(object);

    // create metabolites for all inputs
    // Object root = circuitGraph.getRoot();
    Map<String, CMetab> metabolitesMap = new HashMap<String, CMetab>();
    for (Object vertexObj : circuitGraph.vertexSet()) {
      if (vertexObj instanceof PhysicalPortPin) {
        PhysicalPortPin pin = (PhysicalPortPin) vertexObj;
        int cmet;
        cmet = CMetab.REACTIONS;
        //                if (pin.getDirection() == Direction.OUT) {
        //                    cmet = CMetab.REACTIONS;
        //                } else {
        //                    cmet = CMetab.FIXED;
        //                }
        CMetab metabolite =
            model.createMetabolite(fixId(pin.getName()), compartment.getObjectName(), 10.0, cmet);
        System.out.println("Metabolite: " + fixId(pin.getName()));
        metabolitesMap.put(pin.getName(), metabolite);
        changedObjects.add(metabolite.getInitialValueReference());
      } else if (vertexObj instanceof PLDConfigurableElement) {
        PLDConfigurableElement pldCell = (PLDConfigurableElement) vertexObj;
        for (ChannelAbstract channel :
            pldCell.getInterfaceComponent().getChannels()) { //   .getPins()) {
          for (CPSPort pin : channel.getPorts()) { //   .getPins()) {
            // if (pin.getDirection() == Direction.OUT) { // output pins will became a metabolite
            int cmet;
            cmet = CMetab.REACTIONS;
            CMetab metabolite =
                model.createMetabolite(
                    fixId(pin.getName()), compartment.getObjectName(), 10.0, cmet);
            System.out.println("Metabolite: " + fixId(pin.getName()));
            metabolitesMap.put(pin.getName(), metabolite);
            changedObjects.add(metabolite.getInitialValueReference());
            // }
          }
        }
      }
    }
    //        for (Object vertexObj : circuitGraph.vertexSet()) {
    //            if (vertexObj instanceof PLDConfigurableCellElement) {
    //                PLDConfigurableCellElement pldCell = (PLDConfigurableCellElement) vertexObj;
    //                for (HardwarePortPin pin : pldCell.getInterfaceComponent().getPins()) {
    //                    CMetab metabolite;
    //                    if (pin.getDirection() == Direction.IN) { // output pins will became a
    // metabolite
    //                        Set<ObjectEdge> edges = circuitGraph.edgesOf(vertexObj);
    //                        for (ObjectEdge edge : edges) {
    //                            HardwareCommunicationNet hardwareNet = (HardwareCommunicationNet)
    // edge.getUserObject();
    //                            for (HardwarePortBase port : hardwareNet.getTargets()) {
    //                                if (port.equals(pin)) {
    //                                    hardwareNet.getSource();
    //                                    //metabolite = hardwareNet.getSource();
    //                                }
    //                            }
    //                        }
    //                    }
    //                }
    //            }
    //        }

    // create chemical reactions
    for (Object vertex : circuitGraph.vertexSet()) {
      if (vertex instanceof PLDConfigurableElement) {
        PLDConfigurableElement pldCell = (PLDConfigurableElement) vertex;
        CReaction reaction = model.createReaction("reaction_" + fixId(pldCell.getName()));
        System.out.println("Reaction: " + reaction.getKey());
        CChemEq chemEquation = reaction.getChemEq();
        int func;
        int numSubst = 0;
        int numProd = 0;
        for (ChannelAbstract channel : pldCell.getInterfaceComponent().getChannels()) {
          for (CPSPort pin : channel.getPorts()) {
            CMetab met = metabolitesMap.get(pin.getName());
            assert met != null;
            if (pin.getDirection() == Direction.OUT) {
              func = CChemEq.PRODUCT;
              numProd++;
            } else {
              func = CChemEq.SUBSTRATE;
              numSubst++;
            }
            chemEquation.addMetabolite(met.getKey(), 1.0, func);
            System.out.println("      Metabolite: " + fixId(pin.getName()) + "  " + func);
          }
          CompleteReaction(reaction, numSubst, numProd);
        }
      }
    }
    for (ObjectEdge edge : circuitGraph.edgeSet()) {
      PhysicalCommunicationNet net = (PhysicalCommunicationNet) edge.getUserObject();
      CReaction reaction =
          model.createReaction("reaction_transfer_" + fixId(net.getSource().getName()));
      System.out.println("Reaction: " + reaction.getKey());
      CChemEq chemEquation = reaction.getChemEq();
      CMetab metSubs = metabolitesMap.get(net.getSource().getName());
      chemEquation.addMetabolite(metSubs.getKey(), 1.0, CChemEq.SUBSTRATE);
      int numSubst = 1;
      int numProd = net.getTargets().size();
      for (PhysicalPortBase targetport : net.getTargets()) {
        CMetab metProd = metabolitesMap.get(targetport.getName());
        chemEquation.addMetabolite(metProd.getKey(), 1.0, CChemEq.PRODUCT);
      }
      CompleteReaction(reaction, numSubst, numProd);
    }

    model.compileIfNecessary();

    // now that we are done building the model, we have to make sure all initial values are updated
    // according to their dependencies
    model.updateInitialValues(changedObjects);
    // save the model to a COPASI file
    String filename = Traits.getTEMP_PATHNAME() + inputFileBase + "_chemical_reactions.cps";

    dataModel.saveModel(filename, true);
    // export the model to an SBML file and we want SBML L2V3
    try {
      // String SBML = dataModel.exportSBMLToString();
      // System.out.println("NAO OCORREU CORE DUMP NO JNI!!!: "+SBML);
      // dataModel.exportSBML(Traits.getTEMP_PATHNAME() + inputFileBase +
      // "_chemical_reactions.xml");
      // dataModel.exportSBML(Traits.getTEMP_PATHNAME() + inputFileBase + "_chemical_reactions.xml",
      // true, 2, 3);
    } catch (java.lang.Exception ex) {
      System.err.println("Error. Exporting the model to SBML failed.");
    }
    return model;
  }
Exemple #18
0
    @Override
    public String process(File page, Map<String, String> query) {
      loadContigs();

      if (query.get("contigName").matches("^[ACGT]+$")) {
        contigs.put("manual", query.get("contigName"));
        query.put("contigName", "manual");
      } else if (query.get("contigName").matches("^Pf3D7.+$")) {
        String[] pieces = query.get("contigName").split("[:-]");

        int start = Integer.valueOf(pieces[1].replaceAll(",", ""));
        int end = Integer.valueOf(pieces[2].replaceAll(",", ""));

        ReferenceSequence rseq = REF.getSubsequenceAt(pieces[0], start, end);
        contigs.put("manual", new String(rseq.getBases()));
        query.put("contigName", "manual");
      }

      if (query.containsKey("contigName")
          && contigs.containsKey(query.get("contigName"))
          && graphs.containsKey(query.get("graphName"))) {
        boolean showLinks = query.get("showLinks").equals("links_on");

        String contig = contigs.get(query.get("contigName"));
        String originalContig = contigs.get(query.get("contigName"));
        String refFormattedString = "";
        String kmerOrigin = "";

        if (metrics.containsKey(query.get("contigName"))) {
          String[] loc = metrics.get(query.get("contigName")).get("canonicalLocus").split("[:-]");
          if (!loc[0].equals("*")) {
            boolean isRc = metrics.get(query.get("contigName")).get("isRcCanonical").equals("1");

            if (isRc) {
              contig = SequenceUtils.reverseComplement(contig);
              originalContig = SequenceUtils.reverseComplement(originalContig);
            }

            int locStart = Integer.valueOf(loc[1]);
            int locEnd = Integer.valueOf(loc[2]);

            Cigar cigar =
                cigarStringToCigar(metrics.get(query.get("contigName")).get("cigarCanonical"));
            if (cigar.getCigarElement(0).getOperator().equals(CigarOperator.S)) {
              locStart -= cigar.getCigarElement(0).getLength();
            }

            if (cigar
                .getCigarElement(cigar.getCigarElements().size() - 1)
                .getOperator()
                .equals(CigarOperator.S)) {
              locEnd += cigar.getCigarElement(cigar.getCigarElements().size() - 1).getLength();
            }

            String ref = new String(REF.getSubsequenceAt(loc[0], locStart, locEnd).getBases());

            StringBuilder refFormatted = new StringBuilder();
            int pos = 0;
            for (CigarElement ce : cigar.getCigarElements()) {
              CigarOperator co = ce.getOperator();
              switch (co) {
                case S:
                  refFormatted.append(ref.substring(pos, pos + ce.getLength()).toLowerCase());
                  break;
                case M:
                  refFormatted.append(ref.substring(pos, pos + ce.getLength()));
                  break;
                case I:
                  refFormatted.append(StringUtils.repeat("-", ce.getLength()));
                  break;
              }

              if (ce.getOperator().consumesReferenceBases()) {
                pos += ce.getLength();
              }
            }

            refFormattedString = refFormatted.toString();

            kmerOrigin = metrics.get(query.get("contigName")).get("kmerOrigin");
          }
        }

        CortexGraph cg = graphs.get(query.get("graphName"));

        String sampleName = cg.getColor(0).getSampleName();
        Set<CortexLinksMap> links = new HashSet<CortexLinksMap>();
        if (LINKS != null && !LINKS.isEmpty()) {
          for (CortexLinksMap link : LINKS) {
            if (sampleName.equals(link.getCortexLinks().getColor(0).getSampleName())) {
              links.add(link);
            }
          }
        }

        Set<String> contigKmers = new HashSet<String>();
        for (int i = 0; i <= contig.length() - cg.getKmerSize(); i++) {
          String curKmer = contig.substring(i, i + cg.getKmerSize());

          contigKmers.add(curKmer);
        }

        StringBuilder firstFlank = new StringBuilder();
        String firstKmer = contig.substring(0, cg.getKmerSize());
        Set<String> pks = CortexUtils.getPrevKmers(cg, firstKmer, 0);
        Set<String> usedPrevKmers = new HashSet<String>();
        usedPrevKmers.add(firstKmer);
        while (pks.size() == 1 && usedPrevKmers.size() <= 100) {
          String kmer = pks.iterator().next();
          firstFlank.insert(0, kmer.charAt(0));

          if (usedPrevKmers.contains(kmer)) {
            break;
          }
          usedPrevKmers.add(kmer);

          pks = CortexUtils.getPrevKmers(cg, kmer, 0);
        }

        StringBuilder lastFlank = new StringBuilder();
        String lastKmer = contig.substring(contig.length() - cg.getKmerSize(), contig.length());
        Set<String> nks = CortexUtils.getNextKmers(cg, lastKmer, 0);
        Set<String> usedNextKmers = new HashSet<String>();
        usedNextKmers.add(lastKmer);
        while (nks.size() == 1 && usedNextKmers.size() <= 100) {
          String kmer = nks.iterator().next();
          lastFlank.append(kmer.charAt(kmer.length() - 1));

          if (usedNextKmers.contains(kmer)) {
            break;
          }
          usedNextKmers.add(kmer);

          nks = CortexUtils.getNextKmers(cg, kmer, 0);
        }

        contig = firstFlank.toString() + contig + lastFlank.toString();

        DirectedGraph<CtxVertex, MultiEdge> g =
            new DefaultDirectedGraph<CtxVertex, MultiEdge>(MultiEdge.class);
        for (int i = 0; i <= contig.length() - cg.getKmerSize(); i++) {
          String curKmer = contig.substring(i, i + cg.getKmerSize());
          CortexKmer ck = new CortexKmer(curKmer);
          CtxVertex curVer =
              new CtxVertex(
                  curKmer,
                  i,
                  contigKmers.contains(curKmer) ? VertexType.CONTIG : VertexType.CLIPPED,
                  cg.findRecord(ck));

          g.addVertex(curVer);

          String expectedPrevKmer =
              (i > 0) ? contig.substring(i - 1, i - 1 + cg.getKmerSize()) : "";
          String expectedNextKmer =
              (i < contig.length() - cg.getKmerSize())
                  ? contig.substring(i + 1, i + 1 + cg.getKmerSize())
                  : "";

          Set<String> prevKmers = CortexUtils.getPrevKmers(cg, curKmer, 0);
          for (String prevKmer : prevKmers) {
            if (!expectedPrevKmer.equals(prevKmer)) {
              CortexKmer pk = new CortexKmer(prevKmer);
              CtxVertex prevVer = new CtxVertex(prevKmer, i - 1, VertexType.IN, cg.findRecord(pk));

              MultiEdge me =
                  g.containsEdge(prevVer, curVer) ? g.getEdge(prevVer, curVer) : new MultiEdge();
              me.addGraphName(cg.getCortexFile().getName());

              g.addVertex(prevVer);
              g.addEdge(prevVer, curVer, me);
            }
          }

          Set<String> nextKmers = CortexUtils.getNextKmers(cg, curKmer, 0);
          for (String nextKmer : nextKmers) {
            if (!expectedNextKmer.equals(nextKmer)) {
              CortexKmer nk = new CortexKmer(nextKmer);
              CtxVertex nextVer = new CtxVertex(nextKmer, i + 1, VertexType.OUT, cg.findRecord(nk));

              MultiEdge me =
                  g.containsEdge(curVer, nextVer) ? g.getEdge(curVer, nextVer) : new MultiEdge();
              me.addGraphName(cg.getCortexFile().getName());

              g.addVertex(nextVer);
              g.addEdge(curVer, nextVer, me);
            }
          }
        }

        Set<Map<String, Object>> verticesWithLinks = new HashSet<Map<String, Object>>();
        DataFrame<String, String, Integer> hv = new DataFrame<String, String, Integer>(0);

        for (int q = 0; q <= contig.length() - cg.getKmerSize(); q++) {
          // String sk = cv.getBinaryKmer();
          String sk = contig.substring(q, q + cg.getKmerSize());
          CortexKmer ck = new CortexKmer(sk);

          for (CortexLinksMap link : links) {
            if (link.containsKey(ck)) {
              CortexLinksRecord clr = link.get(ck);
              Map<String, Integer> lc =
                  (!showLinks)
                      ? new HashMap<String, Integer>()
                      : CortexUtils.getKmersAndCoverageInLink(cg, sk, clr);

              Map<String, Object> entry = new HashMap<String, Object>();
              entry.put("kmer", sk);
              entry.put("lc", lc);

              verticesWithLinks.add(entry);

              if (showLinks) {
                for (CortexJunctionsRecord cjr : clr.getJunctions()) {
                  List<String> lk = CortexUtils.getKmersInLink(cg, sk, cjr);

                  for (int i = 0; i < lk.size(); i++) {
                    String kili = lk.get(i);

                    for (int j = 0; j < lk.size(); j++) {
                      String kilj = lk.get(j);

                      if (i != j) {
                        hv.set(kili, kilj, hv.get(kili, kilj) + cjr.getCoverage(0));
                      }
                    }
                  }
                }
              }
            }
          }
        }

        /*
        int hvMax = 0;
        Map<String, Integer> hvlin = new HashMap<String, Integer>();
        if (showLinks) {
            for (String kili : hv.getRowNames()) {
                for (String kilj : hv.getColNames()) {
                    int cov = hv.get(kili, kilj);

                    String id = kili + "_" + kilj;
                    hvlin.put(id, cov);

                    if (cov > hvMax) {
                        hvMax = cov;
                    }
                }
            }
        }
        */

        JSONObject jo = new JSONObject();
        jo.put("contig", contig);
        jo.put("originalContig", originalContig);
        jo.put("ref", refFormattedString);
        jo.put("kmerOrigin", kmerOrigin);
        jo.put("kmerSize", cg.getKmerSize());
        jo.put("clipStart", firstFlank.length());
        jo.put("clipEnd", contig.length() - lastFlank.length());

        List<Map<String, Object>> va = new ArrayList<Map<String, Object>>();
        for (CtxVertex v : g.vertexSet()) {
          Map<String, Object> vm = new HashMap<String, Object>();
          vm.put("base", v.getBase());
          vm.put("kmer", v.getKmer());
          vm.put("pos", v.getPos());
          vm.put("type", v.getVertexType().name());
          vm.put("missing", v.isMissingFromGraph());
          vm.put("cov", v.getCoverage());

          va.add(vm);
        }

        jo.put("vertices", va);
        jo.put("verticesWithLinks", verticesWithLinks);
        // jo.put("hvlin", hvlin);
        // jo.put("hvmax", hvMax);

        return jo.toString();
      }

      return null;
    }