Exemplo n.º 1
0
def getElementaryIntervals(intervals, returnList=0):
    arr = getPoints(intervals)
    # sorting the array with all the end points
    arr = (sorted(arr, key=lambda x: x.getX()))
    arr_ = [each.getX() for each in arr]
    # array to store all the elementary intervals
    elementaryIntervals = []
    # adding all the elementary intervals
    elementaryIntervals.append(Interval(MIN, arr_[0] - epsilon))
    for i in range(0, len(arr_) - 1):
        # skipping over duplicate values
        if arr_[i + 1] == arr_[i]:
            continue
        elementaryIntervals.append(Interval(arr_[i], arr_[i]))
        elementaryIntervals.append(
            Interval(arr_[i] + epsilon, arr_[i + 1] - epsilon))
    elementaryIntervals.append(Interval(arr_[-1], arr_[-1]))
    elementaryIntervals.append(Interval(arr_[-1] + epsilon, MAX))
    # for when the return value needs to be a list
    if returnList == 1:
        arr_ = []
        for each in elementaryIntervals:
            arr_.append([each.getLeft(), each.getRight()])
        return arr_
    # returning the list of elementary intervals
    return elementaryIntervals
Exemplo n.º 2
0
    def empirical_corr_function(self, stateA, stateB, times, symmetric=True):

        n_dim = self.n_variables

        stateA = Interval(stateA, n_dim) if not self.discrete else stateA
        stateB = Interval(stateB, n_dim) if not self.discrete else stateB

        corr_values = []

        for delay in times:
            assert (type(delay) == int)
            assert (delay >= 1)
            sum_ = 0
            counts = 0

            for traj in self.trajectories:
                for i in range(len(traj) - delay):
                    sum_ += (traj[i] in stateA) * (traj[i + delay] in stateB)
                    counts += 1

                    if symmetric:
                        sum_ += (traj[i] in stateB) * \
                                (traj[i + delay] in stateA)
                        counts += 1
            corr_values.append(sum_ / counts)

        return corr_values
    def parse(lines):
        clazz = Clazz()

        intervals = []
        interval: Interval()

        for index in range(0, len(lines)):
            line = lines[index]
            if (line == '   */\n'):
                interval = Interval()
                interval.start = index + 1
                continue
            if (line.endswith(');\n')):
                interval.end = index + 1
                intervals.append(interval)

        del line

        for interval in intervals:
            content = lines[interval.start:interval.end]

            function = Function.parse(content)

            if clazz.functions is None:
                clazz.functions = []

            clazz.functions.append(function)
            del content

        return clazz
Exemplo n.º 4
0
    def from_ensemble(cls,
                      ensemble,
                      stateA=None,
                      stateB=None,
                      map_function=None,
                      discrete=False,
                      dtype='float32'):

        list_of_pathsAB = []

        try:
            n_variables = len(ensemble[0][0])
        except:
            n_variables = 1

        if (stateA is None) or (stateB is None):
            raise Exception(
                'The initial state (stateA) and final state (stateB) \
                have to be specified')

        for traj in ensemble.trajectories:
            previous_color = "Unknown"
            pathAB = []
            for _snapshot in traj:

                if map_function is not None:
                    snapshot = map_function(_snapshot)
                else:
                    snapshot = _snapshot

                # color determination
                if not discrete:
                    if snapshot in Interval(stateA, n_variables):
                        color = "A"
                    elif snapshot in Interval(stateB, n_variables):
                        color = "B"
                    else:
                        color = previous_color
                else:
                    if snapshot in stateA:
                        color = "A"
                    elif snapshot in stateB:
                        color = "B"
                    else:
                        color = previous_color

                if (color == "A"):
                    pathAB.append(snapshot)
                elif (color == "B") and (previous_color == "A"):
                    pathAB.append(snapshot)
                    list_of_pathsAB.append(np.array(pathAB, dtype=dtype))
                    pathAB = []

                previous_color = color

        return cls(list_of_pathsAB,
                   stateA=stateA,
                   stateB=stateB,
                   dtype=dtype,
                   discrete=discrete)
 def test_Interval(self):
     self.assertSequenceEqual(
         list(map(lambda x: str(Interval(x)), self.Intervals_True)),
         self.Answer_Test_Interval)
     for stringInt in self.Intervals_False:
         with self.assertRaises(InputError):
             Interval(stringInt)
Exemplo n.º 6
0
def getElementaryIntervals(intervals, returnList=0):
    # array to store all the end points of the interval
    arr = []
    # adding all the end points of the intervals
    for each in intervals:
        arr.append((each[0]))
        arr.append((each[1]))
    # sorting the array with all the end points
    arr = (sorted(arr))
    # array to store all the elementary intervals
    elementaryIntervals = []
    # adding all the elementary intervals
    elementaryIntervals.append(Interval(MIN, arr[0] - epsilon))
    for i in range(0, len(arr) - 1):
        # skipping over duplicate values
        if arr[i + 1] == arr[i]:
            continue
        elementaryIntervals.append(Interval(arr[i], arr[i]))
        elementaryIntervals.append(
            Interval(arr[i] + epsilon, arr[i + 1] - epsilon))
    elementaryIntervals.append(Interval(arr[-1], arr[-1]))
    elementaryIntervals.append(Interval(arr[-1] + epsilon, MAX))
    # for when the return value needs to be a list
    if returnList == 1:
        arr = []
        for each in elementaryIntervals:
            arr.append([each.getLeft(), each.getRight()])
        return arr
    # returning the list of elementary intervals
    return elementaryIntervals
