Example #1
0
    def change_rule_to_math_inteval(rule):
        rule = rule.replace(' ', '')
        first_char = rule[0:1]
        last_char = rule[-1:]
        mid_str = rule[1:-1]

        try:
            upper_value = float(mid_str.split(',')[1])
        except:
            upper_value = float('inf')

        try:
            lower_value = float(mid_str.split(',')[0])
        except:
            lower_value = float('-inf')

        low_closed = True
        up_closed = True

        if first_char == '(' or first_char == '(':
            low_closed = False

        if last_char == ')' or last_char == ')':
            up_closed = False

        intev = Interval(lower_bound=lower_value, upper_bound=upper_value)
        intev.lower_closed = low_closed
        intev.upper_closed = up_closed

        return intev
Example #2
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)
Example #3
0
def query(root, value, visualize=0):
    out = [
    ]  # placeholder to store all the intervals which contain the query point
    vis_arr = []  # for visualizing the search
    curr = root
    while True:
        # check whether the current node has intervals corresponding to it, if yes, then add those
        if len(curr.getIntervalArr()) > 0:
            out.extend(curr.getIntervalArr())
            if visualize:
                vis_arr.append(copy.deepcopy(curr))
        if curr.getLeftChild() != None:
            # checks whether to move towards the left
            if Interval.liesOnInterval(curr.getLeftChild().getInterval(),
                                       value) or Interval.liesInInterval(
                                           curr.getLeftChild().getInterval(),
                                           value):
                curr = curr.getLeftChild()
                continue
        if curr.getRightChild() != None:
            # checks whether to move towards the right
            if Interval.liesOnInterval(curr.getRightChild().getInterval(),
                                       value) or Interval.liesInInterval(
                                           curr.getRightChild().getInterval(),
                                           value):
                curr = curr.getRightChild()
                continue
        # returns the list of intervals or nodes
        if visualize:
            return vis_arr
        return out
 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)
Example #5
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
Example #6
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
Example #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
Example #8
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
    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
Example #10
0
 def select_notes(self, melody):
     allowed_notes = []
     tonic = melody.key
     if "m" in melody.key:
         tonic = tonic[0:-1]
     allowed_notes.append(tonic)
     start_note = tonic + '4'  # arbitrary octave for computing notes
     current_note = Note(name=start_note)
     scale_steps = scales[melody.scale]['halfsteps']
     for steps in scale_steps:
         interval = Interval(note_1=current_note, halfsteps=steps)
         next_note = interval.get_topnote()
         note_name = next_note.get_name()[0:-1]
         allowed_notes.append(note_name)
         current_note = next_note
     octave = randint(melody.octave_range[0], melody.octave_range[1])
     for x in range(16):
         # pick note and add to melody
         note_name = choice(allowed_notes)
         note_name += str(octave)
         melody.append(Note(name=note_name))
         # pick next octave in range
         bottom = max(melody.octave_range[0], octave - 1)
         top = min(melody.octave_range[1], octave + 1)
         if randint(1, 10) < 2:
             octave = choice([bottom, top])
     return melody
Example #11
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
Example #12
0
    def __init__(self,
                 name,
                 parent,
                 samples,
                 alpha,
                 pi,
                 freezer,
                 logspace=False):
        Interval.__init__(self, samples, alpha, ndim=1)

        self.name = name
        self.parent = parent

        # method for computing p(theta | data)
        self.pi = pi

        self.freezer = freezer

        # compute the hpd interval
        # Adapted from "Monte Carlo Estimation of Bayesian Credible and HPD Intervals", Ming-Hui Chen and Qi-Man Shao, 1999
        # self.epsilon = [self.pi(t) for t in self.samples]
        self.epsilon = [self.compute_pi(sample=t) for t in self.samples]
        self.epsilon.sort()
        j = int(self.n * self.alpha)
        self.epj = self.epsilon[
            j]  # any observation with pi(x|D) > epj is in the region

        self.paramSamples = [s[parent][name] for s in self.samples]
        self.paramSamples.sort()
        self.lb = self.paramSamples[int(self.n * self.alpha)]
        self.ub = self.paramSamples[int(self.n * (1 - self.alpha))]
Example #13
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
    def __init__(self, foliation, coding):
        if coding.index >= foliation.num_intervals(coding.side):
            raise RestrictionError("Invalid interval index.")
        interval = Interval(coding.side, coding.index)

        # Checking if the curve is transverse
        if ((coding.num_flips1 % 2 == 1) != \
           (coding.num_flips2 % 2 == 1)) != \
                    interval.is_flipped(foliation):
            raise RestrictionError("Curve is not transverse to the foliation")


        other_int = interval.pair(foliation)
        other_end = coding.end
        if interval.is_flipped(foliation):
            other_end = (other_end + 1) % 2
        sep1 = Separatrix(foliation, interval, end = coding.end,
                          number_of_flips_to_stop = coding.num_flips1)
        sep2 = Separatrix(foliation, other_int, end = other_end,
                          number_of_flips_to_stop = coding.num_flips2)

        if sep1.is_flipped() == (coding.end == 1):
            openness = ('open','closed')
        else:
            openness = ('closed','open')

        self._sep = [sep1, sep2]
        # print self._sep
        arcs = [Arc(self._sep[i].endpoint, self._sep[(i+1)%2].endpoint,
                    *openness) for i in range(2)]
            

        self._arc = Arc(sep1.endpoint, sep2.endpoint, *openness)

        intersections = sep1.intersections()[:-1] + sep2.intersections()[:-1]

        # if one of the separatrices is longer, both arcs are considered,
        # so if the current one is wrong, we try the other one
        if coding.num_flips1 > 0 or coding.num_flips2 > 0:
            x = intersections[0]
            if self._arc.contains(x):
                self._arc = Arc(sep2.endpoint, sep1.endpoint, *openness)
                self._sep = [sep2, sep1]

        # if self._arc.length() > 0.5 and sep1.end_side == sep2.end_side:
        #     raise RestrictionError("There is either no such curve without "
        #                            "self-intersection or "
        #                            "the curve is one-sided and has length"
        #                            " greater than half, so we can't compute"
        #                            " the train track transition map. ")
        # print self._arc
        # print sep1, sep2
        for x in intersections:
            # print x
            if self._arc.contains(x):
                raise RestrictionError("The curve is self-intersecting")

        self._direction = RIGHT if openness[0] == 'closed' else LEFT
        self._coding = coding
    def test_overlaps(self):
        lunch = Interval(14, 16)
        meeting2 = Interval(12, 14)
        meeting3 = Interval(13, 15)

        self.assertFalse(meeting2.overlaps(lunch))
        self.assertTrue(meeting2.overlaps(meeting3))
        self.assertTrue(meeting3.overlaps(lunch))
