def future(self, i): #到底需不需要考虑拓扑顺序呢??? if type(self.node_list[i]) != Varnode or self.node_list[i].I == None: return #第一次future是提前做的,因此现在I还可能是空呢 for item in self.node_list[i].next_dashed_list: if self.node_list[item].lval != None: #lval != -inf #e.g. 原来是[j_3, a),现在有[, 99] #把lval换成-inf,变成[-inf, a),然后把这个字符串代入Interval进行初始化 tmp = copy.deepcopy(self.node_list[item]) tmp.lval = str(self.node_list[i].I.lower) s = str(tmp).replace('-inf', '').replace('inf', '') if tmp._type == 'int': e = IntInterval.from_string(s) else: e = FloatInterval.from_string(s) else: #rval != inf #e.g. 原来是(a,j_3),现在有[, 99] #把rval=j_3换成99,变成(a, 99),然后把这个字符串代入Interval进行初始化 tmp = copy.deepcopy(self.node_list[item]) tmp.rval = str(self.node_list[i].I.upper) s = str(tmp).replace('-inf', '').replace('inf', '') #用字符串来初始化不能有inf,而要留空 if tmp._type == 'int': e = IntInterval.from_string(s) else: e = FloatInterval.from_string(s) self.node_list[item].I = e
def test_canonicalize_integer_intervals(): assert str(canonicalize(IntInterval([1, 4]))) == '[1, 5)' assert str( canonicalize(IntInterval((1, 7)), lower_inc=True, upper_inc=True)) == '[2, 6]' assert str( canonicalize(IntInterval([1, 7]), lower_inc=False, upper_inc=True)) == '(0, 7]'
def get_feasible_region(self, flow: Flow, send_delay: int, prop_delay: int, proc_delay: int, cycle_len: int) -> IntInterval: last_hop_time_slot_offset: int = flow.get_last_hop_time_slot_offset() if last_hop_time_slot_offset == -1: return IntInterval.closed_open(0, cycle_len) else: assignable_position: int = send_delay + prop_delay + proc_delay + last_hop_time_slot_offset return IntInterval.closed_open(assignable_position, assignable_position + cycle_len) pass
def test_and_operator_for_half_open_intervals_with_empty_results( self, interval1, interval2, empty ): assert ( IntInterval.from_string(interval1) & IntInterval.from_string(interval2) ).empty == empty
class TestArithmeticOperators(object): @mark.parametrize( ('first', 'second', 'result'), ((IntInterval([1, 3]), IntInterval([1, 2]), [2, 5]), (IntInterval([1, 3]), 1, [2, 4]), (1, IntInterval([1, 3]), [2, 4]), ([1, 2], IntInterval([1, 2]), [2, 4]))) def test_add_operator(self, first, second, result): assert first + second == IntInterval(result) @mark.parametrize( ('first', 'second', 'result'), ((IntInterval([1, 3]), IntInterval([1, 2]), [-1, 2]), (IntInterval([1, 3]), 1, [0, 2]), (1, IntInterval([1, 3]), [-2, 0]))) def test_sub_operator(self, first, second, result): assert first - second == IntInterval(result) def test_isub_operator(self): range_ = IntInterval([1, 3]) range_ -= IntInterval([1, 2]) assert range_ == IntInterval([-1, 2]) def test_iadd_operator(self): range_ = IntInterval([1, 2]) range_ += IntInterval([1, 2]) assert range_ == IntInterval([2, 4]) @mark.parametrize( ('first', 'second', 'intersection'), (('[1, 5]', '[2, 9]', '[2, 5]'), ('[3, 4]', '[3, 9]', '[3, 4]'), ('(3, 6]', '[2, 6)', '(3, 6)'))) def test_intersection(self, first, second, intersection): IntInterval(first) & IntInterval(second) == IntInterval(intersection)
class TestArithmeticOperators(object): @mark.parametrize( ('first', 'second', 'result'), ((IntInterval([1, 3]), IntInterval([1, 2]), [2, 5]), (IntInterval([1, 3]), 1, [2, 4]), (1, IntInterval([1, 3]), [2, 4]), ([1, 2], IntInterval([1, 2]), [2, 4]))) def test_add_operator(self, first, second, result): assert first + second == IntInterval(result) @mark.parametrize( ('first', 'second', 'result'), ((IntInterval([1, 3]), IntInterval([1, 2]), [-1, 2]), (IntInterval([1, 3]), 1, [0, 2]), (1, IntInterval([1, 3]), [-2, 0]))) def test_sub_operator(self, first, second, result): assert first - second == IntInterval(result) def test_isub_operator(self): range_ = IntInterval([1, 3]) range_ -= IntInterval([1, 2]) assert range_ == IntInterval([-1, 2]) def test_iadd_operator(self): range_ = IntInterval([1, 2]) range_ += IntInterval([1, 2]) assert range_ == IntInterval([2, 4])
def test_and_operator_with_half_open_intervals( self, interval1, interval2, result ): assert ( IntInterval.from_string(interval1) & IntInterval.from_string(interval2) == IntInterval(result) )
def test_or_operator( self, interval1, interval2, result ): assert ( IntInterval.from_string(interval1) | IntInterval.from_string(interval2) == result )
def calculate_free_blocks(self) -> List[IntInterval]: free_blocks: List[IntInterval] = [] lower: int = 0 for block in self.allocation_blocks_m: if block.interval.lower != 0 and lower < block.interval.lower: free_blocks.append( IntInterval.closed(lower, block.interval.lower - 1)) lower = block.interval.upper + 1 if lower < self.time_slot_num: free_blocks.append( IntInterval.closed(lower, self.time_slot_num - 1)) return free_blocks
def __init__(self, var_type, interval=None): super(Var, self).__init__() self.var_type = var_type self.interval = {} if var_type == 'int': if interval == None: self.interval['int'] = IntInterval.all() else: self.interval['int'] = IntInterval(interval) elif var_type == 'float': if interval == None: self.interval['float'] = FloatInterval.all() else: self.interval['float'] = FloatInterval(interval)
def test_all(self): interval = IntInterval.all(step=2) assert interval.lower == -inf assert interval.upper == inf assert not interval.lower_inc assert not interval.upper_inc assert interval.step == 2
def test_at_most(self): interval = IntInterval.at_most(10, step=2) assert interval.lower == -inf assert interval.upper == 10 assert not interval.lower_inc assert interval.upper_inc assert interval.step == 2
def reset(self): self.flow_times_mapper = { } # clear flow-time-slots mapper when hyper period changes self.allocation_blocks = [] # clear time slot allocation self.allocation_blocks_m = [] # clear merged time slot allocation self.allocation_blocks_c = [] self.allocation_blocks_m_c = [] self.load = 0 self.load_c = 0 self.time_slot_used = 0 self.time_slot_used_c = 0 self.flow_num = 0 self.flow_num_c = 0 self.flow_segment_num = 0 if self.bandwidth != 0 and self.min_flow_size != 0 and self.__hyper_period: self.time_slot_len = ceil(self.min_flow_size / self.bandwidth) # self.time_slot_num = floor(self.__hyper_period / self.time_slot_len) self.time_slot_len = ceil( self.min_flow_size / config.GRAPH_CONFIG['max-bandwidth']) # TODO fix bug here self.time_slot_num = floor(self.__hyper_period / self.time_slot_len) self.free_intervals = [ IntInterval.closed(0, self.time_slot_num - 1) ] else: self.time_slot_len = 0 self.time_slot_num = 0 self.free_intervals = [] self.to_string()
def test_greater_than(self): interval = IntInterval.greater_than(10, step=2) assert interval.lower == 10 assert interval.upper == inf assert not interval.lower_inc assert not interval.upper_inc assert interval.step == 2
def test_closed_open(self): interval = IntInterval.closed_open(10, 14, step=2) assert interval.lower == 10 assert interval.upper == 14 assert interval.lower_inc assert not interval.upper_inc assert interval.step == 2
def test_supports_integers(self): interval = IntInterval(3) assert interval.lower.__class__ == int assert interval.lower == 3 assert interval.upper == 3 assert interval.lower_inc assert interval.upper_inc
def allocate_time_slots_m(self, fid: FlowId, time_slot_offset: int, allocated_len: int): interval: IntInterval = IntInterval.closed_open(time_slot_offset, time_slot_offset + allocated_len) flag: bool = False for time_window in self.time_windows: try: new_time_window_0: IntInterval = time_window | interval if getattr(time_window, 'fid') == fid: i: int = self.time_windows.index(time_window) setattr(new_time_window_0, 'fid', fid) del self.time_windows[i] self.time_windows.insert(i, new_time_window_0) j: int = i + 1 if j < len(self.time_windows) and \ getattr(self.time_windows[j], 'fid') == fid and \ new_time_window_0.upper == self.time_windows[j].lower: new_time_window_1: IntInterval = self.time_windows[j] | self.time_windows[i] setattr(new_time_window_1, 'fid', fid) del self.time_windows[i] del self.time_windows[i] self.time_windows.insert(i, new_time_window_1) flag = True break except Exception as e: pass if flag is False: setattr(interval, 'fid', fid) self.time_windows.append(interval) self.time_windows.sort()
def test_less_than(self): interval = IntInterval.less_than(10, step=2) assert interval.lower == -inf assert interval.upper == 10 assert not interval.lower_inc assert not interval.upper_inc assert interval.step == 2
def compareAirHum(airHum, plantModel): if not plantModel.airHumidity_low or not plantModel.airHumidity_high: return SensorResult(True, airHum, '0', '0', '标准生长模型为空') ret = airHum in IntInterval.closed(plantModel.airHumidity_low, plantModel.airHumidity_high) if ret: return SensorResult( True, airHum, str(plantModel.airHumidity_low) + '-' + str(plantModel.airHumidity_high)) else: # todo 给出指导意见 if airHum - plantModel.airHumidity_low < 0: advice = "当前光照强度为{},标准光照强度为{},建议至少{}光照强度{}".format( airHum, plantModel.airHumidity_low, '上调', plantModel.airHumidity_low - airHum) else: advice = "当前光照强度为{},标准光照强度为{},建议至少{}光照强度{}".format( airHum, plantModel.airHumidity_high, '下调', airHum - plantModel.airHumidity_high) return SensorResult(False, airHum, str(plantModel.airHumidity_low) + '-' + str(plantModel.airHumidity_high), advice=advice)
def compareLight(light, plantModel): if not plantModel.lightIntensity_low or not plantModel.lightIntensity_high: return SensorResult(True, light, '0', '0', '标准生长模型为空') ret = light in IntInterval.closed(plantModel.lightIntensity_low, plantModel.lightIntensity_high) if ret: return SensorResult( True, light, str(plantModel.lightIntensity_low) + '-' + str(plantModel.lightIntensity_high)) else: # todo 给出指导意见 if light - plantModel.lightIntensity_low < 0: advice = "当前光照强度为{},标准光照强度为{},建议至少{}光照强度{}".format( light, plantModel.lightIntensity_low, '上调', plantModel.lightIntensity_low - light) else: advice = "当前光照强度为{},标准光照强度为{},建议至少{}光照强度{}".format( light, plantModel.lightIntensity_high, '下调', light - plantModel.lightIntensity_high) return SensorResult(False, light, str(plantModel.lightIntensity_low) + '-' + str(plantModel.lightIntensity_high), advice=advice)
def compareAirTemp(airTemp, plantModel): """ 比较空气温度 :param airTemp: 实时数据 :param plantModel: 标准生长模型 :return: SensorResult """ if not plantModel.airTemprature_low or not plantModel.airTemprature_high: return SensorResult(True, airTemp, standardData='0-0', advice='标准生长模型为空') ret = airTemp in IntInterval.closed(plantModel.airTemprature_low, plantModel.airTemprature_high) if ret: return SensorResult( True, airTemp, str(plantModel.airTemprature_low) + '-' + str(plantModel.airTemprature_high)) else: # todo 给出指导意见 if airTemp - plantModel.airTemprature_low < 0: advice = "当前温度为{},标准温度为{},建议至少{}温度{}".format( airTemp, plantModel.airTemprature_low, '上调', plantModel.airTemprature_low - airTemp) else: advice = "当前温度为{},标准温度为{},建议至少{}温度{}".format( airTemp, plantModel.airTemprature_high, '下调', airTemp - plantModel.airTemprature_high) return SensorResult(False, airTemp, str(plantModel.airTemprature_low) + '-' + str(plantModel.airTemprature_high), advice=advice)
def compareSoilHum(soilHum, plantModel): if not plantModel.soilHumidity_low or not plantModel.soilHumidity_high: return SensorResult(True, soilHum, '0', '0', '标准生长模型为空') ret = soilHum in IntInterval.closed(plantModel.soilHumidity_low, plantModel.soilHumidity_high) if ret: return SensorResult( True, soilHum, str(plantModel.soilHumidity_low) + '-' + str(plantModel.soilHumidity_high)) else: # todo 给出指导意见 if soilHum - plantModel.soilHumidity_low < 0: advice = "当前土壤湿度为{},标准土壤湿度为{},建议至少{}土壤湿度{}".format( soilHum, plantModel.soilHumidity_low, '上调', plantModel.soilHumidity_low - soilHum) else: advice = "当前土壤湿度为{},标准土壤湿度为{},建议至少{}土壤湿度{}".format( soilHum, plantModel.soilHumidity_high, '下调', soilHum - plantModel.soilHumidity_high) return SensorResult(False, soilHum, str(plantModel.soilHumidity_low) + '-' + str(plantModel.soilHumidity_high), advice=advice)
def __init__(self, _type, const): super(Constnode, self).__init__(_type) self.const = const val = float(const) if val == int(val) and not const.endswith('.0'): self.I = IntInterval([int(val), int(val)]) #TODO: float else: self.I = FloatInterval([val, val]) #TODO: float
def allocate_time_slots(self, flow: Flow, time_slot_offset: int, allocated_len: int, phs_num: int) -> bool: if not self._check_assignable(flow, time_slot_offset, allocated_len, phs_num): return False cycle_time_slot_num: int = int(np.ceil(flow.cycle / self.time_slot_len)) for phs in range(0, phs_num): offset: int = time_slot_offset + phs * cycle_time_slot_num interval: IntInterval = IntInterval.closed_open(offset, offset + allocated_len) setattr(interval, 'm_fid', flow.m_fid) setattr(interval, 'fid', flow.fid) setattr(interval, 'phs', phs) self.time_windows.append(interval) self.time_windows.sort() return True
def start_flow(self, t): """ Only flow after the specified t will actually be transferred from the source account to dest. """ if self._flow_enabled: raise PipeException("Flow already started") if t < self._last_flushed_t: raise PipeException("Time travel not supported yet") if not self._last_stopped_t == None: self._blackouts.append(IntInterval.closed_open(self._last_stopped_t, t)) self._last_flushed_t = t self._flow_enabled = True
def list_to_interval(data_list): '''Method to turn lists into intervals. :param data_list: :return: ''' try: list_interval = [] for i in range(len(data_list)): if i != len(data_list) - 1: data_range = IntInterval.closed_open( data_list[i], data_list[i + 1]) list_interval.append(data_range) print("Success in list to interval", datetime.now(), flush=True) return list_interval except Exception as err: logging.error('Error in list to interval:', err)
def buildDictionary() -> dict: popUpDict = {} with open('PopUpRead.csv', 'r', newline='') as file: read = csv.reader(file) next(read) #skip header for row in read: #skips duplicates if row[0] not in popUpDict: popUpDict[row[0]] = [ [x.strip() for x in row[1].split(',') if x], IntInterval.from_string(row[2]), [x.strip() for x in row[3].split(',') if x], row[4] ] if '' == row[2]: popUpDict[row[0]][1] = '0' if '' == row[4]: popUpDict[row[0]][3] = 'hot' return popUpDict
def _check_assignable(self, flow: Flow, time_slot_offset: int, allocated_len: int, phs_num: int) -> bool: cycle_time_slot_num: int = int(np.ceil(flow.cycle / self.time_slot_len)) for phs in range(0, phs_num): offset: int = time_slot_offset + phs * cycle_time_slot_num interval: IntInterval = IntInterval.closed_open(offset, offset + allocated_len) for time_window in self.time_windows: try: if time_window | interval: if time_window.upper == interval.lower: continue elif time_window.lower == interval.upper: continue elif getattr(time_window, 'm_fid') != flow.m_fid: return False elif getattr(time_window, 'phs') != phs: return False except Exception as e: pass return True
def test_and_operator_for_empty_results(self, interval1, interval2, empty): assert (IntInterval(interval1) & IntInterval(interval2)).empty == empty
@mark.parametrize(('interval', 'string'), ( ((1, 3), '(1, 3)'), ([1, 1], '[1, 1]'), ([1, inf], '[1,]') )) def test_str_representation(interval, string): assert str(IntInterval(interval)) == string @mark.parametrize( ('number_range', 'empty'), ( (IntInterval((2, 3)), True), (IntInterval([2, 3]), False), (IntInterval([2, 2]), False), (IntInterval.from_string('[2, 2)'), True), (IntInterval.from_string('(2, 2]'), True), (IntInterval.from_string('[2, 3)'), False), (IntInterval((2, 10)), False), ) ) def test_bool(number_range, empty): assert bool(IntInterval(number_range)) != empty @mark.parametrize( ('number_range', 'coerced_value'), ( ([5, 5], 5), ([2, 2], 2), )
def test_int_with_empty_interval(number_range): with raises(TypeError): int(IntInterval.from_string(number_range))
from pytest import mark from intervals import IntInterval @mark.parametrize(('interval', 'string'), ( (IntInterval((1, 3)), '2'), (IntInterval([1, 1]), '1'), (IntInterval([1, 3]), '1 - 3'), (IntInterval.from_string('(1, 5]'), '2 - 5'), (IntInterval.from_string('[1,]'), '1 -') )) def test_hyphenized(interval, string): assert interval.hyphenized == string
def test_contains_operator_for_inclusive_interval(self, value): assert value in IntInterval([-1, 2])
def test_or_operator_with_illegal_arguments(self, interval1, interval2): with raises(IllegalArgument): ( IntInterval.from_string(interval1) | IntInterval.from_string(interval2) )
def test_empty_string_as_lower_bound(self): interval = IntInterval.from_string('[,1)') assert interval.lower == -inf assert interval.upper == 1 assert interval.lower_inc assert not interval.upper_inc
def test_eq_operator(self, interval, interval2): assert ( IntInterval.from_string(interval) == IntInterval.from_string(interval2) )
def test_supports_strings_with_bounds(self): interval = IntInterval.from_string('[1, 3]') assert interval.lower == 1 assert interval.upper == 3 assert interval.lower_inc assert interval.upper_inc
def test_step_argument_for_from_string(self): interval = IntInterval.from_string('[2,)', step=2) assert interval.lower == 2 assert interval.upper == inf assert interval.step == 2
def test_supports_strings_with_spaces(self): interval = IntInterval.from_string('1 - 3') assert interval.lower == 1 assert interval.upper == 3 assert interval.lower_inc assert interval.upper_inc
def test_hyphen_format(self, number_range, lower, upper): interval = IntInterval.from_string(number_range) assert interval.lower == lower assert interval.upper == upper
def test_supports_exact_ranges_as_strings(self): interval = IntInterval.from_string('3') assert interval.lower == 3 assert interval.upper == 3 assert interval.lower_inc assert interval.upper_inc
class TestComparisonOperators(object): @mark.parametrize(('comparison', 'result'), ( (IntInterval([1, 3]) == IntInterval([1, 3]), True), (IntInterval([1, 3]) == IntInterval([1, 4]), False), (IntInterval([inf, inf]) == inf, True), (IntInterval([3, 3]) == 3, True), (IntInterval([3, 3]) == 5, False), (IntInterval('(,)') == None, False) )) def test_eq_operator(self, comparison, result): assert comparison is result @mark.parametrize(('comparison', 'result'), ( (IntInterval([1, 3]) != IntInterval([1, 3]), False), (IntInterval([1, 3]) != IntInterval([1, 4]), True), (IntInterval([inf, inf]) != inf, False), (IntInterval([3, 3]) != 3, False), (IntInterval([3, 3]) != 5, True), (IntInterval('(,)') != None, True) )) def test_ne_operator(self, comparison, result): assert comparison is result @mark.parametrize(('comparison', 'result'), ( (IntInterval([1, 3]) > IntInterval([0, 2]), True), (IntInterval((1, 4)) > 1, False), (IntInterval((1, 6)) > [1, 6], False), (IntInterval((1, 6)) > 0, True) )) def test_gt_operator(self, comparison, result): assert comparison is result @mark.parametrize(('comparison', 'result'), ( (IntInterval([1, 3]) >= IntInterval([0, 2]), True), (IntInterval((1, 4)) >= 1, False), (IntInterval((1, 6)) >= [1, 6], False), (IntInterval((1, 6)) >= 0, True) )) def test_ge_operator(self, comparison, result): assert comparison is result @mark.parametrize(('comparison', 'result'), ( (IntInterval([0, 2]) < IntInterval([1, 3]), True), (IntInterval([2, 3]) < IntInterval([2, 3]), False), (IntInterval([2, 5]) < 6, True), (IntInterval([2, 5]) < 5, False), (IntInterval([2, 5]) < inf, True) )) def test_lt_operator(self, comparison, result): assert comparison is result @mark.parametrize(('comparison', 'result'), ( (IntInterval([0, 2]) <= IntInterval([1, 3]), True), (IntInterval([1, 3]) <= IntInterval([1, 3]), True), (IntInterval([1, 7]) <= 8, True), (IntInterval([1, 6]) <= 5, False), (IntInterval([1, 5]) <= inf, True) )) def test_le_operator(self, comparison, result): assert comparison is result def test_integer_comparison(self): assert IntInterval([2, 2]) <= 3 assert IntInterval([1, 3]) >= 0 assert IntInterval([2, 2]) == 2 assert IntInterval([2, 2]) != 3 @mark.parametrize('value', ( IntInterval([0, 2]), 1, (-1, 1), )) def test_contains_operator_for_inclusive_interval(self, value): assert value in IntInterval([-1, 2]) @mark.parametrize('value', ( IntInterval([0, 2]), 2, '[-1, 1]', )) def test_contains_operator_for_non_inclusive_interval(self, value): assert value not in IntInterval((-1, 2)) @mark.parametrize(('interval1', 'interval2', 'expected'), ( (IntInterval((0, 2)), IntInterval((0, 2)), True), (IntInterval([0, 2]), IntInterval([0, 2]), True), (IntInterval('[0, 2)'), IntInterval('[0, 2)'), True), (IntInterval('(0, 2]'), IntInterval('(0, 2]'), True), (IntInterval((0, 2)), IntInterval((1, 2)), False), (IntInterval((0, 2)), IntInterval((0, 1)), False), (IntInterval((0, 2)), IntInterval([0, 1]), False), (IntInterval((0, 2)), FloatInterval((0, 1)), False), )) def test_hash_operator_with_interval_attributes(self, interval1, interval2, expected): actual = (interval1.__hash__() == interval2.__hash__()) assert actual == expected @mark.parametrize(('contains_check', 'expected'), ( (IntInterval([0, 2]) in {IntInterval([0, 2]): ''}, True), (IntInterval([0, 2]) in {IntInterval((0, 2)): ''}, False), (IntInterval([0, 2]) in set([IntInterval([0, 2])]), True), )) def test_hash_operator_with_collections(self, contains_check, expected): assert contains_check is expected
def test_open(self): interval = IntInterval.open(12, 14, step=2) assert interval.lower == 12 assert interval.upper == 14 assert interval.is_open assert interval.step == 2
def test_integer_comparison(self): assert IntInterval([2, 2]) <= 3 assert IntInterval([1, 3]) >= 0 assert IntInterval([2, 2]) == 2 assert IntInterval([2, 2]) != 3
def test_closed(self): interval = IntInterval.closed(10, 11, step=2) assert interval.lower == 10 assert interval.upper == 12 assert interval.is_closed assert interval.step == 2
def test_contains_operator_for_non_inclusive_interval(self, value): assert value not in IntInterval((-1, 2))
def test_intersection(self, first, second, intersection): assert ( IntInterval.from_string(first) & IntInterval.from_string(second) ) == IntInterval.from_string(intersection)