Exemplo n.º 7
0
 def if_unsafe(self):
     if self.state[0] in Interval(
             self.x0_low, self.x0_high) and self.state[1] in Interval(
                 self.x1_low, self.x1_high):
         return 0
     else:
         return 1
Exemplo n.º 8
0
def coalesce(xs, vd_model='vd_sum'):
    """
    This function implements the coalesce operator, it is based on discretize.
    @param xs: the list of Intervals
    @type xs:
    @param vd_model:
    @type vd_model:
    @return: list of Intervals
    @rtype:[Interval]
    """
    res1 = discretize(xs, vd_model)
    res = []
    start_idx = 0
    sum = 0
    total_leng = 0
    for idx in range(start_idx, len(res1) - 1):
        if res1[idx].adjacent(res1[idx + 1]):
            sum += res1[idx].value * len(res1[idx])
            total_leng += len(res1[idx])
        else:
            sum += res1[idx].value * len(res1[idx])
            total_leng += len(res1[idx])
            res.append(
                Interval(res1[start_idx].start, res1[idx].end,
                         sum / total_leng))
            start_idx = idx + 1
            sum = 0
            total_leng = 0
    else:
        sum += res1[-1].value * len(res1[-1])
        total_leng += len(res1[-1])
        res.append(
            Interval(res1[start_idx].start, res1[-1].end, sum / total_leng))
    return res
Exemplo n.º 9
0
def read_file(filename, fields_num=4):
    """
    It assumes the first four columns are chr, start, end, value, we can also specify the fields number,
    in case we don't want the value field
    @param filename: The file to be read
    @type filename: str
    @return: a dictionary, it is sorted by the start of each interval
    @rtype: ['chr', [Interval]]
    """
    d = defaultdict(list)
    with open(filename) as f:
        for line in f:
            row = line.rstrip('\n').split('\t')
            if fields_num == 4:
                chrom, start, end, value = row[0:4]
                d[chrom].append(Interval(int(start), int(end), float(value)))
            elif fields_num == 3:
                chrom, start, end = row[0:3]
                d[chrom].append(Interval(int(start), int(end)))
            else:
                raise Exception('Can not parse your file\n')
    d = OrderedDict(sorted(d.items()))
    for l in d.values():
        l.sort(key=lambda x: x.start)
    return d
Exemplo n.º 10
0
def concave_hull_matrix(binary_matrix, concave_alpha):
    """
    Faster way to convert discrete binary matrix to concave hull binary matrix
    :param binary_matrix: numpy matrix
    :return:
    """

    # binary_matrix = np.uint8(binary_matrix)
    _, cnts, _, = cv2.findContours(np.uint8(binary_matrix), cv2.RETR_EXTERNAL,
                                   cv2.CHAIN_APPROX_SIMPLE)

    # new_binary_matrix = binary_matrix * 255
    # binary = cv2.threshold(new_binary_matrix.astype(np.uint8), 0, 255, cv2.THRESH_BINARY)[1]
    # opencv = OpenCV(binary)
    # cnts = opencv.find_contours(binary_matrix)
    np_cnts = np.zeros((1, 2), dtype=np.uint32)
    for cnt in cnts:
        temp_cnt = np.squeeze(np.asarray(cnt))
        np_cnts = np.row_stack((np_cnts, temp_cnt))

    np_cnts = np.delete(np_cnts, 0, axis=0)
    concave_hull, edge_points = alpha_shape(np_cnts, concave_alpha)

    concave_hull_x_min, concave_hull_y_min, concave_hull_x_max, concave_hull_y_max = concave_hull.bounds
    shape_interal = []
    polygon_list = []
    if concave_hull.geom_type == 'MultiPolygon':
        for polygon in concave_hull:
            x_min, y_min, x_max, y_max = polygon.bounds
            shape_interal.append((Interval(x_min,
                                           x_max), Interval(y_min, y_max)))
            # Can't fill the inner hole
            # mypolygon = polygon.buffer(eps, 1, join_style=JOIN_STYLE.mitre).buffer(-eps, 1, join_style=JOIN_STYLE.mitre)
            # polygon_list.append(mypolygon)

    else:
        shape_interal.append((Interval(concave_hull_x_min, concave_hull_x_max),
                              Interval(concave_hull_y_min,
                                       concave_hull_y_max)))
        # mypolygon = concave_hull.buffer(eps, 1, join_style=JOIN_STYLE.mitre).buffer(-eps, 1, join_style=JOIN_STYLE.mitre)
        # polygon_list.append(mypolygon)

    condition = np.zeros(binary_matrix.shape, dtype=np.bool)
    condition[int(concave_hull_y_min):int(concave_hull_y_max),
              int(concave_hull_x_min):int(concave_hull_x_max)] = True
    binmat_zero_indexs = np.argwhere(
        np.logical_and(binary_matrix == 0, condition))
    for each in binmat_zero_indexs:
        each = np.array([each[1], each[0]])
        point = Point(each)
        # for polygon in polygon_list:
        #     if polygon.covers(point):
        #         binary_matrix[int(each[1])][int(each[0])] = 1
        #         break
        if concave_hull.covers(point):
            binary_matrix[int(each[1])][int(each[0])] = 1

    return binary_matrix