Example #16
0
    def __init__(self, samples, alpha, start=1e-6, tol=1e-6, maxiter=100):
        Interval.__init__(self, samples, alpha, ndim=1)

        p = samples.n
        alphaPotential = 1. * np.arange(self.n) / self.n
        self.alpha = filter(
            lambda x: abs(x - self.alpha) == abs(self.alpha - alphaPotential).
            min(), alphaPotential)[0]

        self.mean = samples.array.mean(0)
        self.std = samples.array.std(0)
        self.lb, self.ub = self.mean - 2 * self.std, self.mean + 2 * self.std

        self.epsilon = start

        # function to calculate the empirical interval alpha for a given epsilon, x
        check = lambda x: 1. * sum(
            (self.samples.array > self.lb - x).all(1) &
            (self.samples.array < self.ub + x).all(1)) / self.n

        bounds = []

        # double to find lower and upper epislon bound
        while check(self.epsilon) < self.alpha:
            bounds.append((self.epsilon, check(self.epsilon)))
            self.epsilon *= 2

        bounds.append((self.epsilon, check(self.epsilon)))

        # binary search
        eLb, eUb = self.epsilon / 2, self.epsilon
        i = 0
        while True:
            if abs(check(eLb) - alpha) < tol:
                self.epsilon = eLb
                break
            elif abs(check(eUb) - alpha) < tol:
                self.epsilon = eUb
                break

            nb = (eLb + eUb) / 2

            if check(nb) < alpha:
                eLb = nb
                bounds.append((nb, check(nb)))
            else:
                eUb = nb
                bounds.append((nb, check(nb)))

            i += 1
            if i > maxiter:
                self.epsilon = eLb
                break

        self.bounds = bounds

        self.lb = self.mean - self.std - self.epsilon
        self.ub = self.mean + self.std + self.epsilon
Example #17
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
Example #18
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
    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)
Example #20
0
def test_interval_class():
    chrom = "1"
    start = 1000
    end = 2000
    test_interval = Interval(chrom=chrom, start=start, end=end)

    test_interval_correct_string = "Interval(1:1000-2000)"

    assert (test_interval.__str__() == test_interval_correct_string)
    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)
Example #22
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)
Example #23
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
Example #24
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
Example #25
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)
Example #26
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
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"
Example #28
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)
Example #29
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
    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)
Example #31
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
Example #32
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)
Example #33
0
    def _init_gen_perm(self, top_labels, bottom_letters, flips):
        """Initialize the permutation-related variables.

        More precisely: _gen_perm, _gen_perm_list, _all_intervals,
        _numerical_label, _pair. Other initializing methods depend on
        these variables, therefore this one must be called first.

        INPUT:

        - ``top_labels``,``bottom_labels``,``flips`` -- as in the constructor

        """
        self._gen_perm = GeneralizedPermutation(\
                        top_labels, bottom_letters, flips = flips)

        # The permutation in list form. Access is faster.
        self._gen_perm_list = self._gen_perm.list()

        # Saving the set of labels.
        self._labels = set(self._gen_perm.alphabet())
        self._labels.discard('JOKER')
        
        # The list of flipped labels.
        self._flips = self._gen_perm.flips() if \
                      isinstance(self._gen_perm[0][0], tuple) else []
        # In the first case, self._gen_perm is a FlippedLabelledPermutationLI
        # that has a flips() method
        # In the second case, self._gen_perm is a LabelledPermutationIET 
        # that doesn't have a flips method, but then there are no
        # flips, so we assign the empty list.

        
        # initializing self._numerical_label and self._pair
        self._all_intervals = [[], []]
        label_to_interval = {}
        self._numerical_label = {}
        count = 0
        self._pair = {}
        for side in {0, 1}:
            for index in range(len(self._gen_perm_list[side])):
                interval = Interval(side, index)
                self._all_intervals[side].append(interval)
                label = interval.label(self)
                if label not in self._numerical_label:
                    self._numerical_label[label] = count
                    count += 1
                    label_to_interval[label] = interval
                else:
                    self._pair[label_to_interval[label]] = interval
                    self._pair[interval] = label_to_interval[label]
Example #34
0
	def test_mergeIntervals(self):
		int_1 = "[4, 9)"
		int_2 = "(5, 12]"
		result = Interval.mergeIntervals(int_1, int_2)
		self.assertTrue(result)
		self.assertEqual(result.lower, 4)
		self.assertEqual(result.upper, 12)
		self.assertEqual(result.lowerBound, "[")
		self.assertEqual(result.upperBound, "]")
