def test_MergeOverlapping(self): int1 = interval('[1,5]') int2 = interval('[2,6)') int3 = interval('(8,10]') int4 = interval('[8,18]') intlist = [int1, int2, int3, int4] self.assertEqual(str(mergeOverlapping(intlist)),'[[1,6), [8,18]]')
def test_sqrt2(self): import math f, p = lambda x: x**2 - 2, lambda x: 2 * x u, v = 6369051672525772 * 2.0 ** -52, 6369051672525773 * 2.0 ** -52 s = interval[u, v] assert v == math.sqrt(2) assert s == interval[0.1, 5].newton(f, p) assert s == interval[0, 2].newton(f, p) assert s == interval[-1, 10].newton(f, p) assert interval() == interval[2, 5].newton(f, p) assert -s == interval[-5, 0].newton(f, p) assert -s | s == interval[-5, +5].newton(f, p) # Failure to converge in only three iterations: messages = [] assert interval() == interval[0, 2].newton( f, p, maxiter=3, tracer_cb = lambda tag, interval: messages.append((tag, interval))) assert messages == [ ('branch' , interval[0.0, 2.0]), ('step' , interval[1.25, 2.0]), ('step' , interval[1.36875, 1.46484375]), ('step' , interval[1.4141253188320488, 1.4143005729166669]), ('abandon', interval[1.4141253188320488, 1.4143005729166669]) ]
def main_function(): ListOfIntervals = list() while len(ListOfIntervals)==0: try: InputIntervals = raw_input("List of intervals?:") if InputIntervals == "quit": break temp = (re.compile('(\(|\[)(-?\d+),(-?\d+)(\)|\])')).findall(InputIntervals) InputIntervals = temp for i in temp: ListOfIntervals.append(interval.interval(i)) if len(ListOfIntervals)==0: print("Bad input. Please try again with the proper input format") except Exception as ErrorMessage: print ErrorMessage while True: NewInt = raw_input("another interval?") if InputIntervals == "quit" or "Quit": break try: ListOfIntervals = interval.interval.insert(ListofIntervals,interval.interval(NewInt)) print ListOfIntervals except Exception and ErrorMessage: print ErrorMessage
def test_mergeIntervals(self): self.assertEqual(str(interval.mergeIntervals("[1,5]", "[2,6)")), '[1, 6)') self.assertEqual(str(interval.mergeIntervals("(8,10]", "[8,18]")), '[8, 18]') self.assertEqual(str(interval.mergeIntervals("(0,3]", "[2,5)")), '(0, 5)') self.assertRaises(ValueError, interval.mergeIntervals, interval.interval('[1,2]'), interval.interval('[3,4)')) self.assertRaises(ValueError, interval.mergeIntervals, interval.interval('[1,2]'), interval.interval('(0,1)'))
def main(): interval_list = raw_input('List of intervals?') split_intlist=interval_list.split(", ") result = [interval(i) for i in split_intlist] try: split_intlist=interval_list.split(", ") result = [interval(i) for i in split_intlist] #list holds for the interval objects except ValueError: print('Invalid interval') except IndexError: print('Invalid interval') while True: input_str = raw_input('Interval?').lower() if input_str == 'quit': exit('End') try: newint = interval(input_str) result=insert(result,newint) str_re = [str(i) for i in result] join_str = ', '.join(str_re) print (join_str) except ValueError: print('Invalid interval')
def test_mergeIntervals_4(self): int1 = interval('[5,8)') int2 = interval('(8,10]') with self.assertRaises(ValueError) as cm: mergeIntervals(int1,int2) thisexception = cm.exception self.assertEquals(str(thisexception), "Invalid input: disjoint intervals")
def setUp(self): self.interval1 = interval('[1,2]') self.interval2 = interval('[3,4]') self.interval3 = interval('[1,4]') self.interval4 = interval('(5,10]') self.list = [self.interval1, self.interval2, self.interval4]
def testCalculateSlicesBeginningAndEnd(self): "one interval at the beginning and one at the end" secs = np.arange(10) inter = interval([0,3]) | interval([8,9]) slices = ObsFile.calculateSlices(inter, secs) new = ObsFile.repackArray(secs, slices) self.assertTrue(npEquals(new, np.array([4,5,6,7])))
def test_insert(self): int1 = interval('[2,6)') int2 = interval('(4,7]') int3 = interval('[9,12)') intervals = [int1,int2,int3] newint = interval('(11,16)') self.assertEqual(str(insert(intervals,newint)),"[[2,7], [9,16)]")
def add_conservation_features(self): ''' will go through the wiggle track and make features of type conservation for intronic regions where conservation is higher than it should be for introns and is at least 6 bp wide ''' tr = self.wigs['MamConserv'] feature_locs = [] idx = 0 for scores in score.sliding_window(self.wigs['MamConserv'], 6, step=1): loc = (idx, idx + 6) if sum(scores) / 6 > cfg.MAM_CONSERV_MIN_WINDOW_SCORE: feature_locs.append(loc) idx += 1 consol_flocs = interval.union([interval(*feature_locs)]) #remove exons and splice signals: consol_flocs = consol_flocs & \ interval(self.get_exon_and_signal_pos()).invert() for cfloc in consol_flocs: sta = int(cfloc[0]) end = int(cfloc[1]) if end - sta < 6: continue fscore = sum(tr[slice(sta, end)]) / (end - sta) self.features.append(make_seq_feature(sta, end, 'MamConserv', {'label' : ['MamConserv', ], 'evidence' : str(fscore)}))
def test_inverse(self): self.assertEqual(interval[0.5, 1], interval[1, 2].inverse()) self.assertEqual(interval[-1, -0.5],(-interval[1, 2]).inverse()) self.assertEqual(interval([-fpu.infinity, -1], [0.5, +fpu.infinity]), interval[-1,2].inverse()) self.assertEqual(interval(-fpu.infinity, [1, +fpu.infinity]), interval[0,1].inverse()) self.assertEqual(interval([-fpu.infinity, -2.0], [0.0, fpu.infinity]), interval([-0.5, 0.5], [0.2, fpu.infinity]).inverse())
def test_sqrt(self): f, p = lambda x: x**2 - 2, lambda x: 2 * x self.assertEqual(imath.sqrt(2), interval[1.4142135623730949, 1.4142135623730951]) self.assertEqual(imath.sqrt(4), interval[2]) self.assertEqual(imath.sqrt(interval[-3, -1]), interval()) self.assertEqual(imath.sqrt(interval[-1, 4]), interval([0.0, 2])) self.assertEqual(imath.sqrt(interval([-3.14, 2], [4,9], [25, 64])), interval([0, 1.4142135623730951], [2, 3], [5, 8]))
def test_mergeIntervals_4(self): a = interval.interval('[1,2)') b = interval.interval('(2,4]') with self.assertRaises(ValueError) as cm: interval.mergeIntervals(a,b) the_exception = cm.exception self.assertEquals(str(the_exception), 'Disjoint intervals!')
def main(): while True: try: list_of_intervals = input("List of intervals? ") if list_of_intervals == 'quit': print ('') sys.exit(1) list_of_intervals = interval.mergeOverlapping(list_of_intervals) break except KeyboardInterrupt: sys.exit(1) except Exception: print ('Invalid list of intervals') pass while True: try: interv = input('Interval? ') if interv == 'quit': print ('') break else: interval(interv) list_of_intervals = interval.insert(list_of_intervals, interv) print (list_of_intervals) except KeyboardInterrupt: sys.exit(1) except: print ('Invalid interval')
def test_insert2(self): ints = [interval(i) for i in ['(1,10)','[2,13)', '[3,5]', '[14,16]']] newint = interval('[17,18]') inserted = insert(ints, newint) self.assertEqual(len(inserted), 2) self.assertEqual(inserted[0].intervallist, [2,12]) self.assertEqual(inserted[1].intervallist, [14,18])
def test_isOverlapping(self): int1 = interval('[1,6)') int2 = interval('(4,7]') int3 = interval('[1,4)') int4 = interval('(4,7]') self.assertTrue(isOverlapping(int1, int2)) self.assertFalse(isOverlapping(int3, int4))
def test_sum(self): assert interval[-fpu.infinity, +fpu.infinity] == interval[-fpu.infinity] + interval[fpu.infinity] assert interval[4, 6] == interval[1, 2] + interval[3, 4] assert interval[3, fpu.infinity] == interval[1, fpu.infinity] + interval[2] assert interval[-fpu.infinity, +fpu.infinity] == interval[-fpu.infinity, -1] + interval[2, +fpu.infinity] assert interval[-fpu.infinity, +fpu.infinity] == interval[-fpu.infinity] + interval[8, +fpu.infinity] assert interval([1, 2], [10, fpu.infinity]) + interval([1, 9], [-2, -1]) == interval([-1, 1], [2, fpu.infinity]) assert interval[1, 9] + interval([1, 2], [10, fpu.infinity]) == interval[2, fpu.infinity]
def test_insert_3(self): a = ['[1,3]', '[6,9]'] lst = [] for item in a: lst.append(interval.interval(item)) b = interval.interval('[4,5]') c = interval.insert(lst, b) self.assertEqual(str(c), '[[1,9]]')
def test_insert_2(self): a = ['[1,2]', '(3,5)', '[6,7)', '(8,10]', '[12,16]'] lst = [] for item in a: lst.append(interval.interval(item)) b = interval.interval('[4,9]') c = interval.insert(lst, b) self.assertEqual(str(c), '[[1,2], (3,10], [12,16]]')
def test_insert_4(self): a = ['[1,2)', '(2,9]'] lst = [] for item in a: lst.append(interval.interval(item)) b = interval.interval('(3,10]') c = interval.insert(lst, b) self.assertEqual(str(c), '[[1,2), (2,10]]')
def test_dennis_schnabel(self): def f(x): return (((x - 12) * x + 47 ) * x - 60 )* x def p(x): return ((4 * x - 12*3) * x + 47*2) * x - 60 self.assertApproximate(interval[-100, 100].newton(f, p), interval(0, 3, 4, 5), 43) self.assertApproximate(interval[-100, 100].newton(lambda x: f(x) + 24, p), interval(0.888305779071752, 1), 59) self.assertApproximate(interval[-100, 100].newton(lambda x: f(x) + 24.1, p), interval(), 0)
def test_sum(self): self.assertEqual(interval[-fpu.infinity, +fpu.infinity], interval[-fpu.infinity] + interval[fpu.infinity]) self.assertEqual(interval[4, 6], interval[1, 2] + interval[3, 4]) self.assertEqual(interval[3, fpu.infinity], interval[1, fpu.infinity] + interval[2]) self.assertEqual(interval[-fpu.infinity, +fpu.infinity], interval[-fpu.infinity, -1] + interval[2, +fpu.infinity]) self.assertEqual(interval[-fpu.infinity, +fpu.infinity], interval[-fpu.infinity] + interval[8, +fpu.infinity]) self.assertEqual(interval([1, 2], [10, fpu.infinity]) + interval([1,9],[-2,-1]), interval([-1, 1], [2, fpu.infinity])) self.assertEqual(interval[1, 9] + interval([1, 2], [10, fpu.infinity]), interval[2, fpu.infinity])
def setUp(self): print 'Test whether two intervals can merge' #interval1 and interval2 can be merged, and interval3 and interval4 cannot be merged. self.interval1 = interval('(1,4)') self.interval2 = interval('[1,3]') self.interval3 = interval('(3,8)') self.interval4 = interval('(-3,2]') self.interval = None
def test_mergeIntervals(self): i = interval() int1 = interval('[',1,5,']') int2 = interval('[',2,6,']') int3 = interval('[',1,6,']') self.assertEqual(i.mergeIntervals(int1, int2).bra1, int3.bra1) self.assertEqual(i.mergeIntervals(int1, int2).bra2, int3.bra2) self.assertEqual(i.mergeIntervals(int1, int2).start, int3.start) self.assertEqual(i.mergeIntervals(int1, int2).end, int3.end)
def test_mergeIntervals(self): int1 = interval('[2,6)') int2 = interval('(4,7]') intm1 = mergeIntervals(int1,int2) int3 = interval('[5,11]') int4 = interval('[12,14]') intm2 = mergeIntervals(int3,int4) self.assertEqual(str(intm1), '[2,7]') self.assertEqual(str(intm2), '[5,14]')
def get_features(self, query, meta=False, aggregate=False, correct=None): ''' returns an iterator on features given a certain query, a meta feature, a sequence motif type object, or a type string. ''' #special cases for 'donor_intron' and 'acceptor_intron' if query == 'donor_intron': return ifilter(lambda f: len(self) in interval(f.extract_pos()), self.get_features('intron')) if query == 'acceptor_intron': return ifilter(lambda f: 0 in interval(f.extract_pos()), self.get_features('intron')) #if aggregate flag, then get all motif types that have that agg string if aggregate: query = ifilter(lambda m: 'aggregate' in m.attribs and \ m.attribs['aggregate'] == query, \ motif.motif_types.values()) #if correct flag, then get all motif types that have the 'correct splice # signal' string if correct is True: is_correct_fxn = \ lambda f: 'function' in f.qualifiers and \ 'correct splice signal' in f.qualifiers['function'] return ifilter(is_correct_fxn, \ self.get_features(query, \ meta=meta, \ aggregate=aggregate)) if correct is False: not_correct_fxn = \ lambda f: 'function' not in f.qualifiers or \ 'correct splice signal' not in f.qualifiers['function'] return ifilter(not_correct_fxn, \ self.get_features(query, \ meta=meta, \ aggregate=aggregate)) sametype = lambda f, q: (f.type == q) or ('seq_motif_type' in f.qualifiers \ and f.qualifiers['seq_motif_type'] == q) if not isinstance(query, str) and isinstance(query, collections.Iterable): recurse_this = lambda q: self.get_features(q, meta, aggregate, correct) iter = chain.from_iterable(map(recurse_this, query)) elif isinstance(query, str): iter = ifilter(lambda f: sametype(f, query), self.features) elif isinstance(query, motif.SeqMotifType): iter = ifilter(lambda f: sametype(f, query.type), self.features) elif isinstance(query, SeqFeature) and query.qualifiers['meta'] == True: iter = self._consolidated[f.qualifiers['seq_motif_type']][query] else: raise GetFeaturesQueryUnknownType return ifilter(lambda f: meta is f.is_meta(), iter)
def __init__(self, a = interval([0, 0]), b = interval([0, 0])): self.a = a self.b = b self.real_max = max(max(self.a)) self.real_min = min(min(self.a)) self.im_max = max(max(self.b)) self.im_min = min(min(self.b))
def test_width(self): assert helpers.ulpwidth(interval[3] ** -1) == [1] assert [1, 1, 1] == helpers.ulpwidth(interval( [9007199254740991 * 2.0 ** -51, 4503599627370496 * 2.0 ** -50], [9007199254740991 * 2.0 ** -49, 16], [-16, -9007199254740991 * 2.0 ** -49])) assert helpers.ulpwidth(interval([5249383869325653 * 2.0 ** -51, 5249383869325655 * 2.0 ** -51])) == [2] assert helpers.ulpwidth(interval[123.34]) == [0] assert helpers.ulpwidth(interval[fpu.infinity]) == [0] assert helpers.ulpwidth(interval[2, fpu.infinity]) == [fpu.infinity]
def test_width(self): self.assertEqual(helpers.ulpwidth(interval[3]**-1), [1]) self.assertEqual(helpers.ulpwidth(interval([9007199254740991 * 2.0 ** -51, 4503599627370496 * 2.0 ** -50], [9007199254740991 * 2.0 ** -49, 16], [-16, -9007199254740991 * 2.0 ** -49], )),[1, 1, 1]) self.assertEqual(helpers.ulpwidth(interval([5249383869325653 * 2.0 ** -51, 5249383869325655 * 2.0 ** -51])),[2]) self.assertEqual(helpers.ulpwidth(interval[123.34]), [0]) self.assertEqual(helpers.ulpwidth(interval[fpu.infinity]), [0]) self.assertEqual(helpers.ulpwidth(interval[2, fpu.infinity]), [fpu.infinity])
def invert(self): ''' separates all the components and takes the intersection of their individual inverses ''' ivls = [] inverse_func = lambda cmp: interval([-inf, cmp[0][0]], [cmp[0][1], inf]) inverses = map(inverse_func, self.components) return reduce(lambda x, y: x & y, inverses, interval((-inf, inf)))
def test_invalidInterval(self): invalidintervallist = ['(1,6]]', '((4,7)', 'foo', '{1,2]'] for invalidinterval in invalidintervallist: with self.assertRaises(IntervalInputException): self.interval = interval(invalidinterval)
def __bwd_propag(self, n_id, box): n = self.dag[n_id] fwd = self.__fwd bwd = self.__bwd rec = self.__bwd_propag if n[0] == '+': bwd[n[1]] = bwd[n_id] - fwd[n[2]] rec(n[1], box) bwd[n[2]] = bwd[n_id] - fwd[n[1]] rec(n[2], box) elif n[0] == '-': bwd[n[1]] = bwd[n_id] + fwd[n[2]] rec(n[1], box) bwd[n[2]] = fwd[n[1]] - bwd[n_id] rec(n[2], box) elif n[0] == '*': bwd[n[1]] = bwd[n_id] / fwd[n[2]] rec(n[1], box) bwd[n[2]] = bwd[n_id] / fwd[n[1]] rec(n[2], box) elif n[0] == '/': bwd[n[1]] = bwd[n_id] * fwd[n[2]] rec(n[1], box) bwd[n[2]] = fwd[n[1]] / bwd[n_id] rec(n[2], box) elif n[0] == '^': i = self.dag[n[2]][1] if i % 2 == 0: p = root(bwd[n_id], i) pp = p & fwd[n[1]] np = (-p) & fwd[n[1]] if is_empty(pp) or is_empty(np): bwd[n[1]] = interval() else: bwd[n[1]] = interval.hull([pp, np]) else: bwd[n[1]] = root(bwd[n_id], i) rec(n[1], box) elif n[0] == 'sqrt': if is_empty(bwd[n_id]) or bwd[n_id][0].sup < 0: bwd[n[1]] = interval() elif bwd[n_id][0].inf < 0: i = interval([0, bwd[n_id][0].sup]) bwd[n[1]] &= i * i else: bwd[n[1]] &= bwd[n_id] * bwd[n_id] assert (not is_empty(bwd[n[1]])) # TODO #elif n[0] == 'sin': elif n[0] == 'C': bwd[n_id] &= n[1] elif n[0] == 'V': box[n[1]] &= bwd[n_id] else: print('unsupported node: ' + str(n)) assert (False)
from interval import interval, inf, imath f = open("day_16.txt") #f = open("test.txt") departure = interval() non_departure = interval() my_ticket = "" overall_rules = interval() rows = {} while True: l = f.readline() if not l.rstrip(): break row = l.rstrip().split(':') intervals = row[1].split(' or ') rule_ivls = interval() for inter in intervals: interval_str = inter.split('-') rule_ivls = rule_ivls | interval[int(interval_str[0]), int(interval_str[1])] overall_rules = overall_rules | rule_ivls rows[row[0]] = rule_ivls print(overall_rules) rules_len = len(rows) while True: l = f.readline().rstrip() if not l:
def test_get_junctions(self): chrom = 'chr1' gtf_donors = {'chr1': {1, 2, 3}} gtf_acceptors = {'chr1': {1, 2, 3}} values = [ [interval([4300.0, 4349.0]), interval([4000.0, 4099.0])], # + chim [interval([4000.0, 4099.0]), interval([4300.0, 4349.0])], # - non-chim [interval([3050.0, 3149.0]), interval([4000.0, 4099.0])], # + non-chim [interval([4000.0, 4099.0]), interval([3050.0, 3149.0])], # - chim [ interval([74598831.0, 74598855.0]), interval([74601450.0, 74601467.0]), # + 1324 interval([74600055.0, 74600075.0]), interval([74603869.0, 74603880.0]) ], ] chains = [ '+', '-', '+', '-', '+', ] exp_lists = [ [{ 'n_junctions': 1, 'chrom': 'chr1', 'chain': '+', 'donor': str(4350), 'annot_donor': 0, 'acceptor': str(3999), 'annot_acceptor': 0, 'chimeric': True }], [{ 'n_junctions': 1, 'chrom': 'chr1', 'chain': '-', 'donor': str(4299), 'annot_donor': 0, 'acceptor': str(4100), 'annot_acceptor': 0, 'chimeric': False }], [{ 'n_junctions': 1, 'chrom': 'chr1', 'chain': '+', 'donor': str(3150), 'annot_donor': 0, 'acceptor': str(3999), 'annot_acceptor': 0, 'chimeric': False }], [{ 'n_junctions': 1, 'chrom': 'chr1', 'chain': '-', 'donor': str(3049), 'annot_donor': 0, 'acceptor': str(4100), 'annot_acceptor': 0, 'chimeric': True }], [ { 'n_junctions': 3, 'chrom': 'chr1', 'chain': '+', 'donor': str(74598856), 'annot_donor': 0, 'acceptor': str(74601449), 'annot_acceptor': 0, 'chimeric': False }, { 'n_junctions': 3, 'chrom': 'chr1', 'chain': '+', 'donor': str(74601468), 'annot_donor': 0, 'acceptor': str(74600054), 'annot_acceptor': 0, 'chimeric': True }, { 'n_junctions': 3, 'chrom': 'chr1', 'chain': '+', 'donor': str(74600076), 'annot_donor': 0, 'acceptor': str(74603868), 'annot_acceptor': 0, 'chimeric': False }, ], ] for i, value in enumerate(values): res_list = ptes.get_junctions(chrom, chains[i], value, gtf_donors, gtf_acceptors) self.assertListEqual(exp_lists[i], res_list)
def get_sin_cos_table(max_theta, min_theta, max_theta_dot, min_theta_dot, action): assert min_theta <= max_theta, f"min_theta = {min_theta},max_theta={max_theta}" assert min_theta_dot <= max_theta_dot, f"min_theta_dot = {min_theta_dot},max_theta_dot={max_theta_dot}" step_theta = 0.1 step_theta_dot = 0.1 # min_theta = max(min_theta, -math.pi / 2) # max_theta = min(max_theta, math.pi / 2) split_theta1 = np.arange(min(min_theta, 0), min(max_theta, 0), step_theta) split_theta2 = np.arange(max(min_theta, 0), max(max_theta, 0), step_theta) split_theta = np.concatenate([split_theta1, split_theta2]) split_theta_dot1 = np.arange(min(min_theta_dot, 0), min(max_theta_dot, 0), step_theta) split_theta_dot2 = np.arange(max(min_theta_dot, 0), max(max_theta_dot, 0), step_theta) split_theta_dot = np.concatenate([split_theta_dot1, split_theta_dot2]) if len(split_theta_dot) == 0: split_theta_dot = np.array([max_theta_dot]) if len(split_theta) == 0: split_theta = np.array([max_theta]) env = MonitoredPendulum(None) force = 0 if action == 1: force = -env.max_torque elif action == 2: force = env.max_torque else: force = 0 split = [] for t_dot in split_theta_dot: for theta in split_theta: lb_theta_dot = t_dot ub_theta_dot = min(t_dot + step_theta_dot, max_theta_dot) lb = theta ub = min(theta + step_theta, max_theta) split.append((interval([lb_theta_dot, ub_theta_dot]), interval([lb, ub]))) sin_cos_table = [] while (len(split)): theta_dot, theta = split.pop() # dynamics newthdot = theta_dot + (-3 * env.g / (2 * env.l) * imath.sin(theta + np.pi) + 3. / (env.m * env.l**2) * force) * env.dt newth = theta + newthdot * env.dt newthdot = interval([ np.clip(newthdot[0].inf, -env.max_speed, env.max_speed), np.clip(newthdot[0].sup, -env.max_speed, env.max_speed) ]) if newth[0].sup > np.pi: if newth[0].inf >= np.pi: # both over the limit, just make a single interval sin_cos_table.append( (theta, theta_dot, PendulumExperiment.interval_normalise_theta_interval( newth), interval(newthdot))) else: # only the upper bound is over the limit, make 2 intervals newth2 = interval([newth[0].inf, np.pi]) sin_cos_table.append( (theta, theta_dot, newth2, interval(newthdot))) normalised2 = PendulumExperiment.normalise_theta_value( newth[0].sup) newth3 = interval([-np.pi, normalised2]) sin_cos_table.append( (theta, theta_dot, newth3, interval(newthdot))) continue elif newth[0].inf < -np.pi: if newth[0].sup <= -np.pi: # both over the limit, just make a single interval sin_cos_table.append( (theta, theta_dot, PendulumExperiment.interval_normalise_theta_interval( newth), interval(newthdot))) else: # only the lower bound is over the limit, make 2 intervals normalise_theta2 = PendulumExperiment.normalise_theta_value( newth[0].inf) newth2 = interval([np.pi, normalise_theta2]) sin_cos_table.append( (theta, theta_dot, newth2, interval(newthdot))) newth3 = interval([-np.pi, newth[0].sup]) sin_cos_table.append( (theta, theta_dot, newth3, interval(newthdot))) continue else: sin_cos_table.append( (theta, theta_dot, newth, interval(newthdot))) return sin_cos_table
def test_format(self): for x in interval[1], interval[1, 2], interval([1, 2], [3, 4]), interval[2, 2.0000000000000004]: assert x == eval(repr(x)) x = interval([1, 2]) assert str(x) == repr(x)
def test_inverse(self): assert interval[0.5, 1] == interval[1, 2].inverse() assert interval[-1, -0.5] == (-interval[1, 2]).inverse() assert interval([-fpu.infinity, -1], [0.5, +fpu.infinity]) == interval[-1, 2].inverse() assert interval(-fpu.infinity, [1, +fpu.infinity]) == interval[0, 1].inverse() assert interval([-fpu.infinity, -2.0], [0.0, fpu.infinity]) == interval([-0.5, 0.5], [0.2, fpu.infinity]).inverse()
def test_count_relative_position(self): interval_lists = [ [interval([-10, 10]), interval([1.0, 100.0])], [interval([-10, 1]), interval([1.0, 100.0])], [interval([10, 20]), interval([1.0, 100.0])], [interval([90, 99]), interval([1.0, 100.0])], [interval([90, 100]), interval([1.0, 100.0])], [interval([20, 10]), interval([1.0, 100.0])], [interval([90, 199]), interval([1.0, 100.0])], [interval([200, 1000]), interval([1.0, 100.0])], [interval([150, 200]), interval([1.0, 100.0])], ] for i, tuple in enumerate(interval_lists): res_int = ptes.count_relative_position(feature=tuple[0], container=tuple[1]) print res_int
def test_get_read_interval(self): cigars = [ '20M30S', '30S20M', '30S20M30S', '20M2I20M', '20M2D20M', '20M32N20M', '20S20M32N20M', '20S20M32N20M1000p76M', ] leftpos = 100 exp_read_dicts = [ OrderedDict([ ('M1', interval([100.0, 119.0])), ]), OrderedDict([ ('M1', interval([100.0, 119.0])), ]), OrderedDict([ ('M1', interval([100.0, 119.0])), ]), OrderedDict([('M1', interval([100.0, 119.0])), ('M2', interval([120.0, 139.0]))]), OrderedDict([('M1', interval([100.0, 119.0])), ('D1', interval([120.0, 121.0])), ('M2', interval([122.0, 141.0]))]), OrderedDict([('M1', interval([100.0, 119.0])), ('N1', interval([120.0, 151.0])), ('M2', interval([152.0, 171.0]))]), OrderedDict([('M1', interval([100.0, 119.0])), ('N1', interval([120.0, 151.0])), ('M2', interval([152.0, 171.0]))]), OrderedDict([('M1', interval([100.0, 119.0])), ('N1', interval([120.0, 151.0])), ('M2', interval([152.0, 171.0])), ('p1', interval([172.0, 1171.0])), ('M3', interval([1172.0, 1247.0]))]), ] res_read_dicts = [ ptes.get_read_interval(cigar=cigar, leftpos=leftpos, output='dict') for cigar in cigars ] for i in range(len(exp_read_dicts)): self.assertEqual(exp_read_dicts[i], res_read_dicts[i])
def test_split_by_p(self): read_dicts = [ OrderedDict([('M1', interval([100.0, 119.0])), ('N1', interval([120.0, 151.0])), ('M2', interval([152.0, 171.0])), ('p1', interval([172.0, 1171.0])), ('M3', interval([1172.0, 1247.0]))]), ] results = [ ptes.split_by_p(read_dict=read_dict) for read_dict in self.input_read_dicts ] exp_results = [ [ OrderedDict([('M1', interval([100.0, 119.0])), ('N1', interval([120.0, 151.0])), ('M2', interval([152.0, 171.0]))]), OrderedDict([('M3', interval([1172.0, 1247.0]))]) ], [ OrderedDict([('M1', interval([100.0, 119.0])), ('N1', interval([120.0, 151.0])), ('M2', interval([152.0, 171.0]))]), OrderedDict([('M3', interval([1248.0, 1260.0]))]) ], [ OrderedDict([('M1', interval([100.0, 119.0])), ('N1', interval([120.0, 151.0])), ('M2', interval([152.0, 171.0]))]), OrderedDict([('M3', interval([1248.0, 1260.0]))]) ], ] for i in range(len(read_dicts)): self.assertEqual(exp_results[i], results[i])
def test_insert(self): ints = [interval(i) for i in ['(1,10)', '[2,13)', '[3,5]', '[14,16]']] newint = interval('[13,14]') self.assertEqual(insert(ints, newint)[0].intervallist, [2, 16])
def test_mergeOverlapping2(self): ints = [interval(i) for i in ['(1,10)', '[2,13)', '[3,5]', '[14,16]']] a = mergeOverlapping(ints) self.assertEqual(len(a), 2) self.assertEqual(a[0].intervallist, [2, 12]) self.assertEqual(a[1].intervallist, [14, 16])
def test_nan_constructor(self): assert interval[2, fpu.nan] == ((-fpu.infinity, fpu.infinity),) assert interval[2, fpu.nan] == ((-fpu.infinity, fpu.infinity),) assert interval(2, fpu.nan, 9) == ((-fpu.infinity, fpu.infinity),)
def test_union(self): assert interval([1, 6], 9) == interval([1, 3], [4, 6]) | interval([2, 5], 9) assert interval[1, 2] | 2.1 == interval([1, 2], 2.1) assert 2.1 | interval[1, 2] == interval([1, 2], 2.1) self.assertRaises(TypeError, lambda: interval[1, 2] | 1j)
def interval_normalise_theta_interval(theta): result = interval([ PendulumExperiment.normalise_theta_value(theta[0].inf), PendulumExperiment.normalise_theta_value(theta[0].sup) ]) return result
def test_abs(self): assert interval([0, 3]) == abs(interval[-3, 2]) assert interval([1, 6], 9) == abs(interval([-9], [-5, -2], [1, 3], [4, 6])) assert interval([1, 6], 9) == abs(interval([9], [2, 5], [-3, -1], [-6, -4]))
def test_hull(self): assert interval([1, 9]) == interval.hull((interval([1, 3], [4, 6]), interval([2, 5], 9)))
def verify_in(x, y): assert x in y assert x & y == interval(x)
def filter_short_intvls(intvls, min_len): """Filter out intervals in <intvls> shorter than <min_len>. <intvls> must consist of INTEGER intervals with inclusive boundaries. """ return interval(*[i for i in intvls if intvl_len(i) >= min_len])
def test_extrema(self): assert interval(1, [2, 3], 4).extrema == interval(1, 2, 3, 4)
print('trying case 1|567 ...') ctr = 0 while not case_queue.empty() and curr_depth < MAX_DEPTH: (M,Mdenom, N,Ndenom, A1,A1denom, A6,A6denom, depth) = case_queue.get() if depth != curr_depth: curr_depth = depth curr_size = next_size ctr += curr_size next_size = 0 print('\ton depth =', curr_depth, '...', 'size =', curr_size, '...', 'so far', ctr, '...') mu = interval[M, M+1] / interval(Mdenom) nu = interval[N, N+1] / interval(Ndenom) a1 = interval[A1, A1+1] / interval(A1denom) a6 = interval[A6, A6+1] / interval(A6denom) if is_feasible(mu, nu, a1, a6): next_size += 2 if depth % 4 == 0: case_queue.put( (M,Mdenom, N,Ndenom, 2*A1, 2*A1denom, A6, A6denom, depth+1) ) case_queue.put( (M,Mdenom, N,Ndenom, 2*A1+1, 2*A1denom, A6, A6denom, depth+1) ) if depth % 4 == 1: case_queue.put( (M,Mdenom, N,Ndenom, A1, A1denom, 2*A6, 2*A6denom, depth+1) ) case_queue.put( (M,Mdenom, N,Ndenom, A1, A1denom, 2*A6+1, 2*A6denom, depth+1) )
def test_midpoint(self): assert interval[0, 4].midpoint == interval[2] assert interval(-1, 1, 4) == interval(-1, [0, 2], [3, 5]).midpoint
time = time.rename("t") size = (len(time), len(S)) columns = np.arange(0, len(S)) s_values = pd.DataFrame(np.zeros(size), index=time, columns=columns) s_epsilon = pd.DataFrame(np.zeros(size), index=time, columns=columns) s_error = pd.DataFrame(np.zeros(size), index=time, columns=columns) print("\n\nMonitor ...") window = deque(maxlen=5) for index, row in data.iterrows(): timestamp = row['t_clock'] # move values (as intervals) from row to itoms for name in itoms.keys(): v = row[name] e = epsilon[name] itoms[name].v = interval([v - e, v + e]) itoms[name].t = timestamp # transform outputs = bring_to_common_domain(S, itoms) # intervals to compare values = [output.v for output in outputs.values()] # each value is only a single interval (otherwise take the hull first) for v in values: assert len(v) == 1 # log s_epsilon.at[timestamp, :] = [(v[0][1] - v[0][0]) / 2 for v in values] s_values.at[timestamp, :] = [v.midpoint[0][0] for v in values] # compare error = faulty(values) if args.median: window.append(error)
def test_opts(self): self.assertRaises(TypeError, lambda: interval(0, 1).newton(None, None, nonexisting=True))
def test_sort_by_xq(self): interval_lists = [ [(0, interval([4300.0, 4349.0])), (1, interval([4000.0, 4099.0]))], # + chim [(0, interval([4300.0, 4349.0])), (1, interval([4000.0, 4099.0]))], # - non-chim [(0, interval([3050.0, 3149.0])), (1, interval([4000.0, 4099.0]))], # + non-chim [(0, interval([3050.0, 3149.0])), (1, interval([4000.0, 4099.0]))], # - chim ] chains = [ '+', '-', '+', '-', ] exp_lists = [ [interval([4300.0, 4349.0]), interval([4000.0, 4099.0])], [interval([4000.0, 4099.0]), interval([4300.0, 4349.0])], [interval([3050.0, 3149.0]), interval([4000.0, 4099.0])], [interval([4000.0, 4099.0]), interval([3050.0, 3149.0])], ] for i, tuple in enumerate(interval_lists): res_list = ptes.sort_by_xq(tuple, chains[i]) self.assertEqual(exp_lists[i], res_list)
def test_cubic(self): assert interval[-2, 2].newton(lambda x: x ** 3 - x, lambda x: 3 * x ** 2 - 1) == interval(-1, 0, 1) assert interval[-5, 5].newton(lambda x: x ** 3 + x - 10, lambda x: 3 * x ** 2 + 1) == interval[2] assert interval[-5, 5].newton(lambda x: x ** 3 + x - 15, lambda x: 3 * x ** 2 + 1) == interval[5249383869325653 * 2.0 ** -51, 5249383869325655 * 2.0 ** -51]
def get_intrinsic_frames(self): int_steps = self.env.intrinsic_timesteps one_min_frames = 60 * self.video_fps * self.frame_freq return interval([0, one_min_frames], [int_steps / 2, int_steps / 2 + one_min_frames], [int_steps - one_min_frames, int_steps])
def modify_parser(subparsers): import argparse from interval import interval subparser = subparsers.add_parser('simple') subparser_preprocess = subparser.add_argument_group( 'data preprocessing options') subparser_preprocess.add_argument('--unit_norm', action='store_true') subparser_preprocess.add_argument('--triangle', type=interval(int), default=0) subparser_preprocess.add_argument('--label_corruption', type=interval(int), default=0) subparser_preprocess.add_argument('--label_corruption_valid', type=interval(int), default=0) subparser_preprocess.add_argument('--label_unshifted_percentile', type=interval(float), default=100.0) subparser_preprocess.add_argument('--gaussian_X', type=interval(int), default=0) subparser_preprocess.add_argument('--zero_Y', type=interval(int), default=0) subparser_preprocess.add_argument('--huge_Y', type=interval(int), default=0) subparser_preprocess.add_argument('--huge_X', type=interval(int), default=0) subparser_preprocess.add_argument('--tiny_X', type=interval(int), default=0) subparser_preprocess.add_argument('--ones', type=interval(int), default=0) subparser_preprocess.add_argument('--max_Y', type=interval(int), default=0) subparser_preprocess.add_argument('--pad_dim', type=interval(int), default=0) subparser_preprocess.add_argument('--pad_dim_numbad', type=interval(int), default=0) subparser_preprocess.add_argument('--parallel', type=int, default=10) subparser_preprocess.add_argument('--prefetch', type=int, default=1000)
def test_interval(self): self.assertEqual(interval('(1,10)').intervallist, [2, 9]) self.assertEqual(interval('[7,20]').intervallist, [7, 20]) self.assertEqual(interval('(-1,4)').intervallist, [0, 3]) self.assertRaises(ValueError, interval, '(0,-10)') #Exception test
def test_failing_constructor(self): self.assertRaises(interval.ComponentError, lambda: interval[1, [2, 3]]) self.assertRaises(interval.ComponentError, lambda: interval[1, 2, 3]) self.assertRaises(interval.ComponentError, lambda: interval(0, [1, 2, 3])) self.assertRaises(interval.ComponentError, lambda: interval(0, [1, [2, 3]])) self.assertRaises(interval.ComponentError, lambda: interval['a', 1])