Exemplo n.º 11
0
def parse_gene(db, ref_flag, prom):
    if ref_flag:  # for GenePred
        gname = ''
        gchr, gstrand = '', ''
        ginterval = []  # genomic regions
        gpromoter = []  # tss regions
        with open(db, 'r') as f:
            for line in f:
                gene_id, chrom, strand, start, end = line.split()[:5]
                if not chrom.startswith('chr'):
                    continue
                start = int(start) - 1
                end = int(end)
                if gname == '':  # first entry
                    gname = gene_id
                    gchr, gstrand = chrom, strand
                # not same gene
                elif gname != gene_id or chrom != gchr or strand != gstrand:
                    gpromoter = Interval(gpromoter)  # combine tss regions
                    for itl in Interval(ginterval).interval:
                        gstart, gend = itl
                        gene_info = '%s\t%s\t%d\t%d\t%s' % (
                            gname, gchr, gstart, gend, gstrand)
                        yield gene_info, gpromoter
                    # update gene info
                    gname = gene_id
                    gchr, gstrand = chrom, strand
                    ginterval = []
                    gpromoter = []
                # add genomic interval
                ginterval.append([start, end])
                # define gene promoter regions
                if strand == '+':
                    gpromoter.append([start - prom, start + prom, start])
                else:
                    gpromoter.append([end - prom, end + prom, end])
            else:  # last entry
                gpromoter = Interval(gpromoter)  # combine tss regions
                for itl in Interval(ginterval).interval:
                    gstart, gend = itl
                    gene_info = '%s\t%s\t%d\t%d\t%s' % (gname, gchr, gstart,
                                                        gend, gstrand)
                    yield gene_info, gpromoter
    else:  # for GTF
        for gene in db.features_of_type('gene'):
            if not gene.seqid.startswith('chr'):
                continue
            gene_info = '%s\t%s\t%d\t%d\t%s' % (gene['gene_name'][0],
                                                gene.seqid, gene.start - 1,
                                                gene.end, gene.strand)
            gpromoter = []  # tss regions
            for t in db.children(gene.id, featuretype='transcript'):
                if gene.strand == '+':
                    gpromoter.append([t.start - prom, t.start + prom, t.start])
                else:
                    gpromoter.append([t.end - prom, t.end + prom, t.end])
            gpromoter = Interval(gpromoter)  # combine tss regions
            yield gene_info, gpromoter
Exemplo n.º 12
0
def overlap(rect1, rect2):
    """Calculate the overlap between two rectangles"""
    xInterval = Interval(rect1[0][0], rect1[1][0]) & Interval(
        rect2[0][0], rect2[1][0])
    yInterval = Interval(rect1[0][1], rect1[1][1]) & Interval(
        rect2[0][1], rect2[1][1])
    area = (xInterval.upper_bound - xInterval.lower_bound) * (
        yInterval.upper_bound - yInterval.lower_bound)
    return area
Exemplo n.º 13
0
def code_list_cleanup(code_list):
    lat_interval = Interval(49.87, 61.02)
    lon_interval = Interval(-8.25, 1.83)
    newlist = []
    for latlng in code_list:
        if latlng != None and latlng[0] in lat_interval and latlng[
                1] in lon_interval:
            newlist.append(latlng)
    return newlist
    def test_merge_interval_if_overlapping_and_preceding_range_greater(self):
        input = [Interval("1"), Interval("2", "10"), Interval("5", "9")]
        res = merge_intervals(input)
        self.assertEqual(len(res), 2)
        self.assertEqual(res[0].start, 1)
        self.assertEqual(res[0].end, 1)

        self.assertEqual(res[1].start, 2)
        self.assertEqual(res[1].end, 10)
Exemplo n.º 15
0
 def is_unsafe(self):
     if self.state[0] in Interval(
             self.range_low, self.range_high) and self.state[1] in Interval(
                 self.range_low,
                 self.range_high) and self.state[2] in Interval(
                     self.range_low, self.range_high):
         return 0
     else:
         return 1
Exemplo n.º 16
0
 def add_record(self, rank, record):
     self.ranks += Interval(rank)
     if ((record.record_type != self.record_type)
             or (record.record_subtypes != self.record_subtypes)):
         raise ValueError(record)
     for field in self.fields:
         self.copy_structure(rank, getattr(self, field),
                             getattr(record, field))
     self.ranks += Interval(rank)
    def test_merge_interval_if_overlapping_unsorted(self):
        input = [Interval("1"), Interval("5", "12"), Interval("3", "9")]
        res = merge_intervals(input)
        self.assertEqual(len(res), 2)
        self.assertEqual(res[0].start, 1)
        self.assertEqual(res[0].end, 1)

        self.assertEqual(res[1].start, 3)
        self.assertEqual(res[1].end, 12)
Exemplo n.º 18
0
def slow(ips):
    from interval import Interval, IntervalSet
    r1 = IntervalSet([Interval(0, 4294967295)])
    r2 = IntervalSet([Interval(ip[0], ip[1]) for ip in ips])
    diff = r1 - r2
    total = 0
    for i in diff:
        start = i.lower_bound + 1
        total += i.upper_bound - start
    print('Part 2: %d' % total)
Exemplo n.º 19
0
def judgeAgeArea(bir):
    if bir in Interval("19981001", "20161201"):
        return "age18L"
    else:
        if bir in Interval("19561001", "19980930"):
            return "age60L"
        else:
            if bir in Interval("19000101", "19560930"):
                return "age60M"
            else:
                return "Error"
Exemplo n.º 20
0
 def high(self):
     if self.average in Interval(97.15, 100.00):
         return 18
     if self.average in Interval(88.58, 97.15):
         return 17
     if self.average in Interval(71.44, 88.58):
         return 16
     if self.average in Interval(42.87, 71.44):
         return 15
     if self.average in Interval(0, 42.87):
         return 14
Exemplo n.º 21
0
    def low(self):

        if self.average in Interval(97.15, 100.00):
            return 3
        if self.average in Interval(88.58, 97.15):
            return 4
        if self.average in Interval(71.44, 88.58):
            return 5
        if self.average in Interval(42.87, 71.44):
            return 6
        if self.average in Interval(0, 42.87):
            return 7
