def start_simulate(self, iteration): #self.log('start simulating') self.__iteration_number = iteration for _ in range(iteration): #self.log("found a new block") random_number = random.random() # Mining Process if random_number < self._alpha: self.calculating_weight(True) self.start_selfish_mining() else: self.calculating_weight(False) self.start_honest_mining() block_creation_response = self.time_window.create_a_block() if block_creation_response == BlockCreationStatus.EndTow: self.chain_evaluation() self.reset_tow() elif block_creation_response == BlockCreationStatus.EndTimeWindow: self.time_window = TimeWindow(self.tow_number, self.min_tow_block_number, self.max_tow_block_number) self.chain_evaluation() self.reset_tow() else: self.__current_block_tow += 1 self.calculating_output() return
def test_union(self): ex = self.tm_windows_examples() tests = [ (ex['Tbase'], 'Tbase', 'Tbase'), (TimeWindow(ex['Tsneigh'].since, ex['Tbase'].until), 'Tbase', 'Tsneigh'), (TimeWindow( ex['Tbase'].since, ex['Teneigh'].until, ), 'Tbase', 'Teneigh'), ([ex['Tsneigh'], ex['Teneigh']], 'Tsneigh', 'Teneigh'), (TimeWindow(ex['Tbase'].since, ex['Toverl'].until), 'Tbase', 'Toverl'), (ex['Tsupset'], 'Tbase', 'Tsupset'), (ex['Tbase'], 'Tbase', 'Tsubset'), ] for result, twname1, twname2 in tests: tw1 = ex[twname1] tw2 = ex[twname2] self.assertEqual( result, tw1.union(tw2), 'Checking "{0}".union("{1}")'.format(twname1, twname2)) self.assertEqual( result, tw1 | tw2, 'Checking "{0}".union("{1}")'.format(twname1, twname2)) self.assertEqual( result, tw2.union(tw1), 'Checking "{0}".union("{1}")'.format(twname2, twname1)) self.assertEqual( result, tw2 | tw1, 'Checking "{0}".union("{1}")'.format(twname2, twname1))
def test__repr__(self): tws = TimeWindowsCollection([ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 0, 0), timedelta(minutes=10)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 5, 0), timedelta(minutes=10)), ]) # check that it does not raise an exception print(repr(tws)) # check that it does not raise any exception with unicode str(repr(tws))
def test_fromtimedelta(self): now = datetime.now() delta = timedelta(minutes=5) tw = TimeWindow.from_timedelta(now, delta) self.assertEqual(tw.since, now) self.assertEqual(tw.until, now + delta) self.assertEqual(tw.delta, delta) # Negative case tw = TimeWindow.from_timedelta(now, -delta) self.assertEqual(tw.since, now - delta) self.assertEqual(tw.until, now) self.assertEqual(tw.delta, delta)
def test_time_window_from_timestamps(self): start = 1420063200 end = start + 120 check_tw = time_window_from_timestamps((start, end)) tw = TimeWindow(utcfromtimestamp_tzaware(start), utcfromtimestamp_tzaware(end)) self.assertEqual(check_tw, tw)
def test_time_window_to_timestamps(self): start = 1420063200 end = start + 120 tw = TimeWindow(utcfromtimestamp_tzaware(start), utcfromtimestamp_tzaware(end)) tw_timestamps = time_window_to_timestamps(tw) self.assertTupleEqual(tw_timestamps, (start, end))
def convert_to_loc_avail(self, db_loc): la = LocationAvailability() la.location_name = db_loc[HASH_KEY] if 'is_muted' in db_loc.keys(): la.is_muted = db_loc['is_muted'] if 'windows' in db_loc.keys(): for w in json.loads(db_loc['windows']): tw = TimeWindow(IsMuted=w["is_muted"], ical=w['ical'], Priority=w['priority']) la.add_window(tw) if 'last_activity' in db_loc.keys(): la.last_activity = arrow.get(db_loc['last_activity']) logging.info('Last motion was ' + la.last_activity.isoformat()) if ((arrow.utcnow() - la.last_activity).seconds > 60): la.is_motion = False else: la.is_motion = True if 'input_capabilities' in db_loc.keys(): for k in json.loads(db_loc['input_capabilities']): i = json.loads(db_loc['input_capabilities'])[k] la.add_input_capability(HardwareId=k, Name=i['name'], Color=i['color'], Style=i['style'], Type=i['type']) return la
def adjust_segments(consumption_segments: dict, weight_series: pd.Series) -> dict: """ Realign consumption segments to end one timestamp before a new product arrives on a scale and start on timestamp of product arrival. Args: consumption_segments: Dictionary of TimeWindow segments. weight_series: Weight measurements as a Pandas Series. Returns: A dictionary of adjusted TimeWindow segments. """ segments = consumption_segments.copy() for segment_index in range(len(segments) - 1): current_segment_data = create_segment_data(segments[segment_index], weight_series) next_segment_data = create_segment_data(segments[segment_index + 1], weight_series) current_end_weight = current_segment_data["end_weight"] next_start_weight = next_segment_data["start_weight"] if current_end_weight >= next_start_weight: weight_sub_range = weight_series[current_segment_data[ "min_weight_time"]:next_segment_data["end_time"]] sub_range_values = np.array(weight_sub_range.values) sub_range_times = weight_sub_range.index peaks, plateaus = signal.find_peaks(sub_range_values, plateau_size=1) first_maxima_index = peaks[0] if plateaus["left_edges"]: plateaus_left_edge = plateaus["left_edges"] first_maxima_index = np.minimum(peaks, plateaus_left_edge)[0] adjusted_current_end_time = sub_range_times[first_maxima_index - 1] adjusted_next_start_time = sub_range_times[first_maxima_index] adjusted_current_segment = TimeWindow( current_segment_data["start_time"], adjusted_current_end_time) adjusted_next_segment = TimeWindow(adjusted_next_start_time, next_segment_data["end_time"]) segments[segment_index] = adjusted_current_segment segments[segment_index + 1] = adjusted_next_segment else: continue return segments
def test_constructor(self): now = datetime.now() until = now + timedelta(minutes=5) tw = TimeWindow(now, until) self.assertEqual(now, tw.since) self.assertEqual(until, tw.until) self.assertEqual(until, tw.until) with self.assertRaises(ValueError): # Test reverse order TimeWindow(until, now) with self.assertRaises(TypeError): TimeWindow("string", until) with self.assertRaises(TypeError): TimeWindow(now, "string")
def test_compress_spatial_time_area(self): # Test empty list res = TimeWindowsCollection([]).compressed() self.assertEqual(res.time_windows, []) # Test single window tws = TimeWindowsCollection([ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 0, 0), timedelta(minutes=10)) ]) res = tws.compressed() self.assertEqual(res.time_windows, tws.time_windows) # Test two overlapping tws = TimeWindowsCollection([ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 0, 0), timedelta(minutes=10)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 5, 0), timedelta(minutes=10)), ]) res = tws.compressed() self.assertEqual(res.time_windows, [ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 0, 0), timedelta(minutes=15)), ]) # Test overlapping and contiguous tws = TimeWindowsCollection([ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 0, 0), timedelta(minutes=10)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 5, 0), timedelta(minutes=8)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 5, 0), timedelta(minutes=10)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 15, 0), timedelta(minutes=3)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 0, 0), timedelta(minutes=3)), ]) res = tws.compressed() self.assertEqual(res.time_windows, [ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 0, 0), timedelta(minutes=18)), ])
def __init__(self, tow_number, min_tow_block_number, max_tow_block_number, show_log=False): self._alpha = 0 self._gamma = 0 self.tow_number = tow_number self.min_tow_block_number = min_tow_block_number self.max_tow_block_number = max_tow_block_number self.time_window = TimeWindow(tow_number, min_tow_block_number, max_tow_block_number) self.__show_log = show_log random.seed(None) self.__public_chain_length = 0 self.__private_chain_length = 0 self.__delta = 0 self.__selfish_miners_win_block = 0 self.__honest_miners_win_block = 0 self.__selfish_miner_revenue = 0 self.__honest_miner_revenue = 0 self.__total_mined_block = 0 self.__total_stale_block = 0 self.__iteration_number = 0 self.__predicted_K = 2 self.__published = False self.__private_chain_weight = [0 for _ in range(max_tow_block_number)] self.__public_chain_weight = [0 for _ in range(max_tow_block_number)] self.__current_block_tow = 1 self.__average_tow = self.time_window.get_average_tow() self.__fork_created = False
def tm_windows_examples(self): """ Generate a set of fixed time windows with the following relationships between them. The actual time scale and point in time may vary. Tbase = |_______________| Tsneigh= |__| Teneigh= |__| Toverl = |_____________| Tsupset= |_____________________| Tsubset= |_____| """ examples = {} now = self.now examples['Tbase'] = TimeWindow.from_timedelta(now, timedelta(minutes=10)) examples['Tsneigh'] = TimeWindow.from_timedelta( examples['Tbase'].since, -timedelta(minutes=1)) examples['Teneigh'] = TimeWindow.from_timedelta( examples['Tbase'].until, timedelta(minutes=1)) examples['Toverl'] = TimeWindow.from_timedelta( examples['Tbase'].since + examples['Tbase'].delta / 2, examples['Tbase'].delta) examples['Tsupset'] = TimeWindow( examples['Tbase'].since - timedelta(minutes=1), examples['Tbase'].until + timedelta(minutes=1)) examples['Tsubset'] = TimeWindow( examples['Tbase'].since + timedelta(minutes=1), examples['Tbase'].until - timedelta(minutes=1)) return examples
def test_smallestpossible(self): ex = self.tm_windows_examples() tests = [ (ex['Tbase'], [ex['Tbase']]), (ex['Tbase'], [ex['Tbase'], ex['Tbase']]), (TimeWindow(ex['Tsneigh'].since, ex['Tbase'].until), [ex['Tbase'], ex['Tsneigh']]), (TimeWindow( ex['Tbase'].since, ex['Teneigh'].until, ), [ex['Tbase'], ex['Teneigh']]), (TimeWindow( ex['Tsneigh'].since, ex['Teneigh'].until, ), [ex['Tsneigh'], ex['Teneigh']]), (TimeWindow( ex['Tsneigh'].since, ex['Teneigh'].until, ), [ex['Tsneigh'], ex['Tbase'], ex['Teneigh']]), (TimeWindow( ex['Tbase'].since, ex['Toverl'].until, ), [ex['Toverl'], ex['Tbase']]), (ex['Tsupset'], [ex['Tsupset'], ex['Tbase']]), (ex['Tbase'], [ex['Tsubset'], ex['Tbase']]), ] for result, tw_set in tests: self.assertEqual(result, TimeWindow.smallest_possible(tw_set))
def test_hash(self): hash1 = hash( TimeWindow.from_timedelta(datetime(2015, 1, 1), timedelta(seconds=1))) for i in range(0, 2048): self.assertEqual( hash( TimeWindow.from_timedelta(datetime(2015, 1, 1), timedelta(seconds=1))), hash1) self.assertNotEqual( hash( TimeWindow.from_timedelta(datetime(2015, 1, 1), timedelta(seconds=1))), hash( TimeWindow.from_timedelta(datetime(2015, 1, 1, 1), timedelta(seconds=1)))) self.assertNotEqual( hash( TimeWindow.from_timedelta(datetime(2015, 1, 1), timedelta(seconds=1))), hash( TimeWindow.from_timedelta(datetime(2015, 1, 1), timedelta(seconds=2))))
def __init__(self): ''' obj -> None This method initializes an object ''' self.conti = True self.wrong = False self.element_1 = StartingWindow() if self.element_1.name != 'quit' and len(self.element_1.name) > 0: self.element_2 = TimeWindow() self.get_chart() self.get_rep() if self.element_2 != None: a = Represent()
def create_consumption_segments(weight_series: pd.Series, peaks: list) -> dict: """ Create and return a dictionary of time windows representing consumption segments of individual products. Args: weight_series: Weight measurements as a Pandas Series. peaks: Peaks in data as a list of time stamps. Returns: Dictionary of time_window.TimeWindows 'windows'. """ weight_schema = pas.weight_series try: weight_schema(weight_series) except pa.errors.SchemaErrors: raise time_stamps = weight_series.index consumption_segments = {} start_time_stamp = time_stamps[0] end_index = (time_stamps.get_loc(peaks[0]) - 1 ) # end the segment 1 timestamp before peak end_time_stamp = time_stamps[end_index] segment_0 = TimeWindow(start_time_stamp, end_time_stamp) consumption_segments[0] = segment_0 for index, break_point in enumerate(peaks): start_time_stamp = break_point if index < len(peaks) - 1: end_index = (time_stamps.get_loc(peaks[index + 1]) - 1 ) # end the segment 1 timestamp before peak end_time_stamp = time_stamps[end_index] else: end_time_stamp = time_stamps[-1] consumption_segments[index + 1] = TimeWindow(start_time_stamp, end_time_stamp) return consumption_segments
def test_complement(self): ex = self.tm_windows_examples() tests = [ (None, 'Tbase', 'Tbase'), (ex['Tbase'], 'Tbase', 'Tsneigh'), (ex['Tbase'], 'Tbase', 'Teneigh'), (TimeWindow(ex['Tbase'].since, ex['Toverl'].since), 'Tbase', 'Toverl'), (None, 'Tbase', 'Tsupset'), ([ TimeWindow(ex['Tbase'].since, ex['Tsubset'].since), TimeWindow(ex['Tsubset'].until, ex['Tbase'].until) ], 'Tbase', 'Tsubset'), ] for result, twname1, twname2 in tests: tw1 = ex[twname1] tw2 = ex[twname2] self.assertEqual( result, tw1.complement(tw2), 'Checking "{0}".complement("{1}")'.format(twname1, twname2)) self.assertEqual( result, tw1 - tw2, 'Checking "{0}".complement("{1}")'.format(twname1, twname2))
def helper_time_periods_to_time_window_list(self, periods): return [ TimeWindow(*list(map(utcfromtimestamp_tzaware, period))) for period in periods ]
def test_split_per_week(self): # Single time test tw = TimeWindow( datetime(2015, 1, 1, 15, 30, 40, 54), datetime(2015, 1, 1, 15, 30, 40, 54), ) self.assertEqual(tw.split_per_week(), [tw]) # Single day test tw = TimeWindow( datetime(2015, 1, 1, 15, 30, 40, 54), datetime(2015, 1, 1, 16, 4, 3, 1), ) self.assertEqual(tw.split_per_week(), [tw]) # Span one week, with period less than 7 days tw = TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 1, 3, 10)) self.assertEqual( tw.split_per_week(), [TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 1, 3, 10))]) # Span two weeks, with period greater than 7 days tw = TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 1, 11, 23, 30)) print(tw.split_per_week()) self.assertEqual(tw.split_per_week(), [ TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 1, 5, 0)), TimeWindow(datetime(2015, 1, 5, 0), datetime(2015, 1, 11, 23, 30)) ])
def test_split_per_day(self): # Single time test tw = TimeWindow( datetime(2015, 1, 1, 15, 30, 40, 54), datetime(2015, 1, 1, 15, 30, 40, 54), ) self.assertEqual(tw.split_per_day(), [tw]) # Single day test tw = TimeWindow( datetime(2015, 1, 1, 15, 30, 40, 54), datetime(2015, 1, 1, 16, 4, 3, 1), ) self.assertEqual(tw.split_per_day(), [tw]) # Span two days, with period less than 24 hours tw = TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 1, 2, 10)) self.assertEqual(tw.split_per_day(), [ TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 1, 2, 0)), TimeWindow(datetime(2015, 1, 2, 0), datetime(2015, 1, 2, 10)) ]) # Span two days, with period greater than 24 hours tw = TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 1, 2, 23, 30)) self.assertEqual(tw.split_per_day(), [ TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 1, 2, 0)), TimeWindow(datetime(2015, 1, 2, 0), datetime(2015, 1, 2, 23, 30)) ]) # A big test tw = TimeWindow( datetime(2015, 1, 1, 15, 30, 40, 54), datetime(2015, 2, 3, 5, 4, 3, 1), ) self.assertEqual(tw.split_per_day(), [ TimeWindow(datetime(2015, 1, 1, 15, 30, 40, 54), datetime(2015, 1, 2, 0, 0)), TimeWindow(datetime(2015, 1, 2, 0, 0), datetime(2015, 1, 3, 0, 0)), TimeWindow(datetime(2015, 1, 3, 0, 0), datetime(2015, 1, 4, 0, 0)), TimeWindow(datetime(2015, 1, 4, 0, 0), datetime(2015, 1, 5, 0, 0)), TimeWindow(datetime(2015, 1, 5, 0, 0), datetime(2015, 1, 6, 0, 0)), TimeWindow(datetime(2015, 1, 6, 0, 0), datetime(2015, 1, 7, 0, 0)), TimeWindow(datetime(2015, 1, 7, 0, 0), datetime(2015, 1, 8, 0, 0)), TimeWindow(datetime(2015, 1, 8, 0, 0), datetime(2015, 1, 9, 0, 0)), TimeWindow(datetime(2015, 1, 9, 0, 0), datetime(2015, 1, 10, 0, 0)), TimeWindow(datetime(2015, 1, 10, 0, 0), datetime( 2015, 1, 11, 0, 0)), TimeWindow(datetime(2015, 1, 11, 0, 0), datetime( 2015, 1, 12, 0, 0)), TimeWindow(datetime(2015, 1, 12, 0, 0), datetime( 2015, 1, 13, 0, 0)), TimeWindow(datetime(2015, 1, 13, 0, 0), datetime( 2015, 1, 14, 0, 0)), TimeWindow(datetime(2015, 1, 14, 0, 0), datetime( 2015, 1, 15, 0, 0)), TimeWindow(datetime(2015, 1, 15, 0, 0), datetime( 2015, 1, 16, 0, 0)), TimeWindow(datetime(2015, 1, 16, 0, 0), datetime( 2015, 1, 17, 0, 0)), TimeWindow(datetime(2015, 1, 17, 0, 0), datetime( 2015, 1, 18, 0, 0)), TimeWindow(datetime(2015, 1, 18, 0, 0), datetime( 2015, 1, 19, 0, 0)), TimeWindow(datetime(2015, 1, 19, 0, 0), datetime( 2015, 1, 20, 0, 0)), TimeWindow(datetime(2015, 1, 20, 0, 0), datetime( 2015, 1, 21, 0, 0)), TimeWindow(datetime(2015, 1, 21, 0, 0), datetime( 2015, 1, 22, 0, 0)), TimeWindow(datetime(2015, 1, 22, 0, 0), datetime( 2015, 1, 23, 0, 0)), TimeWindow(datetime(2015, 1, 23, 0, 0), datetime( 2015, 1, 24, 0, 0)), TimeWindow(datetime(2015, 1, 24, 0, 0), datetime( 2015, 1, 25, 0, 0)), TimeWindow(datetime(2015, 1, 25, 0, 0), datetime( 2015, 1, 26, 0, 0)), TimeWindow(datetime(2015, 1, 26, 0, 0), datetime( 2015, 1, 27, 0, 0)), TimeWindow(datetime(2015, 1, 27, 0, 0), datetime( 2015, 1, 28, 0, 0)), TimeWindow(datetime(2015, 1, 28, 0, 0), datetime( 2015, 1, 29, 0, 0)), TimeWindow(datetime(2015, 1, 29, 0, 0), datetime( 2015, 1, 30, 0, 0)), TimeWindow(datetime(2015, 1, 30, 0, 0), datetime( 2015, 1, 31, 0, 0)), TimeWindow(datetime(2015, 1, 31, 0, 0), datetime(2015, 2, 1, 0, 0)), TimeWindow(datetime(2015, 2, 1, 0, 0), datetime(2015, 2, 2, 0, 0)), TimeWindow(datetime(2015, 2, 2, 0, 0), datetime(2015, 2, 3, 0, 0)), TimeWindow(datetime(2015, 2, 3, 0, 0), datetime(2015, 2, 3, 5, 4, 3, 1)) ])
class NikSelfishMining: def __init__(self, tow_number, min_tow_block_number, max_tow_block_number, show_log=False): self._alpha = 0 self._gamma = 0 self.tow_number = tow_number self.min_tow_block_number = min_tow_block_number self.max_tow_block_number = max_tow_block_number self.time_window = TimeWindow(tow_number, min_tow_block_number, max_tow_block_number) self.__show_log = show_log random.seed(None) self.__public_chain_length = 0 self.__private_chain_length = 0 self.__delta = 0 self.__selfish_miners_win_block = 0 self.__honest_miners_win_block = 0 self.__selfish_miner_revenue = 0 self.__honest_miner_revenue = 0 self.__total_mined_block = 0 self.__total_stale_block = 0 self.__iteration_number = 0 self.__predicted_K = 2 self.__published = False self.__private_chain_weight = [0 for _ in range(max_tow_block_number)] self.__public_chain_weight = [0 for _ in range(max_tow_block_number)] self.__current_block_tow = 1 self.__average_tow = self.time_window.get_average_tow() self.__fork_created = False @property def alpha(self): return self._alpha @alpha.setter def alpha(self, value): if value < 0 or value > 0.5: raise Exception("invalid value for alpha!") self._alpha = value return @property def gamma(self): return self._gamma @gamma.setter def gamma(self, value): if value < 0 or value > 1: raise Exception("invalid value for gamma!") self._gamma = value return def print_input_statistic(self): print('alpha is : {}'.format(self._alpha)) print('gamma is : {}'.format(self._gamma)) return def start_simulate(self, iteration): #self.log('start simulating') self.__iteration_number = iteration for _ in range(iteration): #self.log("found a new block") random_number = random.random() # Mining Process if random_number < self._alpha: self.calculating_weight(True) self.start_selfish_mining() else: self.calculating_weight(False) self.start_honest_mining() block_creation_response = self.time_window.create_a_block() if block_creation_response == BlockCreationStatus.EndTow: self.chain_evaluation() self.reset_tow() elif block_creation_response == BlockCreationStatus.EndTimeWindow: self.time_window = TimeWindow(self.tow_number, self.min_tow_block_number, self.max_tow_block_number) self.chain_evaluation() self.reset_tow() else: self.__current_block_tow += 1 self.calculating_output() return def start_selfish_mining(self): #self.log('starting selfish mining!') self.__private_chain_length += 1 self.calculating_delta() if self.__published: self.__selfish_miners_win_block += 1 return if self.__delta < self.__predicted_K / 2 and self.__current_block_tow > self.__average_tow * 0.8: # self.log('1') self.__published = True return def start_honest_mining(self): # self.log('starting honest mining!') if self.__delta == 0 and self.__private_chain_length == 0: self.__honest_miners_win_block += 1 return self.__public_chain_length += 1 self.calculating_delta() if self.__published: return if self.__current_block_tow > self.__average_tow * 0.8: if self.__delta == self.__predicted_K - 1: # self.log('2') # Risk & Continue to mine return elif self.__delta == self.__predicted_K - 2: # self.log('3') # self.__published = True return else: # self.log('4') self.__published = True return else: # self.log('5') # Risk & Continue to mine return def calculating_delta(self): self.__delta = self.__private_chain_length - self.__public_chain_length # self.log('delta is : {}'.format(self.__delta)) return def calculating_weight(self, is_private_block): if is_private_block: if self.__public_chain_weight[self.__private_chain_length] == 0: self.__private_chain_weight[self.__private_chain_length] = 1 else: if self.__private_chain_weight[ self. __public_chain_length] == 0 and self.__fork_created == True: self.__public_chain_weight[self.__public_chain_length] = 1 return def chain_evaluation(self): if self.__private_chain_length - self.__public_chain_length >= self.__predicted_K: # Decision based on Length self.__selfish_miners_win_block += self.__private_chain_length elif self.__public_chain_length - self.__private_chain_length >= self.__predicted_K: # Decision based on Length self.__honest_miners_win_block += self.__public_chain_length else: # Decision based on Wight private_chain_weight = sum(self.__private_chain_weight) public_chain_weight = sum(self.__public_chain_weight) if private_chain_weight > public_chain_weight: self.__selfish_miners_win_block += self.__private_chain_length elif public_chain_weight > private_chain_weight: self.__honest_miners_win_block += self.__public_chain_length else: random_number = random.random() if random_number < 0.5: self.__selfish_miners_win_block += self.__private_chain_length else: self.__honest_miners_win_block += self.__public_chain_length return def calculating_output(self): self.__total_mined_block = self.__honest_miners_win_block + \ self.__selfish_miners_win_block self.__total_stale_block = self.__iteration_number - self.__total_mined_block self.__honest_miner_revenue = float( self.__honest_miners_win_block / self.__total_mined_block) * 100 self.__selfish_miner_revenue = float( self.__selfish_miners_win_block / self.__total_mined_block) * 100 return def print_final_result(self): print('********************************************') self.print_input_statistic() print('honest miners win block is : {}'.format( self.__honest_miners_win_block)) print('selfish miners win block is : {}'.format( self.__selfish_miners_win_block)) print('total mined block is : {}'.format(self.__total_mined_block)) print('total stale block is : {}'.format(self.__total_stale_block)) print('honest miner revenue is : {}'.format( self.__honest_miner_revenue)) print('selfish miner revenue is : {}'.format( self.__selfish_miner_revenue)) print('honest miner expected reward is : {}'.format( (1 - self.alpha) * self.__iteration_number * 100 / self.__iteration_number)) print('selfish miner expected reward is : {}'.format( (self.alpha) * self.__iteration_number * 100 / self.__iteration_number)) print('********************************************') return def log(self, log_message): if self.__show_log: print(log_message) return def reset_tow(self): self.__published = False self.__private_chain_weight = [ 0 for _ in range(self.max_tow_block_number) ] self.__public_chain_weight = [ 0 for _ in range(self.max_tow_block_number) ] self.__current_block_tow = 1 self.__private_chain_length = 0 self.__public_chain_length = 0 def reset(self): random.seed(None) self.__public_chain_length = 0 self.__private_chain_length = 0 self.__delta = 0 self.__selfish_miners_win_block = 0 self.__honest_miners_win_block = 0 self.__selfish_miner_revenue = 0 self.__honest_miner_revenue = 0 self.__total_mined_block = 0 self.__total_stale_block = 0 self.__iteration_number = 0 return def visualize_data(self, iteration_number): alpha_values = [x / 100 for x in range(51) if x % 5 == 0] selfish_revenue_value_0 = [] selfish_revenue_value_0_5 = [] selfish_revenue_value_1 = [] honest_revenue_value = [] for alpha in alpha_values: self.alpha = alpha self.gamma = 0 self.start_simulate(iteration_number) self.print_final_result() selfish_revenue_value_0.append(self.__selfish_miner_revenue) self.reset() for alpha in alpha_values: self.alpha = alpha self.gamma = 0.5 self.start_simulate(iteration_number) self.print_final_result() selfish_revenue_value_0_5.append(self.__selfish_miner_revenue) self.reset() for alpha in alpha_values: self.alpha = alpha self.gamma = 1 self.start_simulate(iteration_number) self.print_final_result() selfish_revenue_value_1.append(self.__selfish_miner_revenue) self.reset() for alpha in alpha_values: honest_revenue_value.append(alpha * 100) plt.plot(alpha_values, selfish_revenue_value_0, color='r', label='gamma = 0') plt.plot(alpha_values, selfish_revenue_value_0_5, color='y', label='gamma = 0.5') plt.plot(alpha_values, selfish_revenue_value_1, color='g', label='gamma = 1') plt.plot(alpha_values, honest_revenue_value, color='k', label='honest mining') plt.title('Nik Selfish Mining') plt.xlabel('Pool size') plt.ylabel('Relative Revenue') plt.legend(loc="upper left") plt.show()
def test_split_per_month(self): # Single time test tw = TimeWindow( datetime(2015, 1, 1, 15, 30, 40, 54), datetime(2015, 1, 1, 15, 30, 40, 54), ) self.assertEqual(tw.split_per_month(), [tw]) # Single day test tw = TimeWindow( datetime(2015, 1, 1, 15, 30, 40, 54), datetime(2015, 1, 1, 16, 4, 3, 1), ) self.assertEqual(tw.split_per_month(), [tw]) # Span one month, with period less than 30 days tw = TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 1, 15, 10)) self.assertEqual( tw.split_per_month(), [TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 1, 15, 10))]) # Span two months, with period greater than 30 days tw = TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 2, 5, 23, 30)) self.assertEqual(tw.split_per_month(), [ TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 2, 1, 0, 0)), TimeWindow(datetime(2015, 2, 1, 0, 0), datetime( 2015, 2, 5, 23, 30)) ]) # Span three months, with period greater than 30 days tw = TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 3, 5, 23, 30)) self.assertEqual(tw.split_per_month(), [ TimeWindow(datetime(2015, 1, 1, 23), datetime(2015, 2, 1, 0, 0)), TimeWindow(datetime(2015, 2, 1, 0, 0), datetime(2015, 3, 1, 0, 0)), TimeWindow(datetime(2015, 3, 1, 0, 0), datetime( 2015, 3, 5, 23, 30)) ]) # Span three months, with period greater than 30 days, # starting from the middle of the first month tw = TimeWindow(datetime(2015, 1, 15, 5), datetime(2015, 3, 6, 15)) self.assertEqual(tw.split_per_month(), [ TimeWindow(datetime(2015, 1, 15, 5, 0), datetime(2015, 2, 1, 0, 0)), TimeWindow(datetime(2015, 2, 1, 0, 0), datetime(2015, 3, 1, 0, 0)), TimeWindow(datetime(2015, 3, 1, 0, 0), datetime(2015, 3, 6, 15, 0)) ]) # Span five months, with period greater than 30 days, # starting from the 10th day of the first month tw = TimeWindow(datetime(2015, 5, 10, 5), datetime(2015, 7, 23, 15)) self.assertEqual(tw.split_per_month(), [ TimeWindow(datetime(2015, 5, 10, 5, 0), datetime(2015, 6, 1, 0, 0)), TimeWindow(datetime(2015, 6, 1, 0, 0), datetime(2015, 7, 1, 0, 0)), TimeWindow(datetime(2015, 7, 1, 0, 0), datetime( 2015, 7, 23, 15, 0)) ]) # Span two months, with period less than 30 days, # starting from December tw = TimeWindow(datetime(2015, 12, 15, 5), datetime(2016, 1, 6, 15)) self.assertEqual(tw.split_per_month(), [ TimeWindow(datetime(2015, 12, 15, 5, 0), datetime( 2016, 1, 1, 0, 0)), TimeWindow(datetime(2016, 1, 1, 0, 0), datetime(2016, 1, 6, 15, 0)) ])
def __init__(self, wechat_id): BaseCheckin.__init__(self, wechat_id) self.class_list = self.init_class_records() self.enter_time = time.strftime('%H:%M') self.section_id = self.init_section_id(self.enter_time) self.time_window = TimeWindow()
class AutoCheckin(BaseCheckin): def __init__(self, wechat_id): BaseCheckin.__init__(self, wechat_id) self.class_list = self.init_class_records() self.enter_time = time.strftime('%H:%M') self.section_id = self.init_section_id(self.enter_time) self.time_window = TimeWindow() def __str__(self): dic = {} dic['index'] = str(BaseCheckin.checkin_list.index(self)) dic['tea_id'] = self.tea_id dic['crs_id'] = self.crs_id dic['seq_id'] = self.seq_id dic['wechat_id'] = self.wechat_id dic['class_list'] = self.class_list dic['enter_time'] = self.enter_time dic['section_time'] = self.section_id dic['time_window'] = self.time_window def init_section_id(self, nowtime): t = ReadIni() nowtime = int(''.join(nowtime.split(':'))) for i in range(0, 8): e = int(''.join(t.begin_time_list[i]['EndTime'].split(':'))) s = int(''.join(t.begin_time_list[i]['StartTime'].split(':'))) if (nowtime >= s) & (nowtime <= e): return i + 1 else: return 0 def init_detail_records(self): stu_records = self.init_student_records() temp_list = [] for stu_rec in stu_records: temp_dict = { 'StuID': stu_rec['StuID'], 'checkinTime': time.strftime('%Y-%m-%d %H:%M:%S'), 'ProofPath': 'Auto', 'checkinType': 'Auto', 'IsSuc': 'False', 'checkinResult': '缺勤' } temp_list.append(temp_dict) print PrtInfo.successMessage(3) return temp_list def entry_list(self): # self.enter_time = '8:30' class_list = self.init_class_records() intersection_flag = False # 全局队列为空: if BaseCheckin.checkin_list == []: print PrtInfo.successMessage(7) BaseCheckin.checkin_list.append(self) self.time_window.start_timing() return True # 非空 kick_head = False for checkin_obj in BaseCheckin.checkin_list[:]: try: if set(class_list) & set(checkin_obj.class_list): # 存在交集 # 节次不一样 踢掉 if self.section_id != checkin_obj.section_id: intersection_flag = True if BaseCheckin.checkin_list.index(checkin_obj) == 0: # 踢掉的是队首 kick_head = True checkin_obj.notify() BaseCheckin.checkin_list.remove(checkin_obj) # 节次一样,无法进入,退出函数 else: return False except TypeError: print 'invalid operation' return False # 队列中的所有班都与来者没有交集,或者有交集被踢出去 if (intersection_flag == False) | (kick_head == False): # 没有交集 或者 踢掉的不是队首 self.time_window.just_waiting() BaseCheckin.checkin_list.append(self) elif (intersection_flag == True) & (kick_head == True) & \ (BaseCheckin.checkin_list.__len__() != 0): # 有交集 且 踢掉的是队首 且 当前者不是队首 print PrtInfo.successMessage(7) BaseCheckin.checkin_list.append(self) t2 = BaseCheckin.checkin_list[0].enter_time t3 = BaseCheckin.checkin_list[1].enter_time self.time_window.time_second(t2, t3) else: # 有交集 且 踢掉队首 且 自己是队首 print PrtInfo.successMessage(6) BaseCheckin.checkin_list.append(self) self.time_window.start_timing() def get_stu_id_in_class_list(self, wechat_id): student_records = self.init_student_records() for stu_rec in student_records: if stu_rec['WeChatID'] == wechat_id: return stu_rec['StuID'] else: print PrtInfo.notFoundMessage(3) return None def upload_path(self): return raw_input(PrtInfo.promptMessage(5)) def judge_result(self, proof_path): # isLate(time) # isHere(path) # isYourself(path) i = random.randrange(0, 2) if i is 0: return 'True' if i is 1: return 'False' def cancel_leave(self, stu_id): dict = { 'StuID': stu_id, 'checkinTime': time.strftime('%Y-%m-%d %H:%M:%S'), 'ProofPath': '', 'checkinType': 'Auto', 'IsSuc': 'False', 'checkinResult': '' } DetailFile(self.init_detail_name(self.tea_id, self.crs_id, self.seq_id)). \ write_file([dict], 'ab') print 'please finish your check in' def get_detail_record(self, checkin_type, stu_id): checkin_result = None if raw_input("enter 'y' to ask for leave") == 'y': checkin_result = '假条提交' print 'the leave permission uploaded' proof = self.upload_path() judge_result = 'True' else: proof = self.upload_path() judge_result = self.judge_result(proof) if judge_result != 'True': print "you are not 'here' or you are not 'you'" return { 'StuID': stu_id, 'checkinTime': time.strftime('%Y-%m-%d %H:%M:%S'), 'ProofPath': proof, 'checkinType': checkin_type, 'IsSuc': judge_result, 'checkinResult': checkin_result } def get_latest_record(self, stu_id, checkin_type): detail_rec = {} detail_records = BaseFile.read_file( self.init_detail_name(self.tea_id, self.crs_id, self.seq_id)) for rec in detail_records: if (rec['StuID'] == str(stu_id)) & (rec['checkinType'] == str(checkin_type)): detail_rec = rec return detail_rec def init_new_detail_record(self, wechat_id, checkin_type): # 先判断最新记录是否是True stu_id = self.get_stu_id_in_class_list(wechat_id) rec = self.get_latest_record(stu_id, checkin_type) if rec == {}: DetailFile(self.init_detail_name(self.tea_id, self.crs_id, self.seq_id)). \ write_file([self.get_detail_record(checkin_type, stu_id)], 'ab') return elif rec['IsSuc'] != 'True': DetailFile(self.init_detail_name(self.tea_id, self.crs_id, self.seq_id)). \ write_file([self.get_detail_record(checkin_type, stu_id)], 'ab') return else: return def start_checkin(self): self.attach(EndcheckinObserver(self)) self.attach(TimeWindowObserver(self)) if self.entry_list() is not False: self.write_detail_file([]) self.update_sum_by_certain_seq_id(self.seq_id) self.add_seq_id(self.seq_id) # 在seq文件中保存此次seq id 记录 def join_checkin(self, wechat_id): if self in BaseCheckin.checkin_list: checkin_type = raw_input(PrtInfo.promptMessage(6)) if checkin_type == 'Auto': self.init_new_detail_record(wechat_id, 'Auto') PrtInfo.successMessage(8) return True elif checkin_type == 'Random': random_list = self.get_random_list() if random_list == []: print 'No random check in now' return False if self.get_stu_id_in_class_list(wechat_id) not in random_list: print PrtInfo.notFoundMessage(4) return False else: self.init_new_detail_record(wechat_id, 'Random') PrtInfo.successMessage(8) else: print PrtInfo.failedMessage(1) else: print PrtInfo.failedMessage(0) return False def get_random_list(self): records = BaseFile.read_file( self.init_detail_name(self.tea_id, self.crs_id, self.seq_id)) random_list = [] for rec in records: if rec['checkinType'] == 'Random' and rec[ 'checkinResult'] == 'init': random_list.append(rec['StuID']) return random_list def start_random_checkin(self, num): student_records = self.init_student_records() temp_list = random.sample(student_records, num) for line in student_records: if line in temp_list: temp_dict = { 'StuID': line['StuID'], 'checkinTime': time.strftime('%Y-%m-%d %H:%M:%S'), 'ProofPath': 'Auto', 'checkinType': 'Random', 'IsSuc': 'none', 'checkinResult': 'init' } DetailFile( self.init_detail_name(self.tea_id, self.crs_id, self.seq_id)).write_file([temp_dict], 'ab') def is_late(self, rec): checkin_time = ((rec['checkinTime'].split(' '))[1])[0:5] dev = int(self.time_window.dev(self.enter_time, checkin_time)) t = ReadIni() if dev < t.read_late_dev(): return '出勤' else: return '迟到' def get_compared_record(self, auto_rec, ran_rec, is_late): if auto_rec['IsSuc'] == ran_rec['IsSuc']: checkin_result = '出勤' if auto_rec['IsSuc'] == 'True' else '缺勤' auto_rec['checkinResult'] = checkin_result else: t1 = ((auto_rec['checkinTime'].split(' '))[1])[0:5] t2 = ((ran_rec['checkinTime'].split(' '))[1])[0:5] dev_time = int(self.time_window.dev(t1, t2)) if is_late: if auto_rec['IsSuc'] == 'False' and dev_time > 0: auto_rec.update({'checkinResult': '早退'}) else: auto_rec.update({'checkinResult': '迟到'}) else: if auto_rec['IsSuc'] == 'True' and dev_time < 0: auto_rec.update({'checkinResult': '出勤'}) else: auto_rec.update({'checkinResult': '早退'}) return auto_rec def exit_checkin(self): pass def end_checkin(self): detail_file = DetailFile( self.init_detail_name(self.tea_id, self.crs_id, self.seq_id)) for stu in self.init_student_records(): auto_rec = self.get_latest_record(stu['StuID'], 'Auto') ran_rec = self.get_latest_record(stu['StuID'], 'Random') # 没有签到的学生 缺勤 追加到文件中 if auto_rec == {}: if ran_rec == {}: auto_rec = { 'StuID': stu['StuID'], 'checkinTime': time.strftime('%Y-%m-%d %H:%M:%S'), 'ProofPath': 'none', 'checkinType': 'Auto', 'IsSuc': 'False', 'checkinResult': '缺勤' } detail_file.write_file([auto_rec], 'ab') continue else: auto_rec = ran_rec # 签到 并且来的学生 检查是否请假 if auto_rec != {} and auto_rec['checkinResult'] == '假条提交': continue # 得到迟到标记,自助考勤最新记录,抽点考勤最新记录 if ran_rec == {}: if auto_rec['IsSuc'] == 'True': auto_rec.update({'checkinResult': self.is_late(auto_rec)}) else: auto_rec.update({'checkinResult': '缺勤'}) detail_file.write_file([auto_rec], 'ab') continue else: is_late = True if self.is_late(auto_rec) == '迟到' else False auto_rec = self.get_compared_record(auto_rec, ran_rec, is_late) detail_file.write_file([auto_rec], 'ab') ManCheckin.confirm_leave(self, detail_file) self.update_sum()
def test_bug_compress_spatial_time_area(self): # This case was captured live on debugger. tws = TimeWindowsCollection([ TimeWindow(datetime(2015, 3, 4, 16, 40, 31, 0), datetime(2015, 3, 4, 16, 41, 31, 0)), TimeWindow(datetime(2015, 3, 4, 16, 43, 44, 0), datetime(2015, 3, 4, 16, 44, 44, 0)), TimeWindow(datetime(2015, 3, 4, 16, 43, 57, 0), datetime(2015, 3, 4, 16, 44, 57, 0)), TimeWindow(datetime(2015, 3, 4, 16, 44, 9, 0), datetime(2015, 3, 4, 16, 45, 9, 0)), TimeWindow(datetime(2015, 3, 4, 16, 44, 22, 0), datetime(2015, 3, 4, 16, 45, 22, 0)), TimeWindow(datetime(2015, 3, 4, 16, 44, 35, 0), datetime(2015, 3, 4, 16, 45, 35, 0)), TimeWindow(datetime(2015, 3, 4, 16, 46, 23, 0), datetime(2015, 3, 4, 16, 47, 23, 0)), TimeWindow(datetime(2015, 3, 4, 16, 46, 40, 0), datetime(2015, 3, 4, 16, 47, 40, 0)), TimeWindow(datetime(2015, 3, 4, 16, 46, 56, 0), datetime(2015, 3, 4, 16, 47, 56, 0)), TimeWindow(datetime(2015, 3, 4, 16, 47, 12, 0), datetime(2015, 3, 4, 16, 48, 12, 0)), TimeWindow(datetime(2015, 3, 4, 16, 47, 28, 0), datetime(2015, 3, 4, 16, 48, 28, 0)), TimeWindow(datetime(2015, 3, 4, 16, 47, 44, 0), datetime(2015, 3, 4, 16, 48, 44, 0)) ]) res = tws.compressed() self.assertEqual(res.time_windows, [ TimeWindow(datetime(2015, 3, 4, 16, 40, 31), datetime(2015, 3, 4, 16, 41, 31)), TimeWindow(datetime(2015, 3, 4, 16, 43, 44), datetime(2015, 3, 4, 16, 45, 35)), TimeWindow(datetime(2015, 3, 4, 16, 46, 23), datetime(2015, 3, 4, 16, 48, 44)) ])
def test_property_middle(self): now = datetime.now() until = now + timedelta(minutes=10) tw = TimeWindow(now, until) self.assertEqual(tw.middle, now + timedelta(minutes=5))
def test_complement_spatial_time_area(self): period = TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 0, 0), timedelta(hours=1)) # Test on empty list res = TimeWindowsCollection([]).complement(period) self.assertEqual(res.time_windows, [period]) # Test on single included time window tws = TimeWindowsCollection([ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 10, 0), timedelta(minutes=10)) ]) res = tws.complement(period) self.assertEqual(res.time_windows, [ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 0, 0), timedelta(minutes=10)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 20, 0), timedelta(minutes=40)), ]) # Test on single boundary-snapped time window tws = TimeWindowsCollection([ TimeWindow.from_timedelta(datetime(2015, 0o2, 19, 1, 0, 0), timedelta(minutes=10)) ]) res = tws.complement(period) self.assertEqual(res.time_windows, [ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 10, 0), timedelta(minutes=50)), ]) # Test on single partially included time window tws = TimeWindowsCollection([ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 50, 0), timedelta(minutes=20)) ]) res = tws.complement(period) self.assertEqual(res.time_windows, [ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 0, 0), timedelta(minutes=50)), ]) # Test on multiple compressed and ordered time windows tws = TimeWindowsCollection([ TimeWindow.from_timedelta(datetime(2015, 2, 19, 0, 50, 0), timedelta(minutes=20)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 20, 0), timedelta(minutes=5)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 50, 0), timedelta(minutes=20)) ]) res = tws.complement(period) self.assertEqual(res.time_windows, [ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 10, 0), timedelta(minutes=10)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 25, 0), timedelta(minutes=25)), ]) # Test on multiple non-compressed and un-ordered time windows tws = TimeWindowsCollection([ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 20, 0), timedelta(minutes=5)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 50, 0), timedelta(minutes=20)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 0, 52, 0), timedelta(minutes=18)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 0, 52, 0), timedelta(minutes=8)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 0, 50, 0), timedelta(minutes=5)), ]) res = tws.complement(period) self.assertEqual(res.time_windows, [ TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 10, 0), timedelta(minutes=10)), TimeWindow.from_timedelta(datetime(2015, 2, 19, 1, 25, 0), timedelta(minutes=25)), ])