Given a nucmer ref_start_hit and ref_end_hit, returns a new contig. Assumes that these hits can be used to circularise the reference contig of the hits using the query contig
187359
def _make_circularised_contig(self, ref_start_hit, ref_end_hit):
        ''''''
        assert ref_start_hit.ref_name == ref_end_hit.ref_name
        assert ref_start_hit.qry_name == ref_end_hit.qry_name


        qry_name = ref_start_hit.qry_name
        ref_name = ref_start_hit.ref_name
        ref_start_coords = ref_start_hit.ref_coords()
        ref_end_coords = ref_end_hit.ref_coords()

        if ref_start_coords.intersects(ref_end_coords):
            new_ctg = copy.copy(self.reassembly_contigs[qry_name])
            new_ctg.id = ref_name
            return new_ctg

        if ref_start_hit.on_same_strand():
            qry_start_coords = ref_end_hit.qry_coords()
            qry_end_coords = ref_start_hit.qry_coords()
            bases = self.original_contigs[ref_name][ref_start_coords.end+1:ref_end_coords.start] + \
                    self.reassembly_contigs[qry_name][qry_start_coords.start:qry_end_coords.end+1]
            return pyfastaq.sequences.Fasta(ref_name, bases)
        else:
            qry_start_coords = ref_start_hit.qry_coords()
            qry_end_coords = ref_end_hit.qry_coords()
            tmp_seq = pyfastaq.sequences.Fasta('x', self.reassembly_contigs[qry_name][qry_start_coords.start:qry_end_coords.end+1])
            tmp_seq.revcomp()
            return pyfastaq.sequences.Fasta(ref_name, self.original_contigs[ref_name][ref_start_coords.end+1:ref_end_coords.start] + tmp_seq.seq)
1027735
def _get_possible_circular_ref_contigs(self, nucmer_hits, log_fh=None, log_outprefix=None):
        ''''''
        writing_log_file = None not in [log_fh, log_outprefix]
        maybe_circular = {}
        all_nucmer_hits = []
        for l in nucmer_hits.values():
            all_nucmer_hits.extend(l)
        nucmer_hits_by_qry = self._hits_hashed_by_query(all_nucmer_hits)

        for ref_name, list_of_hits in nucmer_hits.items():
            if writing_log_file:
                print(log_outprefix, ref_name, 'Checking ' + str(len(list_of_hits)) + ' nucmer hits', sep='\t', file=log_fh)

            longest_start_hit = self._get_longest_hit_at_ref_start(list_of_hits)
            longest_end_hit = self._get_longest_hit_at_ref_end(list_of_hits)
            if longest_start_hit == longest_end_hit:
                second_longest_start_hit = self._get_longest_hit_at_ref_start(list_of_hits, hits_to_exclude={longest_start_hit})
                second_longest_end_hit = self._get_longest_hit_at_ref_end(list_of_hits, hits_to_exclude={longest_end_hit})
                if second_longest_start_hit is not None:
                    longest_start_hit = self._get_hit_nearest_ref_start([longest_start_hit, second_longest_start_hit])
                if second_longest_end_hit is not None:
                    longest_end_hit = self._get_hit_nearest_ref_end([longest_end_hit, second_longest_end_hit])

            if (
              longest_start_hit is not None
              and longest_end_hit is not None
              and longest_start_hit != longest_end_hit
              and self._hits_have_same_query(longest_start_hit, longest_end_hit)
            ):
                if writing_log_file:
                    print(log_outprefix, ref_name, 'potential pair of nucmer hits for circularization:', sep='\t', file=log_fh)
                    print(log_outprefix, ref_name, '', longest_start_hit, sep='\t', file=log_fh)
                    print(log_outprefix, ref_name, '', longest_end_hit, sep='\t', file=log_fh)

                shortest_hit_length = self._min_qry_hit_length([longest_start_hit, longest_end_hit])
                has_longer_hit = self._has_qry_hit_longer_than(
                    nucmer_hits_by_qry[longest_start_hit.qry_name],
                    shortest_hit_length,
                    hits_to_exclude={longest_start_hit, longest_end_hit}
                )

                if writing_log_file and has_longer_hit:
                    print(log_outprefix, ref_name, 'cannot use this pair because longer match was found', sep='\t', file=log_fh)

                can_circularise = self._can_circularise(longest_start_hit, longest_end_hit)

                if writing_log_file and not can_circularise:
                    print(log_outprefix, ref_name, 'cannot use this pair because positions/orientations of matches no good', sep='\t', file=log_fh)

                if (not has_longer_hit) and can_circularise:
                    print(log_outprefix, ref_name, 'can use this pair of hits', sep='\t', file=log_fh)
                    maybe_circular[ref_name] = (longest_start_hit, longest_end_hit)

        return maybe_circular