Exemplo n.º 22
0
def main():
    """quick dev tests."""

    from interval import Interval
    from relationSymbol import RelationSymbol
    from vocabulary import Vocabulary
    from attribute_interpretation import AttributeInterpretation
    from formula import Formula
    from assumption_base import AssumptionBase
    from attribute import Attribute
    from relation import Relation
    from attribute_structure import AttributeStructure
    from attribute_system import AttributeSystem
    from constant_assignment import ConstantAssignment
    from named_state import NamedState
    from context import Context
    from variable_assignment import VariableAssignment

    a = Attribute('hour', [Interval(0, 23)])
    a2 = Attribute('minute', [Interval(0, 59)])
    r_pm = Relation('R1(h1) <=> h1 > 11', ['hour'], 1)
    r_am = Relation('R2(h1) <=> h1 <= 11', ['hour'], 2)
    r_ahead = Relation('R3(h1,m1,h2,m2) <=> h1 > h2 or (h1 = h2 and m1 > m2)',
                       ['hour', 'minute', 'hour', 'minute'], 3)
    r_behind = Relation('R4(h1,m1,h2,m2) <=> h1 < h2 or (h1 = h2 and m1 < m2)',
                        ['hour', 'minute', 'hour', 'minute'], 4)
    attribute_structure = AttributeStructure(a, a2, r_ahead, r_behind, r_pm,
                                             r_am)

    pm_rs = RelationSymbol('PM', 1)
    am_rs = RelationSymbol('AM', 1)
    ahead_rs = RelationSymbol('Ahead', 4)
    behind_rs = RelationSymbol('Behind', 4)

    vocabulary = Vocabulary(['C1', 'C2'], [pm_rs, am_rs, ahead_rs, behind_rs],
                            ['V1', 'V2'])

    objs = ['s1', 's2', 's3']
    asys = AttributeSystem(attribute_structure, objs)

    const_mapping_2 = {'C1': 's1'}
    p2 = ConstantAssignment(vocabulary, asys, const_mapping_2)

    ascriptions_1 = {
        ("hour", "s1"): [13, 15, 17],
        ("minute", "s1"): [10],
        ("hour", "s2"): [1, 3, 5],
        ("minute", "s2"): [10],
        ("hour", "s3"): [1, 3, 5],
        ("minute", "s3"): [10]
    }

    named_state_4 = NamedState(asys, p2, ascriptions_1)
    def test_merge_interval_if_disjoint(self):
        input = [Interval("1"), Interval("2", "5"), Interval("6", "10")]
        res = merge_intervals(input)
        self.assertEqual(len(res), 3)
        self.assertEqual(res[0].start, 1)
        self.assertEqual(res[0].end, 1)

        self.assertEqual(res[1].start, 2)
        self.assertEqual(res[1].end, 5)

        self.assertEqual(res[2].start, 6)
        self.assertEqual(res[2].end, 10)
Exemplo n.º 24
0
def exclusivejoin(xss, yss):
    """
    To compute segments covered by the first track, but not by the second track.
    The basic idea is to use the result of intersectjoin, then do some processing
    @param xs: list of Intervals
    @type xs:
    @param ys: list of Intervals
    @type ys:
    @return: new list of Intervals
    @rtype:
    """
    res = []
    xs = deque(xss)
    ys = deque(yss)
    while xs and ys:
        if xs[0].precedes(ys[0]):
            res.append(xs[0])
            xs.popleft()
        elif xs[0].follows(ys[0]):
            ys.popleft()
        elif xs[0].start > ys[0].start:
            if xs[0].end == ys[0].end:
                xs.popleft()
                ys.popleft()
            elif xs[0].end > ys[0].end:
                xs[0] = Interval(ys[0].end + 1, xs[0].end, xs[0].value)
                ys.popleft()
            else:
                xs.popleft()
        elif xs[0].start == ys[0].start:
            if xs[0].end == ys[0].end:
                xs.popleft()
                ys.popleft()
            elif xs[0].end > ys[0].end:
                xs[0] = Interval(ys[0].end + 1, xs[0].end, xs[0].value)
                ys.popleft()
            else:
                xs.popleft()
        elif xs[0].start < ys[0].start:
            res.append(Interval(xs[0].start, ys[0].start - 1, xs[0].value))
            if xs[0].end == ys[0].end:
                xs.popleft()
                ys.popleft()
            elif xs[0].end > ys[0].end:
                xs[0] = Interval(ys[0].end + 1, xs[0].end, xs[0].value)
                ys.popleft()
            else:
                xs.popleft()
    else:
        if xs:
            res.extend(xs)
    return res
Exemplo n.º 25
0
def get_chord_data(notes):
    chord_data = []
    for note in notes:
        root = Note(name=(note.get_name()))
        quality = None
        extensions = []
        inversion = None
        intervals = {}
        fifth = None
        first_interval = None
        for other in notes:
            if root.equals(other):
                continue
            if root < other:
                interval = Interval(root, other)
            else:
                other_octave = other.get_octave()
                root_name = root.get_name()[:-1]
                if Note(root_name + str(other_octave)) > other:
                    root = Note(name=root_name + str(other_octave-1))
                else:
                    root = Note(name=root_name + str(other_octave))
                interval = Interval(root, other)
            first_interval = interval if not first_interval
            intervals[interval.get_name()] = interval
        if "major 3rd" in intervals.keys():
            quality = "major"
        elif "minor 3rd" in intervals.keys():
            quality = "minor"
        for name, val in intervals.items()
            for ext in exts:
                if ext in name:
                    extensions.append(val)
            if "5th" in name:
                fifth = val.get_quality()
            if quality == "major" append "augmented 5th" in val.get_names():
                fifth = "augmented" if not fifth
        if not root.equals(notes[0]):
            if "3rd" in first_interval.get_name():
                inversion = "1st"
            elif "5th" in first_interval.get_name():
                inversion = "2nd"
            else:
                inversion = "3rd"
        data = {
            "root": root,
            "quality" : quality,
            "inversion" : inversion,
            "extenstions" : extensions,
            "fifth" : fifth,
        }
        chord_data.append(data)