Example #35
0
def annotate_fusion(ref_f, input_f, output_f):
    """
    Align fusion juncrions to gene annotations
    """
    print('Start to annotate fusion junctions...')
    genes, gene_info = parse_ref1(ref_f)  # gene annotations
    fusions, fusion_index = parse_bed(input_f)  # fusion junctions
    total = set()
    with open(output_f, 'w') as outf:
        for chrom in genes:
            # overlap gene annotations with fusion juncrions
            result = Interval.overlapwith(genes[chrom].interval,
                                          fusions[chrom])
            for itl in result:
                # extract gene annotations
                iso = list(filter(lambda x: x.startswith('iso'), itl[2:]))
                # for each overlapped fusion junction
                for fus in itl[(2 + len(iso)):]:
                    reads = fus.split()[1]
                    fus_start, fus_end = fusion_index[fus]
                    edge_annotations = []  # first or last exon flag
                    for iso_id in iso:
                        g, i, c, s = iso_id.split()[1:]
                        start = gene_info[iso_id][0][0]
                        end = gene_info[iso_id][-1][-1]
                        # fusion junction excesses boundaries of gene
                        # annotation
                        if fus_start < start - 10 or fus_end > end + 10:
                            continue
                        (fusion_info,
                         index,
                         edge) = map_fusion_to_iso(fus_start,
                                                   fus_end, s,
                                                   gene_info[iso_id])
                        if fusion_info:
                            fus_start_str = str(fus_start)
                            fus_end_str = str(fus_end)
                            bed_info = '\t'.join([chrom, fus_start_str,
                                                  fus_end_str,
                                                  'FUSIONJUNC/%s' % reads,
                                                  '0', s, fus_start_str,
                                                  fus_start_str, '0,0,0'])
                            bed = '\t'.join([bed_info, fusion_info, g, i,
                                             index])
                            if not edge:  # not first or last exon
                                outf.write(bed + '\n')
                                total.add(fus)
                            else:  # first or last exon
                                edge_annotations.append(bed)
                    if edge_annotations:  # first or last exon
                        for bed in edge_annotations:
                            outf.write(bed + '\n')
                        total.add(fus)
    print('Annotated %d fusion junctions!' % len(total))
Example #36
0
File: comm.py Project: ctanis/PGDB
 def _get_stream_for_interval(self, interval):
     """Given an interval, get the appropriate stream for it."""
     if interval == self.frontend:
         return self.mrnet_frontend_stream
     elif interval == self.broadcast:
         return self.mrnet_broadcast_stream
     else:
         if isinstance(interval, int):
             interval = Interval(interval)
         stream = None
         mrnet_ranks = []
         for rank in interval.members():
             mrnet_ranks.append(self.mpirank_to_mrnrank(rank))
         # Since multiple MPI ranks correspond to one MRNet rank, eliminate duplicates.
         mrnet_ranks = list(set(mrnet_ranks))
         comm = self.mrnet.new_Communicator(mrnet_ranks)
         return self.mrnet.new_Stream(comm,
                                      self.filter_ids[0],
                                      MRN.SFILTER_WAITFORALL,
                                      MRN.TFILTER_NULL)
Example #37
0
	def test_insert(self):
		input_1 = '(-9, -6], [1, 16], [24, 36)'
		input_2 = '(16, 24)'
		result = Interval.insert(input_1, input_2)
		int_1 = result[0]
		int_2 = result[1]
		self.assertTrue(int_1)
		self.assertEqual(int_1.lower, -9)
		self.assertEqual(int_1.upper, -6)
		self.assertEqual(int_1.lowerBound, "(")
		self.assertEqual(int_1.upperBound, "]")
		self.assertTrue(int_2)
		self.assertEqual(int_2.lower, 1)
		self.assertEqual(int_2.upper, 36)
		self.assertEqual(int_2.lowerBound, "[")
		self.assertEqual(int_2.upperBound, ")")
Example #38
0
def findWeakestLink(list):
    wkstLink = sys.maxint
    maxInter = list[0]
    for i in range(len(list)-1):
        #Candidate list stores possible candidates for weakest link
        candList = []
        if not list[i].isContained(maxInter):
            cand1 = list[i].max - list[i+1].min
            candList.append(cand1)
        cand2 = list[i].max - list[i].min
        candList.append(cand2)
        if min(candList)< wkstLink:
            wkstLink = min(candList)
        maxInter = Interval.maxInterval(maxInter, list[i])
            
    return wkstLink
Example #39
0
	def __init__(self, gradient, path):
		""" 
			gradient: A gradient object to act as background
			path: path to images

		"""
		self.screen = gradient
		self.center = self.screen.get_rect().center

		self.path = path

		# interval class
		self.intervals = Interval()

		self.instr_str = 'UP AND DOWN ARROWS COARSE TUNE. USE LEFT AND RIGHT FOR FINE ADJUSTMENT'
		self.conf_str = 'PRESS ENTER TO CONFIRM'

		self.setLevel(self.level)

		self.initGUI()
Example #40
0
	def test_mergeOverlapping(self):
		input_1 = '[1, 9), (-9, -6], [6, 12), [24, 36), [12, 16]'
		result = Interval.mergeOverlapping(input_1)
		int_1 = result[0]
		int_2 = result[1]
		int_3 = result[2]
		self.assertTrue(int_1)
		self.assertEqual(int_1.lower, -9)
		self.assertEqual(int_1.upper, -6)
		self.assertEqual(int_1.lowerBound, "(")
		self.assertEqual(int_1.upperBound, "]")
		self.assertTrue(int_2)
		self.assertEqual(int_2.lower, 1)
		self.assertEqual(int_2.upper, 16)
		self.assertEqual(int_2.lowerBound, "[")
		self.assertEqual(int_2.upperBound, "]")
		self.assertTrue(int_1)
		self.assertEqual(int_3.lower, 24)
		self.assertEqual(int_3.upper, 36)
		self.assertEqual(int_3.lowerBound, "[")
		self.assertEqual(int_3.upperBound, ")")
 def test_contains_5(self):
     i = Interval(3, 8)
     self.assertTrue(i.contains(5))