1342376
def _get_hit_nearest_ref_end(self, hits):
        ''''''
        nearest_to_end = hits[0]
        for hit in hits[1:]:
            if hit.ref_coords().end > nearest_to_end.ref_coords().end:
                nearest_to_end = hit
        return nearest_to_end
140899
def object_marking_circular_refs(instance):
    
    if instance['type'] != 'marking-definition':
        return

    if 'object_marking_refs' in instance:
        for ref in instance['object_marking_refs']:
            if ref == instance['id']:
                yield JSONError("`object_marking_refs` cannot contain any "
                                "references to this marking definition object"
                                " (no circular references).", instance['id'])
1363681
def reffs(self) -> BaseReferenceSet:
        
        if not self._cts:
            self._cts = BaseReferenceSet(
                [reff for reffs in [self.getReffs(level=i) for i in range(1, len(self.citation) + 1)] for reff in reffs]
            )
        return self._cts
1372459
def ref_coords(self):
        ''''''
        return pyfastaq.intervals.Interval(min(self.ref_start, self.ref_end), max(self.ref_start, self.ref_end))
783262
private Range<RangeTimeUUID> toRange(@Nullable UUID start, @Nullable UUID end, boolean reversed) {
        // If the range is reversed then start and end will also be reversed and must therefore be swapped.
        if (reversed) {
            UUID tmp = start;
            start = end;
            end = tmp;
        }

        if (start == null) {
            if (end == null) {
                return Range.all();
            } else {
                return Range.atMost(new RangeTimeUUID(end));
            }
        } else if (end == null) {
            return Range.atLeast(new RangeTimeUUID(start));
        }
        return Range.closed(new RangeTimeUUID(start), new RangeTimeUUID(end));
    }
932879
def ref(x, y, rw, rh) #:nodoc:
      translate(x, y) if x != 0 || y != 0
      @width = rw if rw
      @height = rh if rh
    end
1213050
def _init_goterm_ref(self, rec_curr, name, lnum):
        """"""
        if rec_curr is None:
            return GOTerm()
        msg = "PREVIOUS {REC} WAS NOT TERMINATED AS EXPECTED".format(REC=name)
        self._die(msg, lnum)
96463
def p_referenceInitializer(p):
    
    if p[1][0] == '$':
        try:
            p[0] = p.parser.aliases[p[1]]
        except KeyError:
            ce = CIMError(
                CIM_ERR_FAILED,
                _format("Unknown alias: {0!A}", p[1]))
            ce.file_line = (p.parser.file, p.lexer.lineno)
            raise ce
    else:
        p[0] = p[1]
1222516
def _nucmer_hits_to_percent_identity(nucmer_hits):
        ''''''
        percent_identities = {}
        max_lengths = {}

        for contig in nucmer_hits:
            max_length = -1
            percent_identity = 0
            for hit in nucmer_hits[contig]:
                if hit.hit_length_qry > max_length:
                    max_length = hit.hit_length_qry
                    percent_identity = hit.percent_identity
            percent_identities[contig] = percent_identity

        return percent_identities