Exemplo n.º 26
0
 def _add_interval_for_binary_boolean(self, var, var_value, rhs_value, op):
     if op in Z3_LE_OPS:
         self.add_interval(var, Interval(MINF, rhs_value))
     elif op in Z3_LT_OPS:
         self.add_interval(var, Interval(MINF, rhs_value - 1))
     elif op in Z3_GE_OPS:
         self.add_interval(var, Interval(rhs_value, INF))
     elif op in Z3_GT_OPS:
         self.add_interval(var, Interval(rhs_value + 1, INF))
     elif op in Z3_EQ_OPS:
         self.add_interval(var, Interval(rhs_value, rhs_value))
     else:
         assert False
Exemplo n.º 27
0
def individual_Bernstein_polynomial(state):
	x0 = state[0]
	x1 = state[1]
	if x0 in Interval(-2, -1): #0.08
		y = 0.0435725822050459*(0.5 - 0.25*x1)*(-1.0*x0 - 1.0)**5*(0.5*x1 + 1)**4 + 0.00525112569711154*(0.5 - 0.25*x1)*(-1.0*x0 - 1.0)**4*(1.0*x0 + 2.0)*(0.5*x1 + 1)**4 + 0.970120610633042*(0.5 - 0.25*x1)*(-1.0*x0 - 1.0)**3*(0.5*x0 + 1)**2*(0.5*x1 + 1)**4 + 3.77518875708639*(0.5 - 0.25*x1)*(-1.0*x0 - 1.0)**2*(0.5*x0 + 1)**3*(0.5*x1 + 1)**4 + 5.40752779754075*(0.5 - 0.25*x1)*(-1.0*x0 - 1.0)*(0.5*x0 + 1)**4*(0.5*x1 + 1)**4 + 2.71396863613472*(0.5 - 0.25*x1)*(0.5*x0 + 1)**5*(0.5*x1 + 1)**4 + 0.031143533099941*(1 - 0.5*x1)**5*(-1.0*x0 - 1.0)**5 + 0.155168051068054*(1 - 0.5*x1)**5*(-1.0*x0 - 1.0)**4*(1.0*x0 + 2.0) + 1.23243979207846*(1 - 0.5*x1)**5*(-1.0*x0 - 1.0)**3*(0.5*x0 + 1)**2 + 2.42900977400397*(1 - 0.5*x1)**5*(-1.0*x0 - 1.0)**2*(0.5*x0 + 1)**3 + 2.35755584564433*(1 - 0.5*x1)**5*(-1.0*x0 - 1.0)*(0.5*x0 + 1)**4 + 0.898694593651958*(1 - 0.5*x1)**5*(0.5*x0 + 1)**5 + 0.309816961904818*(1 - 0.5*x1)**4*(-1.0*x0 - 1.0)**5*(0.25*x1 + 0.5) + 1.53530630733455*(1 - 0.5*x1)**4*(-1.0*x0 - 1.0)**4*(1.0*x0 + 2.0)*(0.25*x1 + 0.5) + 12.0610162133811*(1 - 0.5*x1)**4*(-1.0*x0 - 1.0)**3*(0.5*x0 + 1)**2*(0.25*x1 + 0.5) + 23.2443672600848*(1 - 0.5*x1)**4*(-1.0*x0 - 1.0)**2*(0.5*x0 + 1)**3*(0.25*x1 + 0.5) + 21.5509424419587*(1 - 0.5*x1)**4*(-1.0*x0 - 1.0)*(0.5*x0 + 1)**4*(0.25*x1 + 0.5) + 7.37839877958033*(1 - 0.5*x1)**4*(0.5*x0 + 1)**5*(0.25*x1 + 0.5) + 0.305612616960474*(1 - 0.5*x1)**3*(-1.0*x0 - 1.0)**5*(0.5*x1 + 1)**2 + 1.49563517639774*(1 - 0.5*x1)**3*(-1.0*x0 - 1.0)**4*(1.0*x0 + 2.0)*(0.5*x1 + 1)**2 + 11.4456212467953*(1 - 0.5*x1)**3*(-1.0*x0 - 1.0)**3*(0.5*x0 + 1)**2*(0.5*x1 + 1)**2 + 20.9274560343607*(1 - 0.5*x1)**3*(-1.0*x0 - 1.0)**2*(0.5*x0 + 1)**3*(0.5*x1 + 1)**2 + 17.4243589203542*(1 - 0.5*x1)**3*(-1.0*x0 - 1.0)*(0.5*x0 + 1)**4*(0.5*x1 + 1)**2 + 5.84262876682205*(1 - 0.5*x1)**3*(0.5*x0 + 1)**5*(0.5*x1 + 1)**2 + 0.280561913946506*(1 - 0.5*x1)**2*(-1.0*x0 - 1.0)**5*(0.5*x1 + 1)**3 + 1.25510169385051*(1 - 0.5*x1)**2*(-1.0*x0 - 1.0)**4*(1.0*x0 + 2.0)*(0.5*x1 + 1)**3 + 7.9746568158603*(1 - 0.5*x1)**2*(-1.0*x0 - 1.0)**3*(0.5*x0 + 1)**2*(0.5*x1 + 1)**3 + 13.5049836146893*(1 - 0.5*x1)**2*(-1.0*x0 - 1.0)**2*(0.5*x0 + 1)**3*(0.5*x1 + 1)**3 + 13.1763479301358*(1 - 0.5*x1)**2*(-1.0*x0 - 1.0)*(0.5*x0 + 1)**4*(0.5*x1 + 1)**3 + 5.13660667743809*(1 - 0.5*x1)**2*(0.5*x0 + 1)**5*(0.5*x1 + 1)**3 - 0.00877183218731313*(-1.0*x0 - 1.0)**5*(0.5*x1 + 1)**5 - 0.05014500015286*(-1.0*x0 - 1.0)**4*(1.0*x0 + 2.0)*(0.5*x1 + 1)**5 - 0.305753800119799*(-1.0*x0 - 1.0)**3*(0.5*x0 + 1)**2*(0.5*x1 + 1)**5 - 0.237696136194338*(-1.0*x0 - 1.0)**2*(0.5*x0 + 1)**3*(0.5*x1 + 1)**5 - 0.570204676058344*(-1.0*x0 - 1.0)*(0.5*x0 + 1)**4*(0.5*x1 + 1)**5 - 0.661244434670083*(0.5*x0 + 1)**5*(0.5*x1 + 1)**5
	elif x0 in Interval(-1, 0): 
		y = -0.0848115198792099*x0**5*(0.5 - 0.25*x1)*(0.5*x1 + 1)**4 - 0.0280842060516237*x0**5*(1 - 0.5*x1)**5 - 0.230574961861885*x0**5*(1 - 0.5*x1)**4*(0.25*x1 + 0.5) - 0.182582148963189*x0**5*(1 - 0.5*x1)**3*(0.5*x1 + 1)**2 - 0.16051895866994*x0**5*(1 - 0.5*x1)**2*(0.5*x1 + 1)**3 + 0.0206638885834401*x0**5*(0.5*x1 + 1)**5 - 0.04184199392751*x0**4*(0.5 - 0.25*x1)*(1.0*x0 + 1.0)*(0.5*x1 + 1)**4 + 0.136173953805368*x0**4*(1 - 0.5*x1)**5*(1.0*x0 + 1.0) + 0.863156804790327*x0**4*(1 - 0.5*x1)**4*(1.0*x0 + 1.0)*(0.25*x1 + 0.5) + 0.933804828674357*x0**4*(1 - 0.5*x1)**3*(1.0*x0 + 1.0)*(0.5*x1 + 1)**2 + 0.816778259477465*x0**4*(1 - 0.5*x1)**2*(1.0*x0 + 1.0)*(0.5*x1 + 1)**3 - 0.136747129322713*x0**4*(1.0*x0 + 1.0)*(0.5*x1 + 1)**5 + 1.01298503582607*x0**3*(0.5 - 0.25*x1)*(1.0*x0 + 1.0)**2*(0.5*x1 + 1)**4 - 0.2706949205799*x0**3*(1 - 0.5*x1)**5*(1.0*x0 + 1.0)**2 - 1.37723821501169*x0**3*(1 - 0.5*x1)**4*(1.0*x0 + 1.0)**2*(0.25*x1 + 0.5) - 2.03475438340932*x0**3*(1 - 0.5*x1)**3*(1.0*x0 + 1.0)**2*(0.5*x1 + 1)**2 - 1.70313140658258*x0**3*(1 - 0.5*x1)**2*(1.0*x0 + 1.0)**2*(0.5*x1 + 1)**3 + 0.298439496408126*x0**3*(1.0*x0 + 1.0)**2*(0.5*x1 + 1)**5 - 1.95252571298771*x0**2*(0.5 - 0.25*x1)*(1.0*x0 + 1.0)**3*(0.5*x1 + 1)**4 + 0.262688486581088*x0**2*(1 - 0.5*x1)**5*(1.0*x0 + 1.0)**3 + 1.98831546856502*x0**2*(1 - 0.5*x1)**4*(1.0*x0 + 1.0)**3*(0.25*x1 + 0.5) + 2.26547508511396*x0**2*(1 - 0.5*x1)**3*(1.0*x0 + 1.0)**3*(0.5*x1 + 1)**2 + 0.959727001648322*x0**2*(1 - 0.5*x1)**2*(1.0*x0 + 1.0)**3*(0.5*x1 + 1)**3 - 0.306521772809081*x0**2*(1.0*x0 + 1.0)**3*(0.5*x1 + 1)**5 + 1.2796609751422*x0*(0.5 - 0.25*x1)*(1.0*x0 + 1.0)**4*(0.5*x1 + 1)**4 - 0.133416154240592*x0*(1 - 0.5*x1)**5*(1.0*x0 + 1.0)**4 - 1.22464492926908*x0*(1 - 0.5*x1)**4*(1.0*x0 + 1.0)**4*(0.25*x1 + 0.5) - 0.924107257193429*x0*(1 - 0.5*x1)**3*(1.0*x0 + 1.0)**4*(0.5*x1 + 1)**2 - 0.0366567809946536*x0*(1 - 0.5*x1)**2*(1.0*x0 + 1.0)**4*(0.5*x1 + 1)**3 + 0.154950951365019*x0*(1.0*x0 + 1.0)**4*(0.5*x1 + 1)**5 - 0.286797657706196*(0.5 - 0.25*x1)*(1.0*x0 + 1.0)**5*(0.5*x1 + 1)**4 + 0.0289209061892386*(1 - 0.5*x1)**5*(1.0*x0 + 1.0)**5 + 0.258328797854661*(1 - 0.5*x1)**4*(1.0*x0 + 1.0)**5*(0.25*x1 + 0.5) + 0.113355051736745*(1 - 0.5*x1)**3*(1.0*x0 + 1.0)**5*(0.5*x1 + 1)**2 - 0.0168031083896429*(1 - 0.5*x1)**2*(1.0*x0 + 1.0)**5*(0.5*x1 + 1)**3 - 0.0311374359692583*(1.0*x0 + 1.0)**5*(0.5*x1 + 1)**5
	elif x0 in Interval(0, 1.5):
		y = -0.221576753742516*x0**3*(0.5 - 0.25*x1)*(0.5*x1 + 1)**2 + 0.0273370990887415*x0**3*(1 - 0.5*x1)**3 - 0.0103006373022517*x0**3*(1 - 0.5*x1)**2*(0.25*x1 + 0.5) - 0.0370368618050895*x0**3*(0.5*x1 + 1)**3 - 0.983472078896807*x0**2*(0.5 - 0.25*x1)*(1 - 0.666666666666667*x0)*(0.5*x1 + 1)**2 + 0.147911306407804*x0**2*(1 - 0.666666666666667*x0)*(1 - 0.5*x1)**3 + 0.146114530996197*x0**2*(1 - 0.666666666666667*x0)*(1 - 0.5*x1)**2*(0.25*x1 + 0.5) - 0.166657706328419*x0**2*(1 - 0.666666666666667*x0)*(0.5*x1 + 1)**3 - 1.34087740256057*x0*(0.5 - 0.25*x1)*(1 - 0.666666666666667*x0)**2*(0.5*x1 + 1)**2 + 0.24134252011*x0*(1 - 0.666666666666667*x0)**2*(1 - 0.5*x1)**3 + 0.0245134543834145*x0*(1 - 0.666666666666667*x0)**2*(1 - 0.5*x1)**2*(0.25*x1 + 0.5) - 0.249889216905718*x0*(1 - 0.666666666666667*x0)**2*(0.5*x1 + 1)**3 - 0.276145641532087*(0.5 - 0.25*x1)*(1 - 0.666666666666667*x0)**3*(0.5*x1 + 1)**2 + 0.115683624756955*(1 - 0.666666666666667*x0)**3*(1 - 0.5*x1)**3 + 0.426568730373086*(1 - 0.666666666666667*x0)**3*(1 - 0.5*x1)**2*(0.25*x1 + 0.5) - 0.124549743877033*(1 - 0.666666666666667*x0)**3*(0.5*x1 + 1)**3
	elif x0 in Interval(1.5, 2):
		y = -319.935817838493*(0.5 - 0.25*x1)*(1 - 0.5*x0)**5*(0.5*x1 + 1)**4 - 399.946957257211*(0.5 - 0.25*x1)*(1 - 0.5*x0)**4*(2.0*x0 - 3.0)*(0.5*x1 + 1)**4 - 1799.84218978684*(0.5 - 0.25*x1)*(1 - 0.5*x0)**3*(0.666666666666667*x0 - 1)**2*(0.5*x1 + 1)**4 - 1349.92174908893*(0.5 - 0.25*x1)*(1 - 0.5*x0)**2*(0.666666666666667*x0 - 1)**3*(0.5*x1 + 1)**4 - 126.557612017576*(0.5 - 0.25*x1)*(4.0 - 2.0*x0)*(0.666666666666667*x0 - 1)**4*(0.5*x1 + 1)**4 - 75.9352716888999*(0.5 - 0.25*x1)*(0.666666666666667*x0 - 1)**5*(0.5*x1 + 1)**4 + 23.6192536126727*(1 - 0.5*x0)**5*(1 - 0.5*x1)**5 + 11.7033615728635*(1 - 0.5*x0)**5*(1 - 0.5*x1)**4*(0.25*x1 + 0.5) - 107.394323437658*(1 - 0.5*x0)**5*(1 - 0.5*x1)**3*(0.5*x1 + 1)**2 - 315.434644447754*(1 - 0.5*x0)**5*(1 - 0.5*x1)**2*(0.5*x1 + 1)**3 - 31.9998485995974*(1 - 0.5*x0)**5*(0.5*x1 + 1)**5 + 28.0544239822634*(1 - 0.5*x0)**4*(1 - 0.5*x1)**5*(2.0*x0 - 3.0) - 5.01589388389946*(1 - 0.5*x0)**4*(1 - 0.5*x1)**4*(2.0*x0 - 3.0)*(0.25*x1 + 0.5) - 176.623122799601*(1 - 0.5*x0)**4*(1 - 0.5*x1)**3*(2.0*x0 - 3.0)*(0.5*x1 + 1)**2 - 395.656673749074*(1 - 0.5*x0)**4*(1 - 0.5*x1)**2*(2.0*x0 - 3.0)*(0.5*x1 + 1)**3 - 39.9998646034803*(1 - 0.5*x0)**4*(2.0*x0 - 3.0)*(0.5*x1 + 1)**5 + 118.8849731783*(1 - 0.5*x0)**3*(1 - 0.5*x1)**5*(0.666666666666667*x0 - 1)**2 - 110.865682887353*(1 - 0.5*x0)**3*(1 - 0.5*x1)**4*(0.666666666666667*x0 - 1)**2*(0.25*x1 + 0.5) - 973.470419210769*(1 - 0.5*x0)**3*(1 - 0.5*x1)**3*(0.666666666666667*x0 - 1)**2*(0.5*x1 + 1)**2 - 1785.13054391813*(1 - 0.5*x0)**3*(1 - 0.5*x1)**2*(0.666666666666667*x0 - 1)**2*(0.5*x1 + 1)**3 - 179.999564096466*(1 - 0.5*x0)**3*(0.666666666666667*x0 - 1)**2*(0.5*x1 + 1)**5 + 83.0589039999059*(1 - 0.5*x0)**2*(1 - 0.5*x1)**5*(0.666666666666667*x0 - 1)**3 - 148.970644569484*(1 - 0.5*x0)**2*(1 - 0.5*x1)**4*(0.666666666666667*x0 - 1)**3*(0.25*x1 + 0.5) - 848.162042751341*(1 - 0.5*x0)**2*(1 - 0.5*x1)**3*(0.666666666666667*x0 - 1)**3*(0.5*x1 + 1)**2 - 1341.51834081319*(1 - 0.5*x0)**2*(1 - 0.5*x1)**2*(0.666666666666667*x0 - 1)**3*(0.5*x1 + 1)**3 - 134.999783623425*(1 - 0.5*x0)**2*(0.666666666666667*x0 - 1)**3*(0.5*x1 + 1)**5 + 6.63717037659708*(1 - 0.5*x1)**5*(4.0 - 2.0*x0)*(0.666666666666667*x0 - 1)**4 + 2.85136700166291*(1 - 0.5*x1)**5*(0.666666666666667*x0 - 1)**5 - 19.8175367927388*(1 - 0.5*x1)**4*(4.0 - 2.0*x0)*(0.666666666666667*x0 - 1)**4*(0.25*x1 + 0.5) - 15.2992697998482*(1 - 0.5*x1)**4*(0.666666666666667*x0 - 1)**5*(0.25*x1 + 0.5) - 90.0526181076045*(1 - 0.5*x1)**3*(4.0 - 2.0*x0)*(0.666666666666667*x0 - 1)**4*(0.5*x1 + 1)**2 - 59.1304382190112*(1 - 0.5*x1)**3*(0.666666666666667*x0 - 1)**5*(0.5*x1 + 1)**2 - 125.965508731429*(1 - 0.5*x1)**2*(4.0 - 2.0*x0)*(0.666666666666667*x0 - 1)**4*(0.5*x1 + 1)**3 - 75.6740213246269*(1 - 0.5*x1)**2*(0.666666666666667*x0 - 1)**5*(0.5*x1 + 1)**3 - 12.6562365690179*(4.0 - 2.0*x0)*(0.666666666666667*x0 - 1)**4*(0.5*x1 + 1)**5 - 7.59374466437586*(0.666666666666667*x0 - 1)**5*(0.5*x1 + 1)**5	
	else:
		raise ValueError('Undefined Partition')
	return y