Example #42
0
class Game:
	""" The main game class. This deals with two oscillators, of which one is adjustable.
		The diffrence between those frequencies are measured and compared to the wanted interval.
		Margin of errors is given i cents.

	 """
	screen = None
	center = None #screen center
	instructions = None #instructions surface
	interval = None #interval surface
	result = None # surface for result displaying


	path = None #for resources

	#GUI elements
	knob = None
	knob_rect = None
	plate = None

	running = False #state check

	intevals = None #interval array
	guide_osc = None # guide note oscillator
	guide = None # guide_osc frequency
	osc = None # user ajustable oscillator
	guide_ch = None #Audio channel
	osc_ch = None #Audio channel
	pitch = None # osc frequency


	steps = 1 # number of musical notes. Level one starts at an octave
	prev_steps = [] #stores old game settings
	max_freq = 0 # 4 x base oscillator frequency (two octaves)
	min_freq = 0 # bace oscillator frequency

	level = 1 #level

	pause = False # pausing main loop

	practise = False
	tuner = None

	acceptable_off = 10 # how many cents off for a corrects answer?


	def __init__(self, gradient, path):
		""" 
			gradient: A gradient object to act as background
			path: path to images

		"""
		self.screen = gradient
		self.center = self.screen.get_rect().center

		self.path = path

		# interval class
		self.intervals = Interval()

		self.instr_str = 'UP AND DOWN ARROWS COARSE TUNE. USE LEFT AND RIGHT FOR FINE ADJUSTMENT'
		self.conf_str = 'PRESS ENTER TO CONFIRM'

		self.setLevel(self.level)

		self.initGUI()
		#self.initAudio()

	def initGUI(self):
		""" Inits the graphical components """

		#clear background
		self.screen.clear()
		self.screen.draw()

		#knob image
		img = pygame.image.load(self.path + 'knob.png')

		#plates
		self.plate = pygame.image.load(self.path + 'rust.png')

		self.knob = Knob(img)
		self.knob.set_plate(self.plate)
		#self.knob.set_shadow((-6,-4), 150, 25)
		knb_center = self.knob.get_rect().center
		self.knob = (self.knob, (self.center[0]-knb_center[0], self.center[1]-knb_center[1])) # also stores knob.rect at blit time		
		
		self.center = self.screen.get_rect().center

		#"back" 
		back_img = pygame.image.load(self.path + 'back.png')
		back_pos = (30,30)
		#tuple width the image and it's position and a third element containting elements Rect.
		self.back = (back_img, (30,30), self.screen.blit(back_img, back_pos))

		#arrow
		arrow_img = pygame.image.load(self.path + 'arrow.png')
		self.arrow = (arrow_img, (self.center[0] - arrow_img.get_width()/2, 104)) 

		#instructions, texts
		instrs = ['UP', 'DOWN', 'FINE UP', 'FINE DOWN', 'PRESS ENTER TO CONFIRM']
		font = pygame.font.Font(self.path + 'Actor-Regular.ttf', 10)

		#instructions, key images
		key_images = pygame.Surface((184, 69), pygame.SRCALPHA, 32) #collecting those images in a surface, for flexible positioning.
		key_images_cp = key_images.get_rect().center

		img = pygame.image.load(self.path + 'key.png')
		up = pygame.transform.rotozoom(img, 90, 1)
		key_images.blit(up, (key_images_cp[0] - up.get_size()[0]/2, 0)) #up arrow
		key_images.blit(font.render(instrs[0], True, BLACK), (key_images_cp[0] - font.size(instrs[0])[0]/2, 9)) #up text
		key_images.blit(font.render(instrs[3], True, BLACK), (0, key_images_cp[1] - font.size(instrs[3])[1]/2)) #left text
		left = pygame.transform.rotozoom(img, 180, 1)
		key_images.blit(left, (font.size(instrs[3])[0] + 5, key_images_cp[1] - left.get_size()[1]/2)) #left arrow
		right = img
		key_images.blit(right, (key_images.get_width() - font.size(instrs[3])[0] - 5 - right.get_size()[0], key_images_cp[1] - right.get_size()[1]/2)) #right arrow (reflects left)
		key_images.blit(font.render(instrs[2], True, BLACK), (key_images.get_width() - font.size(instrs[3])[0] + 5 - right.get_size()[0], key_images_cp[1] - font.size(instrs[2])[1]/2)) #right text
		key_images.blit(font.render(instrs[1], True, BLACK), (key_images_cp[0] - font.size(instrs[1])[0]/2, 44)) #down text
		down = pygame.transform.rotozoom(img, 270, 1)
		key_images.blit(down, (key_images_cp[0] - down.get_size()[0]/2, 69 - down.get_size()[1])) #up arrow

		#public parent container for instructions
		self.instructions = pygame.Surface((self.screen.get_width(), 115), pygame.SRCALPHA, 32)
		self.instructions.blit(key_images, (self.instructions.get_rect().center[0] - key_images_cp[0], 0))
		self.instructions.blit(font.render(instrs[4], True, BLACK),(self.instructions.get_rect().center[0] - font.size(instrs[4])[0]/2, key_images.get_height() + 20))


	def initAudio(self):
		""" Inits the two oscillators and their channels. """

		#guide tone
		self.guide_osc = Oscillator('sine', self.guide, BUFFER_SIZE)
		self.guide_ch = pygame.mixer.Channel(0)
		self.guide_ch.set_volume(0.9/2.0)

		#adjustable (the knob one), starts at same freq
		self.osc = Oscillator('sine', self.pitch, BUFFER_SIZE)
		self.osc_ch = pygame.mixer.Channel(1)
		self.osc_ch.set_volume(0.9/2.0)

	def setLevel(self, level):
		""" inits different levels """

		lowest_freq = 220 # low limit
		# for use in levels > 4
		rand_guide = self.stepToFreq(random.randint(0, 12), 220) # 220Hz < 440Hz in perfect notes.

		if level == 1:
			self.guide = 440
			self.steps = 0
			self.pitch = self.stepToFreq(1, self.guide)

		elif level == 2:
			self.guide = 440
			self.steps = 12
			self.pitch = self.stepToFreq(11, self.guide)

		elif level == 3:
			self.guide = 440
			self.steps = 7
			self.pitch = self.stepToFreq(6, self.guide)

		elif level == 4:
			self.guide = rand_guide
			self.steps = 5
			init_rand = random.randint(0, 11)
			self.pitch = self.stepToFreq(init_rand, self.guide)

		elif level == 5:
			self.guide = rand_guide
			self.steps = self.randExclude(self.prev_steps + [5], 0,12)
			init_rand = random.randint(0, 11)
			self.pitch = self.stepToFreq(11, self.guide)

		elif level == 6:
			self.guide = rand_guide
			self.steps = self.randExclude(self.prev_steps + [6])
			init_rand = random.randint(0, 24)
			self.pitch = self.stepToFreq(11, self.guide)

		elif level >= 7:
			self.guide = rand_guide
			self.steps = random.randint(0,24) # whole range
			init_rand = random.randint(0, 24)
			self.pitch = self.stepToFreq(11, self.guide)

		else:
			return False

		self.prev_steps.append(self.steps) #store, for unique intervals the first 6 levels
		
		# set min/max frequencies
		self.max_freq = self.guide * 4 # maximum frequency
		self.min_freq = self.guide - 20# minimum frequency 
		
		#set interval text
		self.setIntervalText()

	def setIntervalText(self):
		""" Text to display the wanted interval """
		font = pygame.font.Font(pygame.font.get_default_font(), 18)
		img = font.render(self.intervals.at(self.steps), True, BLACK)
		#interval surface gets made every time function is called, this is done during pauses in main loop. The inefficiency should not be a problem.
		self.interval = pygame.Surface((self.screen.get_width(), font.get_height()), SRCALPHA, 32)
		self.interval.blit(img, (self.center[0] - img.get_width()/2, 0))



	def draw(self):
		""" draw screen """

		self.back = (self.back[0], self.back[1], self.screen.blit(self.back[0], self.back[1]))
		self.screen.blit(self.arrow[0], self.arrow[1])

		self.screen.blit(self.knob[0], self.knob[1])

		if not self.pause:
			self.screen.blit(self.interval, (0, 70))
			self.screen.blit(self.instructions, (0, 285))

		#practise mode?
		if self.practise is True:
			#display tuner
			goal = self.stepToFreq(self.steps, self.guide_osc.frequency())
			cents = self.hertzToCents(goal, self.pitch)
			self.tuner.update(cents)
			self.screen.blit(self.tuner, (self.center[0]-self.tuner.center[0], 20))

		self.screen.draw()

	def updateChannels(self):
		""" update audio queues """
		if self.guide_ch.get_queue() == None:
			self.guide_ch.queue(self.guide_osc.samples())

		if self.osc_ch.get_queue() == None:
			self.osc_ch.queue(self.osc.samples())

	def set_practise(self, on=True):
		""" Turn practise mode on/off """
		self.practise = on
		self.tuner = Tuner(self.path) #initiats at practise on, and stays.

	def message(self):
		""" Checks current frequency (at the adjustable oscillator)
			and sets a message to user
		"""
		font = pygame.font.Font(pygame.font.get_default_font(), 18)

		goal = self.stepToFreq(self.steps, self.guide_osc.frequency())
		cents = self.hertzToCents(goal, self.pitch)

		self.screen.clear()

		if cents < 0: off = 'flat'
		elif cents > 0: off = 'sharp'

		msg = ''

		#ok?
		if cents > -self.acceptable_off and cents < self.acceptable_off:
			self.level += 1;
			self.setLevel(self.level)
			self.guide_osc.set_frequency(self.guide)

			msg = 'Well done! Just ' + str(round(cents,1)) + ' cents ' + off + '.'
		else:
			msg = str(round(cents,1)) + ' cents ' + off + '. Try again'

		if round(cents,1) == 0:
			msg = 'Amazing! Right on the spot!'

		#display message
		img = font.render(msg.upper(), True, BLACK)
		self.screen.blit(img, (self.center[0] - img.get_width()/2, 70))

		#instruction message
		cont = 'PRESS ANY KEY TO CONTINUE.'
		font = pygame.font.Font(self.path + 'Actor-Regular.ttf', 10)
		self.screen.blit(font.render(cont, True, BLACK),(self.center[0] - font.size(cont)[0]/2, self.screen.get_height() - font.size(cont)[1] - 13))

		self.draw()

	def run(self):
		""" main game loop.
			Always starts from level 1, and reinits the oscillators/audio channels 
		"""

		if self.running:
			return False
		self.running = True
		degrees = 0
		self.setLevel(1) # start from level 1 again
		self.initAudio() # init audio here for fresh oscillators

		clock = pygame.time.Clock()

		while self.running:
			
			if not self.pause:
				#start with checking each channels audio queue
				self.updateChannels()
				self.screen.clear()

				mx,my = pygame.mouse.get_pos()
				keystate = pygame.key.get_pressed()

				#fast increase frequency
				if keystate[K_UP]:
					if self.pitch < self.max_freq:
						self.pitch += 1.6#*= 1.01
						#self.pitch *= 1.01
						degrees += 1.3
						self.knob[0].rotate(degrees)

				#fast decrease frequency
				elif keystate[K_DOWN]:
					if self.pitch > self.min_freq:
						self.pitch -= 1.6#/= 1.01
						#self.pitch /= 1.01
						degrees -= 1.3
						self.knob[0].rotate(degrees)

				#slow decrease frequency
				elif keystate[K_LEFT]:
					if self.pitch > self.min_freq:
						self.pitch -=  0.1
						degrees -= 0.2
						self.knob[0].rotate(degrees)

				#slow increase frequency
				elif keystate[K_RIGHT]:
					if self.pitch < self.max_freq:
						self.pitch += 0.1
						degrees += 0.2
						self.knob[0].rotate(degrees)

				self.osc.set_frequency(self.pitch)
				

			for e in pygame.event.get():
				if e.type == QUIT:
					self.running = False

				elif e.type == MOUSEBUTTONDOWN:
					#check back button
					if self.back[2].collidepoint(e.pos):
						self.running = False

				elif e.type == KEYUP:
					#unpause
					if self.pause:
						self.pause = False
						break
					elif e.key == K_RETURN:
						self.pause = True
						self.message()
						
			if not self.pause:
				#redraw screen
				self.draw()
			clock.tick(60)


		self.running = False
		return True


	#helpers
	def hertzToCents(self, a, b):
		try:
			return 1200 * math.log((b/float(a)), 2)
		except Exception as e:
			print e
			return 0

	def posToDeg(self, pos): #not used
		""" Returns a positions degree from windows center """
		degree = math.degrees(math.atan2(self.center[1]-pos[1], self.center[0]-pos[0])) + 180
		if degree == 360.0:
			degree = 0
		return round(degree)

	def randExclude(self, seq, low=0, high=24):
		""" returns a random integer

			seq: numbers to exclude (list)
			low: lowest int
			high: highest int
		"""
		rand = 0
		while rand in seq:
			rand = random.randint(low, high)
		return rand

	def stepToFreq(self, step, frequency=False):
		""" returns a frequncy scale or a new frequency

			step: number of keys
			frequency: from frequency
		"""
		if not frequency:
			return math.pow(2, step/12.0)

		return frequency * math.pow(2, step/12.0)

	def freqToNote(self, freq): #not used
		""" Code for determining note name from frequency value.
			Code is written for equal temperament and A=440.
			Notes are displayed according to sharps. This can be overrided easily by changing the array definition below.

			Written by Firat Civaner (for mathlab)
			http://www.mathworks.com/matlabcentral/fileexchange/35330-frequency-to-note/content/freq2note.m


			return: A tuple with  a string with notename + octave and frequency offset in cents
		"""

		A4 = 440
		notenames = ['C' , 'C#', 'D' , 'D#' , 'E' , 'F' , 'F#', 'G' , 'G#' , 'A' , 'A#' , 'B' ]

		centdif = round( 1200 * math.log(freq/A4)/math.log(2))

		notedif = round(centdif/100)
		if centdif % 100 > 50:
			notedif = notedif + 1

		error = centdif-notedif*100
		notenumber = notedif + 9 + 12*4 #count of half tones starting from C0.

		octavenumber = round((notenumber)/12)
		place = int(round(notenumber % 12 + 1))
		if place < 0 or place > len(notenames)-1:
			print place
			return 'error'
		try:
			return (notenames[place]+str(octavenumber), error)
		except:
			return 'Error. Could not identify note'
