Returns the genetic distance between this genome and the other. This distance value
        is used to compute genome compatibility for speciation.
341931
def distance(self, other, config):
        

        # Compute node gene distance component.
        node_distance = 0.0
        if self.nodes or other.nodes:
            disjoint_nodes = 0
            for k2 in iterkeys(other.nodes):
                if k2 not in self.nodes:
                    disjoint_nodes += 1

            for k1, n1 in iteritems(self.nodes):
                n2 = other.nodes.get(k1)
                if n2 is None:
                    disjoint_nodes += 1
                else:
                    # Homologous genes compute their own distance value.
                    node_distance += n1.distance(n2, config)

            max_nodes = max(len(self.nodes), len(other.nodes))
            node_distance = (node_distance + config.compatibility_disjoint_coefficient * disjoint_nodes) / max_nodes

        # Compute connection gene differences.
        connection_distance = 0.0
        if self.connections or other.connections:
            disjoint_connections = 0
            for k2 in iterkeys(other.connections):
                if k2 not in self.connections:
                    disjoint_connections += 1

            for k1, c1 in iteritems(self.connections):
                c2 = other.connections.get(k1)
                if c2 is None:
                    disjoint_connections += 1
                else:
                    # Homologous genes compute their own distance value.
                    connection_distance += c1.distance(c2, config)

            max_conn = max(len(self.connections), len(other.connections))
            connection_distance = (connection_distance + config.compatibility_disjoint_coefficient * disjoint_connections) / max_conn

        distance = node_distance + connection_distance

        return distance
1059114
def compatible(self, a, b):
        """"""
        return len(set([a] + self.descendants(a))
                   .intersection([b] + self.descendants(b))) > 0
894735
static Codec<Tuple, DoubleGene> codec(
		final IntRange v1Domain,
		final LongRange v2Domain,
		final DoubleRange v3Domain
	) {
		return Codec.of(
			Genotype.of(
				DoubleChromosome.of(DoubleRange.of(v1Domain.getMin(), v1Domain.getMax())),
				DoubleChromosome.of(DoubleRange.of(v2Domain.getMin(), v2Domain.getMax())),
				DoubleChromosome.of(v3Domain)
			),
			gt -> new Tuple(
				gt.getChromosome(0).getGene().intValue(),
				gt.getChromosome(1).getGene().longValue(),
				gt.getChromosome(2).getGene().doubleValue()
			)
		);
	}
1245469
def is_snp(self):
        ''''''
        nucleotides = {'A', 'C', 'G', 'T'}
        return len(self.REF) == 1 and self.REF in nucleotides and set(self.ALT).issubset(nucleotides)
409727
def left_overlaps(self, other, min_overlap_size=1):
        

        if self.alt != other.alt:
            # allele must match!
            return False

        if len(other.prefix) > len(self.prefix):
            # only consider strings that overlap like:
            #   self: ppppAssss
            #   other:   ppAsssssss
            # which excludes cases where the other sequence has a longer
            # prefix
            return False
        elif len(other.suffix) < len(self.suffix):
            # similarly, we throw away cases where the other sequence is shorter
            # after the alt nucleotides than this sequence
            return False

        # is the other sequence a prefix of this sequence?
        # Example:
        # p1 a1 s1 = XXXXXXXX Y ZZZZZZ
        # p2 a2 s2 =       XX Y ZZZZZZZZZ
        # ...
        # then we can combine them into a longer sequence
        sequence_overlaps = (
            self.prefix.endswith(other.prefix) and
            other.suffix.startswith(self.suffix)
        )
        prefix_overlap_size = min(len(self.prefix), len(other.prefix))
        suffix_overlap_size = min(len(other.suffix), len(self.suffix))
        overlap_size = (
            prefix_overlap_size + suffix_overlap_size + len(self.alt))

        return sequence_overlaps and overlap_size >= min_overlap_size