Exemplo n.º 28
0
 def get_quota_modify_strategy(self, category_id, model_score,
                               original_quota):
     for quota_modify_strategy in self.quota_modify_strategy_list:
         score_segment = json.loads(quota_modify_strategy['score_segment'])
         quota_segment = json.loads(quota_modify_strategy['quota_segment'])
         score_in = model_score in Interval(score_segment[0],
                                            score_segment[1],
                                            upper_closed=False)
         quota_in = original_quota in Interval(quota_segment[0],
                                               quota_segment[1],
                                               upper_closed=False)
         if quota_modify_strategy[
                 'category_id'] == category_id and score_in and quota_in:
             return quota_modify_strategy
Exemplo n.º 29
0
 def test_overlap(self):
     """Test intervals overlap by 1, by a small value, and by a large value."""
     self.assertTrue(overlaps(Interval(1, 2), Interval(2, 3)))
     self.assertTrue(overlaps(Interval(1, 3), Interval(2, 4)))
     self.assertTrue(overlaps(Interval(1, 10), Interval(5, 15)))
     self.assertFalse(overlaps(Interval(1, 10), Interval(5, 15)),
                      'Expected failure here')
Exemplo n.º 30
0
    def __preprocess(self):
        """
        Preprocess the callset by filling the regions with no calls with EventType.NO_CALL events, thereby assigning
        an event to every single base.

        """

        for sample in self.sample_names:
            interval_to_call_map = OrderedDict()
            for contig in self.ref_dict.contigs:
                contig_interval = self.ref_dict.get_contig_interval_for_chrom_name(
                    contig)
                events_on_contig = self.sample_to_calls_map.get(
                    sample)._get_interval_tree(contig)
                if not events_on_contig:
                    continue

                result = events_on_contig.copy()
                # TODO make code aware of 1-based representation
                # TODO i.e. right now some events overlap by a single base
                # This hacky code fills potential gaps between calls that lie within interval with NO_CALL events
                result.addi(
                    contig_interval.start, contig_interval.end,
                    Call(interval=contig_interval,
                         sample=sample,
                         event_type=EventType.NO_CALL,
                         call_attributes={
                             "QS": 0,
                             "QA": 0
                         }))
                result.split_overlaps()
                for interval in events_on_contig.items():
                    result.remove_overlap(interval.begin, interval.end)
                for interval in events_on_contig.items():
                    result.addi(interval.begin, interval.end,
                                Call.deep_copy(interval.data))

                for t in sorted(result):
                    if t.end - t.begin == 1 and t.data.event_type == EventType.NO_CALL:
                        # intervaltree.split_overlaps will create single base regions which we want to discard
                        continue
                    call = Call.deep_copy(t.data)
                    if t.data.event_type == EventType.NO_CALL:
                        call.interval = Interval(contig, t.begin, t.end)
                    interval_to_call_map[Interval(contig, t.begin,
                                                  t.end)] = call
            self.sample_to_calls_map[sample] = FeatureCollection(
                interval_to_call_map)