Example #43
0
        user_input = raw_input("Interval?: ")
        if user_input == "quit":
            continue_flag = False
        else:
            try:
                # Validate the users interval input. Strips white spaces.
                user_input = user_input.strip().replace(' ', '')
                # Uses a regular expression to verify the format of the input
                lone_interval_pattern = '([\(|\[]-?\d+,-?\d+[\)|\]])'
                match = re.findall(lone_interval_pattern, user_input)
                # If there is a match continues with the program, if not, an exception is raised.
                if match:
                    user_input = match[0]

                    interval_to_insert = Interval(user_input)
                    interval_objects_list = Interval.insert(interval_objects_list, interval_to_insert)
                    print interval_objects_list
                else:
                    raise IntervalException("User Interval Input with invalid format. Try again")

            except IntervalException as e:
                print e

except IntervalException as e:
    print "Interval Error:", e
except ValueError as e:
    print "Interval Error:", e


"""
interval3 = Interval('[-10,-7]')
Example #44
0
 def test_insertintervals(self):
     s = LeetSolution()
     r = s.insertintervals(Interval.fromlist([1, 3, 6, 9]), Interval(2, 5))
     self.assertEqual([1, 5, 6, 9], Interval.tolist(r))
     r = s.insertintervals(Interval.fromlist([1, 2, 3, 5, 6, 7, 8, 10, 12, 16]), Interval(4, 9))
     self.assertEqual([1, 2, 3, 10, 12, 16], Interval.tolist(r))
Example #45
0
 def testMapto(self):
     r = Interval.mapto(self.d, self.c)
     self.assertListEqual(r, [[3, 4, 'a', 'I'], [3, 7, 'b', 'I'], [4, 6, 'e', 'I'], [4, 7, 'd', 'I'], [5, 7, 'f', 'I'],
                              [10, 11, 'd', 'II'], [10, 12, 'x', 'II'], [16, 20, 'x', 'III'], [16, 17, 'h', 'III'], 
                              [18, 20, 'i', 'III'], [23, 24, 'x', 'IV']], 'Failed in Mapto')
 def test_lower_endpoint_4_9(self):
     i = Interval(4, 9)
     self.assertEqual(i.lower(), 4)
     self.assertEqual(i.upper(), 9)
Example #47
0
 def __call__(self, param):
     f_value = self.__f(param)
     if isinstance(f_value, Interval):
         return Interval.cos(f_value)
     else:
         return math.cos(f_value)
Example #48
0
    while True:
        answer = input('Continue? (y/n): ')
        if answer in ('y', 'n', 'yes', 'no', 'Y', 'Yes', 'N', 'No'):
            break
        print('Invalid input.')
        
    if answer in ('y', "yes", 'Y', 'Yes'):
        break
    else:
        print('Sorry to see you go.')
        sys.exit()

while True:
    userInput = input("List of intervals?  ")
    try:
    	intList = Interval.mergeOverlapping(userInput)
    	print(intList)
    	break
    except:
    	print("Invalid list")


while True:
	addOn = input("interval?  ")
	if addOn == "quit":
		print('Sorry to see you go.')
		sys.exit()

	try:
		test = Interval(addOn)
	except:
Example #49
0
 def test_fromlist(self):
     l = [1, 2, 3, 10, 12, 16]
     r = Interval.fromlist(l)
     print(Interval.tolist(r))
Example #50
0
    def add_match(self, page, match):
        # l('ADDING ' + str(match))
        info = RangeMatch(self, page, match)
        # l(info)
        pageno = page.info['number']
        pagenoval = rnum_to_int(pageno)
        if pagenoval == 0 and len(pageno) > 0:
            pagenoval = int(pageno)

        matchint = Interval.between(match.b, match.b + match.size)

        overlaps = [m for m in self.matches
                    if m & matchint]

        # if nearnos matches either, mark flag and amp score
        if pageno:
            nearnos = self.find_nearnos(match)
            # l("GREPME near is [%s] pagenoval %s" % (nearnos, pagenoval))
            # for no in nearnos[1], nearnos[0]:
            if nearnos is None: # XXX SHOULDN"T BE NEEDED!!!!!!!!!!!!
                nearnos = []
            for no in nearnos[1], nearnos[0]:
            # for no in nearnos:
                if no is not None:
                    # l(no.val)
                    if no.val == pagenoval:
                        info.notes += 'nearno: %s' % pageno
                        # l("GOODMATCH tc %s, %s %s" % (self.page.index, pageno, self.score))
                        self.score += 1
                        info.nearno = no.word_index
                        break
                    if no.val > pagenoval - 10 and match.a < 10:
                        self.score += .01
                        break

        # cases: no overlap
        if len(overlaps) == 0:
            self.matchinfo[matchint] = info
            self.matches = self.matches + IntervalSet([matchint])
        else:
            start = match.b
            end = match.b + match.size
            for i in overlaps:
                oinfo = self.matchinfo[i]
                ostart = oinfo.match.b
                oend = oinfo.match.b + oinfo.match.size
                scootback = 0
                if ostart < start:
                    scootback = start - ostart
                    start = ostart
                if oend > end:
                    end = oend
                info.match = Match(info.match.a - scootback, start, end - start)
                if oinfo.nearno != -1:
                    # assert(info.nearno == -1)
                    info.nearno = oinfo.nearno
                # info.score += oinfo.score
                # info.pageno = oinfo.pageno
                # info.notes = info.notes + ' ' + info.notes
                # for opageno in oinfo.pagenos:
                #     opagecount = oinfo.pagenos[opageno]
                #     if opageno in info.pagenos:
                #         info.pagenos[opageno] += opagecount
                #     else:
                #         info.pagenos[opageno] = opagecount
            self.matches += IntervalSet([matchint])
            (new_i,) = [m for m in self.matches if m & matchint]
            self.matchinfo[new_i] = info
Example #51
0
    def _parse(values):
        """
        Parse a ``list`` into the standard format used by ValueSet objects.
        Any ``int``\s, ``long``\s, and ``float``\s are absorbed into an
        Interval object if they are contained by that Interval and the base
        types contained in ``values`` are sorted.

        :return: Filtered, sorted values in the ValueSet standard format.
        :rtype: ``list``

        :raises TypeError: ``values`` parameter must be either a ``list`` or \
        ``set``.
        """

        def _extend_intervals(type_lists):
            """
            If int or long is just beyond infirmum or supremum, extend the
            interval.
            """

            for i in type_lists[int]:
                for index, interval in enumerate(type_lists["_is_Interval"]):
                    if interval._type == int:
                        if i == interval[0] - 1:
                            type_lists["_is_Interval"][index] = Interval(i, interval[1])
                            type_lists[int].remove(i)
                            return True
                        if i == interval[1] + 1:
                            type_lists["_is_Interval"][index] = Interval(interval[0], i)
                            type_lists[int].remove(i)
                            return True

            for i in type_lists[long]:
                for index, interval in enumerate(type_lists["_is_Interval"]):
                    if interval._type == long:
                        if i == interval[0] - 1:
                            type_lists["_is_Interval"][index] = Interval(i, interval[1])
                            type_lists[long].remove(i)
                            return True
                        if i == interval[1] + 1:
                            type_lists["_is_Interval"][index] = Interval(interval[0], i)
                            type_lists[long].remove(i)
                            return True
            return False

        def _filter_numerics(type_lists):
            """Filter out numeric values subsumed by some Interval."""
            # filter out the ints, floats, and longs, subsumed by some Interval
            bad_ints, bad_floats, bad_longs = [], [], []
            for i in type_lists[int]:
                for interval in type_lists["_is_Interval"]:
                    if interval._type == int:
                        if i in interval:
                            if i not in bad_ints:
                                bad_ints.append(i)

            for f in type_lists[float]:
                for interval in type_lists["_is_Interval"]:
                    if interval._type == float:
                        if f in interval:
                            if f not in bad_floats:
                                bad_floats.append(f)

            for l in type_lists[long]:
                for interval in type_lists["_is_Interval"]:
                    if interval._type == long:
                        if l in interval:
                            if l not in bad_longs:
                                bad_longs.append(l)

            for bi in bad_ints:
                type_lists[int].remove(bi)

            for bf in bad_floats:
                type_lists[float].remove(bf)

            for bl in bad_longs:
                type_lists[long].remove(bl)

        # only accept sets and lists for valueset parameter
        if not isinstance(values, list) and not isinstance(values, set):
            raise TypeError("values paramter must be a list or set")

        # make copy of input before processing
        input_set = deepcopy(values)

        # convert set to list
        if isinstance(input_set, set):
            input_set = list(input_set)

        type_lists = ValueSet._split_by_types(values)

        # If intervals are within this valueset
        if type_lists["_is_Interval"]:
            type_lists["_is_Interval"] = Interval.collapse_intervals(
                type_lists["_is_Interval"])
            while _extend_intervals(type_lists): pass
            _filter_numerics(type_lists)

        output_set = []
        # reconstruct list, sorting when possible
        for base_type in ValueSet._base_types:
            output_set += sorted(type_lists[base_type])
        for object_type in ValueSet._object_types:
            output_set += type_lists[object_type]

        return output_set
Example #52
0
 def testOverlapwith(self):
     r = Interval.overlapwith(self.c, self.d)
     self.assertListEqual(r, [[3, 7, 'I', 'a', 'b', 'e', 'd', 'f'], [10, 12, 'II', 'd', 'x'], [16, 20, 'III', 'x', 'h', 'i'],
                              [23, 25, 'IV', 'x']], 'Failed in Overlapwith')
def get_tt_map(old_fol, new_fol, path_entries, transformation_coding):
    tt_new = new_fol.train_track()
    tt_old = old_fol.train_track()
    vertex_map = {}
    edge_map = {}

    # Finding the strip which is not rectangular but L-shaped
    # more specifically, the long vertical end of it.
    to_be_corrected = []
    if not new_fol.is_bottom_side_moebius():
        long_path_int = Interval(BOTTOM, new_fol.num_intervals(BOTTOM) - 1)
        
    else:
        side, pos = new_fol.in_which_interval(0, BOTTOM)
        long_path_int = Interval(0, pos)
        
    # Also, finding the intervals on the opposite side of it that will need
    # to be corrected.
    start = long_path_int.raw_endpoint(LEFT, new_fol)
    # new_fol.divpoints[long_path_int[0]][long_path_int[1]]
    bound = start + 0.5 if new_fol.is_bottom_side_moebius() else start
    n = new_fol.num_intervals(TOP) - 1
    
    while Interval(TOP, n).raw_endpoint(LEFT, new_fol) > bound:
        to_be_corrected.append((0,n))
        n -= 1


    for interval in new_fol.intervals():
        side, pos = interval.as_tuple()
        # print x1, x2
        if not (side, pos, 0) in path_entries:
            continue
        pe = [path_entries[(side, pos, i)] for i in [LEFT, RIGHT]]
        # print pe[0]
        # print pe[1]
        long_end = None
        # for i in [LEFT, RIGHT]:
        if (side, pos) == long_path_int:
            # the long end is at the beginning
            long_end = (START, LEFT)
            # print (pe[i].new_side, pe[i].new_end, i)
            # print long_path
        elif (pe[0].new_side, pe[0].new_i) == long_path_int:
            # the long end is at the end
            long_end = (END, pe[0].new_end)
        tails, center = break_apart([pe[0].path,pe[1].path], long_end)
        
        # print side, pos
        # print "tails: ", tails
        # print "center:", center
        # print "long_path_int:", long_path_int
        # print "Long end:", long_end

        # computing the path in the long part of the L-shaped strip that has to
        # be appended to some other paths on the other side
        if long_end != None:
            # finding the right tail 
            long_path_to_append = tails[long_end[0]][long_end[1]]
            
            # reversing if necessary
            if long_end[0] == END:
                long_path_to_append = TrainTrackPath(long_path_to_append).reversed()
                
            # cutting off the first edge
            long_path_to_append = long_path_to_append[1:]

        v0 = vertex_map[interval] = tails[START][LEFT][-1].end()
        v1 = vertex_map[interval.pair(new_fol)] = tails[END][LEFT][0].start()
        edge_map[tt_new.get_edge_from(interval, 'pair')] = TrainTrackPath(center)
        edge_map[tt_new.get_edge_from(interval, 'center')] = TrainTrackPath(tails[START][LEFT]).reversed()
        b = tails[END][RIGHT if interval.is_flipped(new_fol) else LEFT]
        edge_map[tt_new.get_edge_from(interval.pair(new_fol), 'center')] = TrainTrackPath(b)

    # print long_path_to_append
    # print to_be_corrected
    # print edge_map
    for (side, pos) in to_be_corrected:
        interval = Interval(side, pos)
        edge_map[tt_new.get_edge_from(interval, 'center')].extend(long_path_to_append)

    return TrainTrackMap(domain = tt_new,
                         codomain = tt_old,
                         vertex_map = vertex_map,
                         edge_map = edge_map,
                         coding_list = [transformation_coding])
 def test_lower_endpoint_3_8(self):
     i = Interval(3, 8)
     self.assertEqual(i.lower(), 3)
     self.assertEqual(i.upper(), 8)
 def test_contains_1(self):
     i = Interval(3, 8)
     self.assertFalse(i.contains(1))