202160
def shift_or_mirror_into_invertible_domain(self, solution_genotype,
                                               copy=False):
        
        assert solution_genotype is not None
        if copy:
            y = [val for val in solution_genotype]
        else:
            y = solution_genotype
        if isinstance(y, np.ndarray) and not isinstance(y[0], float):
            y = array(y, dtype=float)
        for i in rglen(y):
            lb = self._lb[self._index(i)]
            ub = self._ub[self._index(i)]
            al = self._al[self._index(i)]
            au = self._au[self._index(i)]
            # x is far from the boundary, compared to ub - lb
            if y[i] < lb - 2 * al - (ub - lb) / 2.0 or y[i] > ub + 2 * au + (ub - lb) / 2.0:
                r = 2 * (ub - lb + al + au)  # period
                s = lb - 2 * al - (ub - lb) / 2.0  # start
                y[i] -= r * ((y[i] - s) // r)  # shift
            if y[i] > ub + au:
                y[i] -= 2 * (y[i] - ub - au)
            if y[i] < lb - al:
                y[i] += 2 * (lb - al - y[i])
        return y
480356
def mutateSequence(seq, distance):
    
    subProb=distance
    inProb=0.05*distance
    deProb=0.05*distance
    contProb=0.9
    l = []
    bases = [ 'A', 'C', 'T', 'G' ]
    i=0
    while i < len(seq):
        if random.random() < subProb:
            l.append(random.choice(bases))
        else:
            l.append(seq[i])
        if random.random() < inProb:
            l += getRandomSequence(_expLength(0, contProb))[1]
        if random.random() < deProb:
            i += int(_expLength(0, contProb))
        i += 1
    return "".join(l)
722443
def comparison(self):
        
        node = self.expr()

        while self.token.nature in (
            Nature.EQ,
            Nature.NE,
            Nature.LE,
            Nature.GE,
            Nature.LT,
            Nature.GT,
        ):
            token = self.token
            if token.nature == Nature.EQ:
                self._process(Nature.EQ)
            elif token.nature == Nature.NE:
                self._process(Nature.NE)
            elif token.nature == Nature.LE:
                self._process(Nature.LE)
            elif token.nature == Nature.GE:
                self._process(Nature.GE)
            elif token.nature == Nature.LT:
                self._process(Nature.LT)
            elif token.nature == Nature.GT:
                self._process(Nature.GT)
            else:
                self.error()

            node = BinaryOperation(left=node, op=token, right=self.expr())

        return node
942041
def similarity(self, other):
        """"""
        logging.debug("comparing %r and %r...", self.stripped, other.stripped)
        ratio = SequenceMatcher(a=self.stripped, b=other.stripped).ratio()
        similarity = self.Similarity(ratio)
        return similarity
582911
private static void onePointCrossover(Program gp1, Program gp2, LGP manager, RandEngine randEngine) {
      // Xianshun says:
      // this implementation is derived from Algorithm 5.1 in Section 5.7.1 of Linear
      // Genetic Programming

      // length(gp1) <= length(gp2)
      if (gp1.length() > gp2.length())
      {
         gp1 = gp2;
         gp2 = gp1;
      }

      int max_distance_of_crossover_points = (gp1.length() - 1) < manager.getMaxDistanceOfCrossoverPoints() ? manager.getMaxDistanceOfCrossoverPoints() : (gp1.length() - 1);

      int i1 = randEngine.nextInt(gp1.length());
      int i2 = randEngine.nextInt(gp2.length());

      int crossover_point_distance = (i1 > i2) ? (i1 - i2) : (i2 - i1);

      int ls1 = gp1.length() - i1;
      int ls2 = gp2.length() - i2;

      // 1. assure abs(i1-i2) <= max_distance_of_crossover_points
      // 2. assure l(s1) <= l(s2)
      boolean not_feasible=true;
      int count = 0;
      while (not_feasible && count < 10) {
         not_feasible = false;
         // ensure that the maximum distance between two crossover points is not exceeded
         if (crossover_point_distance > max_distance_of_crossover_points) {
            not_feasible = true;
            i1 = randEngine.nextInt(gp1.length());
            i2 = randEngine.nextInt(gp2.length());
            crossover_point_distance = (i1 > i2) ? (i1 - i2) : (i2 - i1);
         }
         else {
            ls1 = gp1.length() - i1;
            ls2 = gp2.length() - i2;
            // assure than l(s1) <= l(s2)
            if (ls1 > ls2) {
               not_feasible = true;
               i1 = randEngine.nextInt(gp1.length());
               i2 = randEngine.nextInt(gp2.length());
               crossover_point_distance = (i1 > i2) ? (i1 - i2) : (i2 - i1);
            }
            else {
               // assure the length of the program after crossover do not exceed the maximum program length or below minimum program length
               if ((gp2.length() - (ls2 - ls1)) < manager.getMinProgramLength() || (gp1.length() + (ls2 - ls1)) > manager.getMaxProgramLength()) {
                  not_feasible = true;
                  // when the length constraint is not satisfied, make the segments to be exchanged the same length
                  if (gp1.length() >= gp2.length()) {
                     i1 = i2;
                  }
                  else {
                     i2 = i1;
                  }
                  crossover_point_distance = 0;
               }
               else {
                  not_feasible = false;
               }
            }
         }
         count++;
      }

      List<Instruction> instructions1 = gp1.getInstructions();
      List<Instruction> instructions2 = gp2.getInstructions();

      List<Instruction> instructions1_1 = new ArrayList<>();
      List<Instruction> instructions1_2 = new ArrayList<>();

      List<Instruction> instructions2_1 = new ArrayList<>();
      List<Instruction> instructions2_2 = new ArrayList<>();

      for (int i = 0; i < i1; ++i)
      {
         instructions1_1.add(instructions1.get(i));
      }
      for (int i = i1; i < instructions1.size(); ++i)
      {
         instructions1_2.add(instructions1.get(i));
      }

      for (int i = 0; i < i2; ++i)
      {
         instructions2_1.add(instructions2.get(i));
      }
      for (int i = i2; i < instructions2.size(); ++i)
      {
         instructions2_2.add(instructions2.get(i));
      }

      instructions1.clear();
      instructions2.clear();

      for (int i = 0; i < i1; ++i)
      {
         instructions1.add(instructions1_1.get(i));
      }
      for (int i = 0; i < instructions2_2.size(); ++i)
      {
         instructions1.add(InstructionHelper.reassign2Program(instructions2_2.get(i), gp1));
      }

      for (int i = 0; i < i2; ++i)
      {
         instructions2.add(instructions2_1.get(i));
      }

      for (int i = 0; i < instructions1_2.size(); ++i)
      {
         instructions2.add(InstructionHelper.reassign2Program(instructions1_2.get(i), gp2));
      }

      gp1.invalidateCost();
      gp2.invalidateCost();
   }
311309
def range(self):
    
    return GenomicRange(self._rngs[0].chr,self._rngs[0].start,self._rngs[-1].end)
380256
def distance_to(self, other):
        
        if self.overlaps(other):
            return 0
        try:
            if self.begin < other.begin:
                return other.begin - self.end
            else:
                return self.begin - other.end
        except:
            if self.end <= other:
                return other - self.end
            else:
                return self.begin - other
1178417
def is_homozygous(self):
        ''''''
        if self.FORMAT is None:
            return False
        else:
            genotypes = set(self.FORMAT.get('GT', '0/1').split('/'))
            return '.' not in genotypes and len(genotypes) == 1
321294
def similarity(self, other):
        """"""
        ratio = SequenceMatcher(a=self.value, b=other.value).ratio()
        similarity = self.Similarity(ratio)
        return similarity
629258
def copy(self):
        '''

        '''
        return type(self)(self.name, self.start, self.stop, self.feature_type,
                          gene=self.gene, locus_tag=self.locus_tag,
                          qualifiers=self.qualifiers, strand=self.strand)
301176
def compare_genomes(fastas, id2desc, algorithm):
    
    hits = {}
    for pair in itertools.permutations(fastas, 2):
        if pair[0] not in hits:
            hits[pair[0]] = {}
        hits[pair[0]][pair[1]] = {}
    for pair in itertools.combinations(fastas, 2):
        A, B = pair
        blastF = open(search(A, B, method = algorithm, alignment = 'local'))
        blastR = open(search(B, A, method = algorithm, alignment = 'local'))
        for compare in [A, B, blastF], [B, A, blastR]:
            query, ref, blast = compare
            for hit in best_blast(blast, 1):
                a, b, pident, qstart, qend, e, bit = \
                        hit[0].split()[0], hit[1].split()[0], float(hit[2]), float(hit[6]), float(hit[7]), float(hit[-2]), float(hit[-1])
                alignment_length = abs(qstart - qend + 1)
                norm_bit = normalize_bit(a, b, bit, id2desc)
                length_fraction = float((alignment_length) / id2desc[a][2])
                hits[query][ref][a] = ['fbh', a, b, pident, length_fraction, e, bit, norm_bit]
    return hits
762248
def genome_lengths(fastas, info):
    
    if info is False:
        info = {}
    for genome in fastas:
        name = genome.rsplit('.', 1)[0].rsplit('/', 1)[-1].rsplit('.contigs')[0]
        if name in info:
            continue
        length = 0
        fragments = 0
        for seq in parse_fasta(genome):
            length += len(seq[1])
            fragments += 1
        info[name] = {'genome size (bp)':length, '# contigs':fragments}
    return info