1254130
def _get_identical_contigs(self, hits_dict):
        ''''''
        equivalent_contigs = []

        for qry_name, containing in hits_dict.items():
            equivalent = set()
            for containing_name in containing:
                if containing_name in hits_dict and qry_name in hits_dict[containing_name]:
                    equivalent.add(containing_name)
                    equivalent.add(qry_name)

            if len(equivalent):
                equivalent_contigs.append(equivalent)
                equivalent_contigs = self._collapse_list_of_sets(equivalent_contigs)

        return equivalent_contigs
4984
def _can_circularise(self, start_hit, end_hit):
        ''''''
        if not(self._is_at_ref_start(start_hit) or self._is_at_ref_end(end_hit)):
            return False

        if self._is_at_qry_end(start_hit) \
          and self._is_at_qry_start(end_hit) \
          and start_hit.on_same_strand() \
          and end_hit.on_same_strand():
            return True

        if self._is_at_qry_start(start_hit) \
          and self._is_at_qry_end(end_hit) \
          and (not start_hit.on_same_strand()) \
          and (not end_hit.on_same_strand()):
            return True

        return False
815353
private int getSkipCorrectedReference(List<Integer> tokenPositions, int refNumber) {
    int correctedRef = 0;
    int i = 0;
    for (int tokenPosition : tokenPositions) {
      if (i++ >= refNumber) {
        break;
      }
      correctedRef += tokenPosition;
    }
    return correctedRef - 1;
  }
645785
def main(args):
    
    p = OptionParser(main.__doc__)
    p.add_option("--refids", help="Use subset of contigs in the ref")
    p.add_option("--refcov", default=.01, type="float",
                 help="Minimum reference coverage [default: %default]")
    p.add_option("--all", default=False, action="store_true",
                 help="Plot one pdf file per ref in refidsfile [default: %default]")
    p.add_option("--color", default="similarity",
                 choices=("similarity", "direction", "none"),
                 help="Color the dots based on")
    p.add_option("--nolayout", default=False, action="store_true",
                 help="Do not rearrange contigs")
    p.set_align(pctid=0, hitlen=0)
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    deltafile, = args
    reffasta, queryfasta = open(deltafile).readline().split()
    color = opts.color
    layout = not opts.nolayout
    prefix = op.basename(deltafile).split(".")[0]
    qsizes = Sizes(queryfasta).mapping
    rsizes = Sizes(reffasta).mapping

    refs = SetFile(opts.refids) if opts.refids else set(rsizes.keys())
    refcov = opts.refcov
    pctid = opts.pctid
    hitlen = opts.hitlen
    deltafile = filter([deltafile, "--pctid={0}".format(pctid),
                        "--hitlen={0}".format(hitlen)])

    if opts.all:
        for r in refs:
            pdffile = plot_some_queries([r], qsizes, rsizes, deltafile, refcov,
                                        prefix=prefix, color=color,
                                        layout=layout)
            if pdffile:
                sh("mv {0} {1}.pdf".format(pdffile, r))
    else:
        plot_some_queries(refs, qsizes, rsizes,
                          deltafile, refcov,
                          prefix=prefix, color=color, layout=layout)
673922
def _get_nblock_regions(in_file, min_n_size, ref_regions):
    
    out_lines = []
    called_contigs = set([])
    with utils.open_gzipsafe(in_file) as in_handle:
        for line in in_handle:
            contig, start, end, ctype = line.rstrip().split()
            called_contigs.add(contig)
            if (ctype in ["REF_N", "NO_COVERAGE", "EXCESSIVE_COVERAGE", "LOW_COVERAGE"] and
                  int(end) - int(start) > min_n_size):
                out_lines.append("%s\t%s\t%s\n" % (contig, start, end))
    for refr in ref_regions:
        if refr.chrom not in called_contigs:
            out_lines.append("%s\t%s\t%s\n" % (refr.chrom, 0, refr.stop))
    return pybedtools.BedTool("\n".join(out_lines), from_string=True)
883159
def _get_longest_hit_at_qry_start(self, nucmer_hits):
        ''''''
        hits_at_start = [hit for hit in nucmer_hits if self._is_at_qry_start(hit)]
        return self._get_longest_hit_by_ref_length(hits_at_start)