def loadTrafficNodes(fileName): reader = csv.reader(open(fileName)) trafficNodes = [] for row in reader: if (row[0] == "ongeval" or row[0] == 'blokkade') and row[14] == "TRUE" and row[40] != '': # Important indexes: # situationRecordType 1 # situationId 6 # validityOverallStartTime 11 # validityOverallEndTime 13 # lat lon 40 # alertCLocationName 41 # Insert above values into TrafficNode Object # Split the latitude and longitude into two separate variables if '|' in row[40]: loc = row[40].split('|')[0].split(' ') else: loc = row[40].split(' ') # Split date and time into two separate variables start = row[11].split(' ') end = row[13].split(' ') # Add a TrafficNode to the list of trafficNodes trafficNodes.append( TrafficNode(row[6], row[1], Interval(start[0], start[1], end[0], end[1]), Location(loc[1], loc[0]), row[41])) return trafficNodes
def setIndepdomain(self, indepdomain): if isinstance(indepdomain, str): self.indepvarname = indepdomain if self.indepdomain is not None: # If indepdomain already set and indepvarname is none then # name won't get put in place unless we force it here self.indepvarname = indepdomain self.indepdomain.name = indepdomain else: self.indepdomain = Interval(self.indepvarname, 'float', [-Inf, Inf]) self.indepvartype = Float else: if isinstance(indepdomain, Interval): if self.trajirange: if indepdomain.contains(self.trajirange) is notcontained: raise ValueError, ( "Cannot set independent variable" " domain inside current trajectory's" " range") self.indepdomain = indepdomain self.indepvarname = indepdomain.name self.indepvartype = _pynametype[indepdomain.typestr] elif isinstance(indepdomain, dict): assert len( indepdomain) == 1, "Dictionary must have only 1 entry" d = indepdomain.values()[0] assert all(isfinite(d)), "Values must be finite" assert isincreasing(d), "Values must be increasing" if self.trajirange: assert self.trajirange.get(0) in d assert self.trajirange.get(1) in d self.indepvarname = indepdomain.keys()[0] if isinstance(d, list): self.indepdomain = array(d) elif isinstance(d, Array) or isinstance(d, NArray): self.indepdomain = d else: raise TypeError, ("Invalid type for independent " "variable domain") self.indepvartype = self.indepdomain.type() else: print "Independent variable argument domain was:", indepdomain raise TypeError, ("Invalid type for independent variable " "domain")
def test_diminished_increasing(note, second, dimished_second, dimished_number, _a, _b): inter = Interval.Interval(note, second) if note == second: return dimished = inter.get_diminished_interval() assert dimished.secondNote == dimished_second assert dimished.get_interval_number() == dimished_number
def test_augmented_increasing(note, second, _a, _b, augmented_second, augmented_number): inter = Interval.Interval(note, second) if inter.secondNote == 'B': return augmented = inter.get_augmented_interval() assert augmented.secondNote == augmented_second assert augmented.get_interval_number() == augmented_number
def __init__(self, fn, datapoints=None, numtypes=(Float, Float)): assert isinstance(fn, types.FunctionType) or \ isinstance(fn, types.BuiltinFunctionType), \ ("fn argument must be a regular Python function") self.fn = fn # datapoints can be exhaustive list of known values for fn or # a Interval range for continuous-valued functions if datapoints is None: datapoints = (Interval('indepvardom', _pynametype[numtypes[0]], [-Inf, Inf]), Interval('depvardom', _pynametype[numtypes[1]], [-Inf, Inf])) try: self.datapoints = (datapoints[0], datapoints[1]) except TypeError: raise TypeError, ("datapoints argument must be a 2-tuple or list " "of 2-tuples or lists") try: self.types = (numtypes[0], numtypes[1]) except TypeError: raise TypeError, ("numtypes argument must be a 2-tuple or list " "of 2-tuples or lists")
def create_intervals(components: List[str], separated=True) -> List[Interval]: """Given valid components list, create Intervals from pairwise components. :param components: comma-separated user-input list of Interval objects :param separated: boolean denoting whether our components are split or self-contained. Allows for re-use of method when testing numerous intervals :return intervals: list of Interval objects made from components """ if separated: # Zip the even and odd elements of our components list, ensuring # each item is a potential Interval object. zipped_components = zip(components[::2], components[1::2]) # Join each pair by a comma. :joined should now contain eligible intervals. components = [', '.join(pair) for pair in zipped_components] # Initialize container for valid intervals. intervals = [] for candidate in components: try: # Attempt to create an Interval object using our string representation. # If we succeed, append that interval to our container. interval = Interval(candidate) intervals.append(interval) # If we do not succeed: locate the exception, print this information to # the user, and continue. except ParsingException as p: print(str(p), file=sys.stderr) except RangeMismatchException as rm: print(str(rm), file=sys.stderr) except RangeException as r: print(str(r), file=sys.stderr) except EOFError: print("End-of-file error. Exiting...") break except (KeyboardInterrupt, SystemExit): break # Return elements from components that were successfully made into # Interval objects. return intervals
def __common_answer(self): self.window[str(self.current)].update(self.correct) self.current += 1 try: self.correct = next(self.scale_generator) except StopIteration: self.window['LeftAnswer'].update("_", disabled=True) self.window['RightAnswer'].update("_", disabled=True) return close_notes = [ Interval.get_sharp(self.correct), Interval.get_bemol(self.correct) ] incorrect = random.choice(close_notes) options = [self.correct, incorrect] random.shuffle(options) self.correct_button = 'LeftAnswer' if options[ 0] == self.correct else 'RightAnswer' self.window['LeftAnswer'].update(options[0]) self.window['RightAnswer'].update(options[1])
def main(): files = natsorted(populateFiles()) font = pygame.font.SysFont("genevattf", 100) # display = pygame.display.set_mode( # (500, 500)) text = font.render("Ear Trainer", 1, (0, 0, 0)) II = b.button((0, 162, 199), 200, 200, 150, 40, "Interval Identifier") MM = b.button((0, 162, 199), 200, 300, 150, 40, "Melody Matcher") # main loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.QUIT exit() running = False if event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() if II.isOver(pos): Interval.run(files, display) if MM.isOver(pos): Melody.run(files, display) display.fill((255, 255, 255)) text = font.render("Ear Trainer", 1, (0, 0, 0)) display.blit(text, (80, 30)) II.draw(display) MM.draw(display) pygame.display.update()
def interactive_input(intervals: List[Interval]): """Read-eval-response loop for interactive insertion into :intervals. :param intervals: list of Interval objects to be inserted into :return: never-ending; if user enters a common 'quit' symbol they will exit """ # While our user has not asked to exit, keep receiving input. response = input('Interval: ').lower() while response not in ['q', 'quit', 'exit']: try: # Attempt to coerce this new input as an Interval object. # If we succeed, insert into the current list of Intervals # and print the new, sorted, merged list of Intervals including # the original input. Print the new intervals list, as well. interval = Interval(response) intervals = insert_into(intervals, interval) print(', '.join([str(interval) for interval in intervals])) # If we cannot create an Interval object or insert the response # into :interval, locate the exception, tell the user what happened, # and continue. except ParsingException as p: print(str(p), file=sys.stderr) except RangeMismatchException as rm: print(str(rm), file=sys.stderr) except RangeException as r: print(str(r), file=sys.stderr) except EOFError: print("End-of-file error. Exiting...") break except (KeyboardInterrupt, SystemExit): print("Exiting...") break # Once we've reasonably handled exceptions, prompt the user # for their next requested interval of insertion. response = input('Interval: ')
def setIndepdomain(self, indepdomain): if isinstance(indepdomain, str): self.indepvarname = indepdomain if self.indepdomain is not None: # If indepdomain already set and indepvarname is none then # name won't get put in place unless we force it here self.indepvarname = indepdomain self.indepdomain.name = indepdomain else: self.indepdomain = Interval(self.indepvarname, 'float', [-Inf, Inf]) self.indepvartype = Float else: if isinstance(indepdomain, Interval): if self.trajirange: if indepdomain.contains(self.trajirange) is notcontained: raise ValueError, ("Cannot set independent variable" " domain inside current trajectory's" " range") self.indepdomain = indepdomain self.indepvarname = indepdomain.name self.indepvartype = _pynametype[indepdomain.typestr] elif isinstance(indepdomain, dict): assert len(indepdomain) == 1, "Dictionary must have only 1 entry" d = indepdomain.values()[0] assert all(isfinite(d)), "Values must be finite" assert isincreasing(d), "Values must be increasing" if self.trajirange: assert self.trajirange.get(0) in d assert self.trajirange.get(1) in d self.indepvarname = indepdomain.keys()[0] if isinstance(d, list): self.indepdomain = array(d) elif isinstance(d, Array) or isinstance(d, NArray): self.indepdomain = d else: raise TypeError, ("Invalid type for independent " "variable domain") self.indepvartype = self.indepdomain.type() else: print "Independent variable argument domain was:", indepdomain raise TypeError, ("Invalid type for independent variable " "domain")
def intervalIntersection2(self, A, B): """ :type A: list[Interval] :type B: list[Interval] :rtype: list[Interval] """ res, j = [], 0 for a in A: # skip those ahead of interval a while j < len(B) and B[j].end < a.start: j += 1 # get intersections k = j while k < len(B) and B[k].start <= a.end: res.append( Interval(max(a.start, B[k].start), min(a.end, B[k].end))) k += 1 return res
def intervalIntersection(self, A, B): ans = [] i = j = 0 while i < len(A) and j < len(B): # Let's check if A[i] intersects B[j]. # lo - the startpoint of the intersection # hi - the endpoint of the intersection lo = max(A[i].start, B[j].start) hi = min(A[i].end, B[j].end) if lo <= hi: ans.append(Interval(lo, hi)) # Remove the interval with the smallest endpoint if A[i].end < B[j].end: i += 1 else: j += 1 return ans
def getTlengthIntervals(self,content): numbers=content.split(" ")#[:-1] #print len(numbers) intervalList=[] multiple=1 #print "getTlengthIntervals: ", self.markFlowLength,self.intervalLength for i in range(0, self.markFlowLength*multiple): intervalList.append(Interval.Interval()) upperBound=self.intervalLength i=0 condition=True count=0 while i< len(numbers): #print(count) if upperBound==self.intervalLength+self.markFlowLength*multiple*self.intervalLength: break if numbers[i]=='' or numbers[i]=='\n':# this means we are in the end of our file break if float(numbers[i])<upperBound: intervalList[count].append(float(numbers[i]))#????/// i+=1 else: upperBound+=self.intervalLength count+=1 #self.fingerPrintLoc=self.getFingerPrintLocations(self.baseIntervals) al=0 for i in range(0,len(intervalList)): #print intervalList[i].getlen(),"k" al+=intervalList[i].getlen() #print al,"gallllllllllllllllllllllllllll" return intervalList
class Modelo_Estructurado(): def __init__(self, fichero): self.__interval = Interval(fichero) def Get_res_number(self): return self.__interval.Get_res_number() def All_data_stored(self): return self.__interval.All_data_stored() def Bit_padding(self): self.__interval.Bit_padding() def run(self, elem): Level_id = 0 while (not self.__interval.Is_in_Level(Level_id, elem)): self.__interval.Emit(ESC, Level_id) Level_id += 1 self.__interval.Emit(elem, Level_id)
def setOutput(self, outputdata, funcspec=None, globalt0=0, var_namemap=None, ics=None, refvars=None): """Dynamically create 'output' method of Variable""" self.globalt0 = globalt0 if type(outputdata) in [types.FunctionType, types.BuiltinFunctionType, types.MethodType]: # Variable generated from function, given in closed form self.output = outputdata assert ics is None, "Invalid option for this type of output" if outputdata != noneFn: self.defined = True elif isinstance(outputdata, tuple): # For ExplicitFnGen or ImplicitFnGen types, whose functional forms # may need to access these at call time. assert len(outputdata) == 2, "Incorrect size of outputdata tuple" if funcspec is not None: self.addMethods(funcspec) self._var_namemap = var_namemap self._funcreg['funcspec'] = (None, funcspec) else: raise ValueError, 'funcspec missing in setOutput' # Add the specific mapping functions for Ex/ImplicitFnGen objects try: exec outputdata[1] in globals() except: print 'Internal Error in _mapspecfn code' raise has_op = hasattr(self, 'output') # have to define this function in here because use of lambda # won't allow me to pickle the Variable object if not has_op or (has_op and self.output is noneFn): def wrap_output(arg): return eval(outputdata[0])(self, arg) setattr(self, 'output', wrap_output) self._funcreg['outputdata'] = (None, outputdata) t0 = self.indepdomain.get(0) if ics is None and not isinstance(funcspec, ImpFuncSpec): try: self.initialconditions = {self.coordname: self.output(t0)} except ValueError: self.initialconditions = {self.coordname: NaN} except TypeError: print "Debugging info: self.output = ", self.output raise else: self.initialconditions = ics self._vectorizable = False self._refvars = refvars self.defined = True elif type(outputdata) in [types.InstanceType, types.TypeType, \ OutputFn] or isinstance(outputdata, interpclass): # Variable generated by callable object that generates values over # mesh points that it holds, e.g. by interpolation # (InstanceType and TypeType are for backwards compatibility, e.g. # for old SciPy interpolate code that uses Classic Classes) assert ics is None, "Invalid option for this type of output" assert '__call__' in dir(outputdata), "Must provide callable object" self.output = outputdata if hasattr(outputdata, 'datapoints'): if hasattr(outputdata, 'types'): deptypestr = _pytypename[outputdata.types[0]] indeptypestr = _pytypename[outputdata.types[1]] else: # default deptypestr = indeptypestr = 'float' if isinstance(outputdata.datapoints[0], Interval): assert outputdata.types[0] == \ outputdata.datapoints[0].type, \ "Inconsistent type with Interval bounds" self.trajirange = outputdata.datapoints[0] else: self.trajirange = Interval('traj_indep_bd', indeptypestr, extent(outputdata.datapoints[0])) if isinstance(outputdata.datapoints[1], Interval): assert outputdata.types[1] == \ outputdata.datapoints[1].type, \ "Inconsistent type with Interval bounds" self.trajdrange = outputdata.datapoints[1] else: self.trajdrange = Interval('traj_dep_bd', deptypestr, extent(outputdata.datapoints[1])) self.defined = True elif isinstance(outputdata, Pointset): # Variable generated from a pointset (without interpolation) assert ics is None, "Invalid option for this type of output" assert isparameterized(outputdata), ("Must only pass parameterized" " pointsets") if outputdata.dimension == 1: self.coordname = copy.copy(outputdata.coordnames[0]) self.indepvarname = outputdata.indepvarname self.output = Varcaller(outputdata) self.coordtype = outputdata.coordtype self.indepvartype = outputdata.indepvartype if self.indepdomain is not None: for v in outputdata[self.indepvarname]: if not v in self.indepdomain: raise ValueError, ("New Pointset data violates " "independent variable domain already specified") if self.depdomain is not None: for v in outputdata[self.coordname]: if not v in self.depdomain: raise ValueError, ("New Pointset data violates " "dependent variable domain already specified") self.trajirange = Interval('traj_indep_bd', _pytypename[self.indepvartype], extent(outputdata.indepvararray)) self.trajdrange = Interval('traj_dep_bd', _pytypename[self.coordtype], extent(outputdata[self.coordname])) self.defined = True else: raise ValueError, \ "Pointset data must be 1D to create a Variable" elif outputdata is None: # placeholder for an unknown output type assert ics is None, "Invalid option when outputdata argument is None" self.output = noneFn self.defined = False else: raise TypeError, ("Invalid type for data argument: " \ +str(type(outputdata)))
def test_augmented_out_of_actave_should_raise_error(): with pytest.raises(ValueError): interval = Interval.Interval('C', 'B') interval.get_augmented_interval()
def test_diminished_unison_should_raise_error(): with pytest.raises(ValueError): unison = Interval.Interval('C', 'C') unison.get_diminished_interval()
def test_distance_increasing(second, distance): root = 'B' unison = Interval.Interval(root, second) assert unison.get_interval_number() == distance
def test_sharp(note, bemol): assert Interval.get_sharp(bemol) == note
def __init__(self, fichero): self.__interval = Interval(fichero)
def setDepdomain(self, depdomain): if isinstance(depdomain, str): self.coordname = depdomain if self.depdomain is None: if self.coordtype is None: self.depdomain = Interval(self.coordname, 'float', [-Inf, Inf]) self.coordtype = Float else: self.depdomain = Interval(self.coordname, _pytypename[self.coordtype], _nummaxmin[self.coordtype]) else: # If interp functions supplied then don't have a name for # Interval yet, so update it. if isinstance(self.output, interpclass) and \ isinstance(self.depdomain, Interval): self.depdomain.name = depdomain else: assert isinstance(self.output, Pointset) print "Warning: Dependent variable already named. " + \ "Ignoring user-supplied name." else: if isinstance(depdomain, Interval): if self.trajdrange: if depdomain.contains(self.trajdrange) is notcontained: raise ValueError, ("Cannot set dependent variable " "domain inside current trajectory's " "range") self.depdomain = depdomain self.coordname = depdomain.name if self.coordtype is None: self.coordtype = depdomain.type elif self.coordtype == depdomain.type: pass else: raise TypeError, ("Mismatch between type of depdomain " "argument and Pointset coord data") elif isinstance(depdomain, dict): assert len(depdomain) == 1, "Dictionary must have only 1 entry" d = depdomain.values()[0] if self.trajdrange: assert self.trajdrange.get(0) in d assert self.trajdrange.get(1) in d ## if not isincreasing(d): ## d.sort() assert all(isfinite(d)), "Values must be finite" self.coordname = depdomain.keys()[0] if isinstance(d, list): if self.coordtype is not None: self.depdomain = array(d, self.coordtype) else: self.depdomain = array(d) elif isinstance(d, Array) or isinstance(d, NArray): da = array(d) if self.coordtype is not None and \ self.coordtype != da.type(): raise TypeError, ("Mismatch between type of depdomain " "argument and Pointset coord data") else: self.depdomain = da else: raise TypeError, ("Invalid type for dependent variable " "domain") self.coordtype = self.depdomain.type() else: print "Dependent variable domain argument was:", depdomain raise TypeError, "Invalid type for dependent variable domain" if isinstance(self.output, Pointset): assert self.coordname == self.output.coordnames[0], \ "Mismatch between Pointset coord name and declared name" assert self.indepvarname == self.output.indepvarname, \ ("Mismatch between Pointset independent variable name " "and declared name")
class Variable(object): """One-dimensional discrete and continuous real variable class. """ def __init__(self, outputdata=None, indepdomain=None, depdomain=None, name='noname'): # funcreg stores function data for dynamically created methods # to allow a Variable to be copied using pickling self._funcreg = {} if isinstance(name, str): self.name = name else: raise TypeError, "name argument must be a string" # defaults for empty 'placeholder' Variables if outputdata is None or isinstance(outputdata, Pointset): if indepdomain is None: indepdomain = 't' if depdomain is None: depdomain = 'x' # set some initial values so that can test if what changed # after calling setOutput() self._vectorizable = True self.defined = False self.indepdomain = None self.indepvartype = None self.indepvarname = None self.depdomain = None self.coordtype = None self.coordname = None self._refvars = None # for use with ExplicitFnGen # Ranges covered by the current trajectory held (if known) self.trajirange = None self.trajdrange = None # independent variable domain self.setIndepdomain(indepdomain) # output function self.setOutput(outputdata) # dependent variable domain self.setDepdomain(depdomain) assert self.coordname != self.indepvarname, ("Independent variable " "name and coordinate name must be different") self.warnings = [] # Auxiliary functions for user-defined code to call def _auxfn_globalindepvar(self, parsinps, t): return self.globalt0 + t def _auxfn_initcond(self, parsinps, varname): return self.initialconditions[varname] def _auxfn_heav(self, parsinps, x): if x>0: return 1 else: return 0 def _auxfn_if(self, parsinps, c, e1, e2): if c: return e1 else: return e2 def _auxfn_getindex(self, parsinps, varname): return self._var_namemap[varname] def addMethods(self, funcspec): """Add dynamically-created methods to Veriable object""" # Add the auxiliary function specs to this Variable's namespace for auxfnname in funcspec.auxfns: fninfo = funcspec.auxfns[auxfnname] if not hasattr(Variable, fninfo[1]): # user-defined auxiliary functions # (built-ins are provided explicitly) try: exec fninfo[0] in globals() except: print 'Error in supplied auxiliary function code' raise self._funcreg[fninfo[1]] = ('Variable', fninfo[0]) setattr(Variable, fninfo[1], eval(fninfo[1])) # Add the spec function to this Variable's namespace fninfo_spec = funcspec.spec if not hasattr(Variable, fninfo_spec[1]): try: exec fninfo_spec[0] in globals() except: print 'Error in supplied functional specification code' raise self._funcreg[fninfo_spec[1]] = ('Variable', fninfo_spec[0]) setattr(Variable, fninfo_spec[1], eval(fninfo_spec[1])) # Add the auxiliary spec function (if present) to this Var's namespace if funcspec.auxspec: fninfo_auxspec = funcspec.auxspec if not hasattr(Variable, fninfo_auxspec[1]): try: exec fninfo_auxspec[0] in globals() except: print 'Error in supplied auxiliary variable code' raise self._funcreg[fninfo_auxspec[1]] = ('Variable', fninfo_auxspec[0]) setattr(Variable, fninfo_auxspec[1], eval(fninfo_auxspec[1])) # For implicit functions if isinstance(funcspec, ImpFuncSpec): impfn_name = funcspec.algparams['impfn_name'] if funcspec.algparams['jac']: jac_str = "fprime=funcspec.algparams['jac']," else: jac_str = "" # Wrap spec fn like this as it has been set up as a # method, but want to call as regular function # *** ALSO *** spec fn has signature (ds, t, x, p) # but implicit function solvers expect # (x, t, p), so have to switch 1st and 2nd args here # after 'ds' filled with None if len(funcspec.vars) == 1: # dimension == 1, so have to make list output from spec # into a scalar # Also, scalar a1 needs to be put into list form for # acceptance as x in spec fn specfn_str = "lambda a1, a2, a3: " \ + fninfo_spec[1] \ + "(None, a2, [a1], a3)[0]" else: # for dimension > 1 a1 will already be an array / list specfn_str = "lambda a1, a2, a3: " \ + fninfo_spec[1] \ + "(None, a2, a1, a3)" this_scope = globals() # WE CHANGE GLOBALS() this_scope.update({'funcspec': locals()['funcspec'], 'fninfo_spec': locals()['fninfo_spec']}) impfn_str = impfn_name + \ " = makeImplicitFunc(" + specfn_str + "," \ + jac_str + """x0=funcspec.algparams['x0'], extrafargs=(funcspec.algparams['pars'],), xtolval=funcspec.algparams['atol'], maxnumiter=funcspec.algparams['maxnumiter'], solmethod=funcspec.algparams['solvemethod'], standalone=False)""" try: exec impfn_str in this_scope except: print 'Error in supplied implicit function code' raise # record special reference to the implicit fn, # as its a method of Variable (for delete method). self._funcreg['_impfn'] = (impfn_name, impfn_str) # In previous versions setattr was to self, not the Variable class setattr(Variable, impfn_name, eval(impfn_name)) # clean up globals() afterwards del this_scope['funcspec'] del this_scope['fninfo_spec'] def setOutput(self, outputdata, funcspec=None, globalt0=0, var_namemap=None, ics=None, refvars=None): """Dynamically create 'output' method of Variable""" self.globalt0 = globalt0 if type(outputdata) in [types.FunctionType, types.BuiltinFunctionType, types.MethodType]: # Variable generated from function, given in closed form self.output = outputdata assert ics is None, "Invalid option for this type of output" if outputdata != noneFn: self.defined = True elif isinstance(outputdata, tuple): # For ExplicitFnGen or ImplicitFnGen types, whose functional forms # may need to access these at call time. assert len(outputdata) == 2, "Incorrect size of outputdata tuple" if funcspec is not None: self.addMethods(funcspec) self._var_namemap = var_namemap self._funcreg['funcspec'] = (None, funcspec) else: raise ValueError, 'funcspec missing in setOutput' # Add the specific mapping functions for Ex/ImplicitFnGen objects try: exec outputdata[1] in globals() except: print 'Internal Error in _mapspecfn code' raise has_op = hasattr(self, 'output') # have to define this function in here because use of lambda # won't allow me to pickle the Variable object if not has_op or (has_op and self.output is noneFn): def wrap_output(arg): return eval(outputdata[0])(self, arg) setattr(self, 'output', wrap_output) self._funcreg['outputdata'] = (None, outputdata) t0 = self.indepdomain.get(0) if ics is None and not isinstance(funcspec, ImpFuncSpec): try: self.initialconditions = {self.coordname: self.output(t0)} except ValueError: self.initialconditions = {self.coordname: NaN} except TypeError: print "Debugging info: self.output = ", self.output raise else: self.initialconditions = ics self._vectorizable = False self._refvars = refvars self.defined = True elif type(outputdata) in [types.InstanceType, types.TypeType, \ OutputFn] or isinstance(outputdata, interpclass): # Variable generated by callable object that generates values over # mesh points that it holds, e.g. by interpolation # (InstanceType and TypeType are for backwards compatibility, e.g. # for old SciPy interpolate code that uses Classic Classes) assert ics is None, "Invalid option for this type of output" assert '__call__' in dir(outputdata), "Must provide callable object" self.output = outputdata if hasattr(outputdata, 'datapoints'): if hasattr(outputdata, 'types'): deptypestr = _pytypename[outputdata.types[0]] indeptypestr = _pytypename[outputdata.types[1]] else: # default deptypestr = indeptypestr = 'float' if isinstance(outputdata.datapoints[0], Interval): assert outputdata.types[0] == \ outputdata.datapoints[0].type, \ "Inconsistent type with Interval bounds" self.trajirange = outputdata.datapoints[0] else: self.trajirange = Interval('traj_indep_bd', indeptypestr, extent(outputdata.datapoints[0])) if isinstance(outputdata.datapoints[1], Interval): assert outputdata.types[1] == \ outputdata.datapoints[1].type, \ "Inconsistent type with Interval bounds" self.trajdrange = outputdata.datapoints[1] else: self.trajdrange = Interval('traj_dep_bd', deptypestr, extent(outputdata.datapoints[1])) self.defined = True elif isinstance(outputdata, Pointset): # Variable generated from a pointset (without interpolation) assert ics is None, "Invalid option for this type of output" assert isparameterized(outputdata), ("Must only pass parameterized" " pointsets") if outputdata.dimension == 1: self.coordname = copy.copy(outputdata.coordnames[0]) self.indepvarname = outputdata.indepvarname self.output = Varcaller(outputdata) self.coordtype = outputdata.coordtype self.indepvartype = outputdata.indepvartype if self.indepdomain is not None: for v in outputdata[self.indepvarname]: if not v in self.indepdomain: raise ValueError, ("New Pointset data violates " "independent variable domain already specified") if self.depdomain is not None: for v in outputdata[self.coordname]: if not v in self.depdomain: raise ValueError, ("New Pointset data violates " "dependent variable domain already specified") self.trajirange = Interval('traj_indep_bd', _pytypename[self.indepvartype], extent(outputdata.indepvararray)) self.trajdrange = Interval('traj_dep_bd', _pytypename[self.coordtype], extent(outputdata[self.coordname])) self.defined = True else: raise ValueError, \ "Pointset data must be 1D to create a Variable" elif outputdata is None: # placeholder for an unknown output type assert ics is None, "Invalid option when outputdata argument is None" self.output = noneFn self.defined = False else: raise TypeError, ("Invalid type for data argument: " \ +str(type(outputdata))) def setIndepdomain(self, indepdomain): if isinstance(indepdomain, str): self.indepvarname = indepdomain if self.indepdomain is not None: # If indepdomain already set and indepvarname is none then # name won't get put in place unless we force it here self.indepvarname = indepdomain self.indepdomain.name = indepdomain else: self.indepdomain = Interval(self.indepvarname, 'float', [-Inf, Inf]) self.indepvartype = Float else: if isinstance(indepdomain, Interval): if self.trajirange: if indepdomain.contains(self.trajirange) is notcontained: raise ValueError, ("Cannot set independent variable" " domain inside current trajectory's" " range") self.indepdomain = indepdomain self.indepvarname = indepdomain.name self.indepvartype = _pynametype[indepdomain.typestr] elif isinstance(indepdomain, dict): assert len(indepdomain) == 1, "Dictionary must have only 1 entry" d = indepdomain.values()[0] assert all(isfinite(d)), "Values must be finite" assert isincreasing(d), "Values must be increasing" if self.trajirange: assert self.trajirange.get(0) in d assert self.trajirange.get(1) in d self.indepvarname = indepdomain.keys()[0] if isinstance(d, list): self.indepdomain = array(d) elif isinstance(d, Array) or isinstance(d, NArray): self.indepdomain = d else: raise TypeError, ("Invalid type for independent " "variable domain") self.indepvartype = self.indepdomain.type() else: print "Independent variable argument domain was:", indepdomain raise TypeError, ("Invalid type for independent variable " "domain") def setDepdomain(self, depdomain): if isinstance(depdomain, str): self.coordname = depdomain if self.depdomain is None: if self.coordtype is None: self.depdomain = Interval(self.coordname, 'float', [-Inf, Inf]) self.coordtype = Float else: self.depdomain = Interval(self.coordname, _pytypename[self.coordtype], _nummaxmin[self.coordtype]) else: # If interp functions supplied then don't have a name for # Interval yet, so update it. if isinstance(self.output, interpclass) and \ isinstance(self.depdomain, Interval): self.depdomain.name = depdomain else: assert isinstance(self.output, Pointset) print "Warning: Dependent variable already named. " + \ "Ignoring user-supplied name." else: if isinstance(depdomain, Interval): if self.trajdrange: if depdomain.contains(self.trajdrange) is notcontained: raise ValueError, ("Cannot set dependent variable " "domain inside current trajectory's " "range") self.depdomain = depdomain self.coordname = depdomain.name if self.coordtype is None: self.coordtype = depdomain.type elif self.coordtype == depdomain.type: pass else: raise TypeError, ("Mismatch between type of depdomain " "argument and Pointset coord data") elif isinstance(depdomain, dict): assert len(depdomain) == 1, "Dictionary must have only 1 entry" d = depdomain.values()[0] if self.trajdrange: assert self.trajdrange.get(0) in d assert self.trajdrange.get(1) in d ## if not isincreasing(d): ## d.sort() assert all(isfinite(d)), "Values must be finite" self.coordname = depdomain.keys()[0] if isinstance(d, list): if self.coordtype is not None: self.depdomain = array(d, self.coordtype) else: self.depdomain = array(d) elif isinstance(d, Array) or isinstance(d, NArray): da = array(d) if self.coordtype is not None and \ self.coordtype != da.type(): raise TypeError, ("Mismatch between type of depdomain " "argument and Pointset coord data") else: self.depdomain = da else: raise TypeError, ("Invalid type for dependent variable " "domain") self.coordtype = self.depdomain.type() else: print "Dependent variable domain argument was:", depdomain raise TypeError, "Invalid type for dependent variable domain" if isinstance(self.output, Pointset): assert self.coordname == self.output.coordnames[0], \ "Mismatch between Pointset coord name and declared name" assert self.indepvarname == self.output.indepvarname, \ ("Mismatch between Pointset independent variable name " "and declared name") def __call__(self, indepvar, checklevel=0): if checklevel == 0: # level 0 -- no depvar bounds checking at all # (no need to check for indepvar as list case, which output # should know how to handle) try: if not self._vectorizable and type(indepvar) in \ [list, Array, NArray]: return [self.output(ival) for ival in indepvar] else: return self.output(indepvar) except OverflowError: print "Overflow error at independent variable =", indepvar raise elif checklevel in [1,2]: if self.trajirange is None: idep = self.indepdomain else: # use known bounds on indep variable imposed by self.output idep = self.trajirange indepvar_ok = True # level 1 -- ignore uncertain cases (treat as contained) # level 2 -- warn on uncertain (treat as contained) if type(indepvar) in [list, Array, NArray]: vectorizable = self._vectorizable for d in indepvar: # use 'in' so that this is compatible with # interval, array and index indeps try: contresult = d in idep except PyDSTool_UncertainValueError: contresult = True # adjust for rounding error so that interpolator # does not barf on out-of-range values if d < idep.get(0): try: # list dix = indepvar.index(d) except AttributeError: # array dix = indepvar.tolist().index() indepvar[dix] = idep.get(0) elif d > idep.get(1): try: # list dix = indepvar.index(d) except AttributeError: # array dix = indepvar.tolist().index() indepvar[dix] = idep.get(1) if checklevel == 2: self.warnings.append((d, None)) if not contresult: indepvar_ok = False break else: vectorizable = True try: indepvar_ok = indepvar in idep except PyDSTool_UncertainValueError, errinfo: # adjust for rounding error so that interpolator # does not barf on out-of-range values if indepvar < idep.get(0): indepvar = idep.get(0) elif indepvar > idep.get(1): indepvar = idep.get(1) if checklevel == 2: self.warnings.append((indepvar, None)) # continue to get dependent variable value, unless indep # value was not OK if not indepvar_ok: ## print "*** Debug info for variable: ", self.name ## print "Interval rounding tolerance was", idep._abseps if vectorizable: raise ValueError, ('Independent variable value(s) ' 'out of range in Variable call') else: raise ValueError, ('Independent variable value '+\ str(indepvar) + ' out of ' 'range in Variable call') try: if vectorizable: depvar = self.output(indepvar) else: depvar = [self.output(ival) for ival in indepvar] depvar_ok = True except PyDSTool_BoundsError, errinfo: depvar_ok = False # Now check that all computed values were in depdomain if depvar_ok: # no need to use self.trajdrange instead of # self.depdomain because we trust that self.output # generated the output within its own bounds! if type(depvar) in [list, Array, NArray, Pointset]: if isinstance(depvar, Pointset): dv = depvar.toarray() else: dv = depvar for d in dv: # use 'in' so that this is compatible with # interval, array and index indeps try: contresult = d in self.depdomain except PyDSTool_UncertainValueError, errinfo: contresult = True if checklevel == 2: # find which indepvar was the cause of # the uncertain value try: # list depix = dv.index(d) except AttributeError: # array depix = dv.tolist().index(d) self.warnings.append((indepvar[depix], errinfo.val)) if not isfinite(d): print "Warning: Return value for independent " + \ "variable %f was not finite"%indepvar + \ "for Variable '%s'"%self.name if not contresult: depvar_ok = False break elif depvar is None: print "*** Debug info for variable: ", self.name print "Independent variable domain: ", self.indepdomain._infostr(1) print "Dependent variable domain: ", self.depdomain._infostr(1) raise ValueError, ("Cannot compute a return value for " "this independent variable value: " + str(indepvar)) else: if isinstance(depvar, Point): dv = depvar[0] else: dv = depvar try: depvar_ok = dv in self.depdomain except PyDSTool_UncertainValueError, errinfo: if checklevel == 2: self.warnings.append((indepvar, errinfo.varval)) if not isfinite(dv): print "Warning: Return value for independent variable", indepvar print "was not finite for Variable '%s'"%self.name
# self.start = s # self.end = e class Solution: def eraseOverlapIntervals(self, intervals: 'List[Interval]') -> 'int': if len(intervals) <= 1: return 0 intervals.sort(key=lambda x: [x.end, -x.start]) cur = intervals[0] ret = 0 for i in range(1, len(intervals)): if intervals[i].start >= cur.end: cur = intervals[i] continue ret += 1 return ret # test if __name__ == "__main__": tmp = NonoverlappingIntervals() intervals = [ Interval(1, 2), Interval(2, 3), Interval(3, 4), Interval(1, 3) ] result = tmp.eraseOverlapIntervals(intervals) print(result)
def test_decreasing_augmented_should_raise(): with pytest.raises(ValueError): interval = Interval.Interval('B', 'A#') interval.get_augmented_interval()
return intervals # 9/2/2020 # use bisect_left to find the insert position, then insert the interval # Then start from i-1 element, we must check and merge these intervals def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: i = bisect_left(intervals, newInterval) intervals.insert(i, newInterval) while i < len(intervals): if i > 0 and intervals[i - 1][1] >= intervals[i][0]: intervals[i - 1][1] = max(intervals[i - 1][1], intervals[i][1]) intervals.pop(i) else: i += 1 return intervals obj = Solution() case, new = [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], Interval(4, 8) case, new = [[3, 5], [6, 7], [8, 10], [12, 16]], Interval(1, 6) case, new = [], Interval(1, 3) case, new = [[0, 5], [9, 12]], Interval(7, 16) # expect [[0, 5], [7, 16]] intervals = [] for element in case: intervals.append(Interval(*element)) print(obj.insert2(intervals, new))
def get_random_interval_from_root(root): second_note = random.choice(Interval.notes) interval = Interval.Interval(root, second_note) logger.debug(f"Get random interval from root returned {interval}") return interval
def test_bemol(note, bemol): assert Interval.get_bemol(note) == bemol
while i < len(A) and j < len(B): if A[i][0] > B[j][1]: # B[j] on left of A[i] j += 1 elif A[i][1] < B[j][0]: # B[j] on right of A[i] i += 1 else: # A[i] and B[j] has intersection s, e = max(A[i][0], B[j][0]), min(A[i][1], B[j][1]) res.append([s, e]) if A[i][1] > B[j][ 1]: # advance pointer for interval with smaller end j += 1 else: i += 1 return res #A, B = [], [] # expect [] #A, B = [], [Interval(1, 1)] # expect [] #A, B = [Interval(1, 1)], [] # expect [] #A, B = [Interval(1, 2), Interval(3, 5)], [Interval(0, 4)] # expect [[1, 2], [3, 4]] A, B = [Interval(0, 2), Interval(5, 10), Interval(13, 23), Interval(24, 25)], [ Interval(1, 5), Interval(8, 12), Interval(15, 24), Interval(25, 26) ] print(Solution().intervalIntersection(A, B))