Exemplo n.º 1
0
 def __init__(self, x=50, y=50, scale=10):
     super(ShowSavedDate, self).__init__(x, y, scale)
     self.statistic = Statistic()
     self.snapshots = self.statistic.read_snapshots(file="dump.txt")
     self.snapshot_generator = self.all_snapshots()
     self.key = None
     self.cells = []
Exemplo n.º 2
0
    def __init__(self, my_lambda=0, file_name="dump.txt"):
        super().__init__()
        statistic = Statistic(output=file_name)
        x, y, self.m = statistic.get_training_set()

        self.X = x[:, :]
        self.Y = y[:]

        self.m = len(self.Y)
        self.output_layer_size = 3

        # reading the data
        # data = loadmat('ex4data1.mat')
        # self.X = data['X'][0:500, :]
        # self.Y = data['y'][0:500, :]
        # self.m = len(self.Y)
        # self.output_layer_size = 10

        self.my_lambda = my_lambda
        self.input_layer_size = self.X.shape[1]
        self.internal_layer_size = 25

        self.theta1 = None
        self.theta2 = None
        self.w1 = None
        self.w2 = None
        self.weights = None
        self.j = []
        self._randomize_thetas()
Exemplo n.º 3
0
    def __init__(self, sensors_list, target_list, sensor_range, paint):
        """
		:param sensors_list:lista obiektów typu Sensor
		:param sensing_range:
		:param targets_list:pytanie czy będziemy obserwować cele czy jakiś obszar
		jeśli obszar to parametr jest niepotrzebny
		:param duration: czas trwania symulacji (czas życia sieci sensorowej)
		:param paint: obiekt łączący z interfacem, uaktualnia ekran
		z symulacja, najlepiej użyj self.paint.paint(self)
		za każdym razem kiedy włączysz lub wyłączysz jakiś sensor,
		możesz też użyć tej funkcji np. w jakiejś głównej pętli symulacji
		:param percent_observed_targets: procent obserwowanych celów
		"""
        self.start = time.time()
        self.sensor_list = sensors_list  #type: list[Sensor]
        self.target_list = target_list  #type: list[Target]
        self.statistics = Statistic(target_list,
                                    sensors_list)  # type: Statistic
        self.duration = 0
        self.paint = paint
        self.percent_observed_targets = 0
        self.sensor_range = sensor_range
        self.compute_sensors_targets(self.sensor_list)
        self.fields_list = []  #type:list[Field]
        #zliczam targety zanim usunę z listy wszystkie te które nie są pokryte
        self.target_number = len(self.target_list)
        self.old_list = self.target_list.copy()
        self.target_list = list(
            filter(lambda x: len(x.covering_sensors) != 0, self.target_list))
        self.build_fields_list(self.target_list)

        self.q = 90
Exemplo n.º 4
0
 def __init__(self, class_range=3, file_name="", my_lambda=1):
     self.X = None
     self.Y = None
     self.weights = None
     self.class_range = class_range
     self.my_lambda = my_lambda
     self.cost_data = [[], [], []]
     self.stat = Statistic(output=file_name)
     self.X, self.Y, self.m = self.stat.get_training_set()
     self.weights = np.zeros([self.class_range, self.X.shape[1]])
Exemplo n.º 5
0
    def __init__(self, x, y, ai=None, auto=False, scale=10):
        self.snake = Snake(x // 2, y // 2)
        self.fruit = None
        super(SnakeGame, self).__init__(x, y, scale)

        self.run = False
        self.key = None
        self.prev_key = None
        self.prev_fruit = None
        self.ai = ai
        self.auto = auto
        self.statistic = Statistic()
        self.set_fruit()
        self.snapshot = None
        self.timer_delta = 0
Exemplo n.º 6
0
class ShowSavedDate(Window):
    def __init__(self, x=50, y=50, scale=10):
        super(ShowSavedDate, self).__init__(x, y, scale)
        self.statistic = Statistic()
        self.snapshots = self.statistic.read_snapshots(file="dump.txt")
        self.snapshot_generator = self.all_snapshots()
        self.key = None
        self.cells = []

    def all_snapshots(self):
        for snapshot in self.snapshots:
            yield snapshot

    def keyPressEvent(self, event):
        self.key = event.key()

    def timerEvent(self, event):
        if self.key == Qt.Key_Space:
            snapshot = next(self.snapshot_generator)
            self.cells = []
            for i in range(snapshot['x']):
                for j in range(snapshot['y']):
                    if snapshot['map'][i][j] == 1 or snapshot['map'][i][j] == 2:
                        self.cells.append((i, j, Qt.green))
                    elif snapshot['map'][i][j] == 4:
                        self.cells.append((i, j, Qt.red))
            self.setWindowTitle("Current %s, Next %s" %
                                (KEYS[snapshot['current_direction']],
                                 KEYS[snapshot['next_direction']]))

        self.openGL.animate(self.cells)
        self.key = None
Exemplo n.º 7
0
class LogisticRegression(object):

    def __init__(self, class_range=3, file_name="", my_lambda=1):
        self.X = None
        self.Y = None
        self.weights = None
        self.class_range = class_range
        self.my_lambda = my_lambda
        self.cost_data = [[], [], []]
        self.stat = Statistic(output=file_name)
        self.X, self.Y, self.m = self.stat.get_training_set()
        self.weights = np.zeros([self.class_range, self.X.shape[1]])

    def cost_function(self, initial_theta, X, y, i):
        zero_theta = initial_theta.copy()
        zero_theta[0] = 0
        reg = (self.my_lambda * np.power(zero_theta, 2).sum())/2
        sig = sigmoid(np.matmul(X, initial_theta))
        cost = (-np.matmul(np.transpose(y), np.log(sig)) - np.matmul(np.transpose(1 - y), np.log(1 - sig)) + reg) / self.m
        self.cost_data[i].append(cost)

        return cost

    def gradient(self, initial_theta, X, y, i):
        zero_theta = initial_theta.copy()
        zero_theta[0] = 0
        sig = sigmoid(np.matmul(X, initial_theta))
        reg = self.my_lambda * zero_theta
        grad = (np.matmul(np.transpose(X), sig - y) + reg) / self.m
        return grad

    def optimize_one(self, index):
        initial_theta = np.zeros(len(self.weights[index]))
        y = self.Y == index
        y = y.astype(int)
        result = op.minimize(fun=self.cost_function,
                             x0=initial_theta,
                            args=(self.X, y, index),
                            method='TNC',
                            jac=self.gradient)
        print(result)
        return result.x

    def optimize(self):
        t = list()
        for i in range(self.class_range):
            t.append(self.optimize_one(i))

        self.weights = np.asarray(t)
        return self.weights

    def predict(self, x):
        w = np.matmul(self.weights, x).tolist()
        print(w, w.index(max(w)))
        return w.index(max(w))
Exemplo n.º 8
0
    def timerEvent(self, event):
        if not self.run and self.key:
            self.run = True

        if self.auto:
            if self.key and self.ai.weights is not None:
                np_array_map = Statistic.create_map(self.snake, self.fruit,
                                                    self.x, self.y)
                obstacles = Statistic.snapshot_prepare_data_1(
                    np_array_map, self.snake.current_key)
                move = self.ai.predict(obstacles)
                self.key = keys_mapping.mapping_3_to_4(
                    next_move=move,
                    current_key=self.key,
                    previous_key=self.prev_key)
            else:
                self.key = random.choice(
                    (Qt.Key_Right, Qt.Key_Left, Qt.Key_Up, Qt.Key_Down))

        if self.prev_fruit:
            self.snapshot = Statistic.create_snapshot(
                current_direction=self.snake.current_key,
                next_direction=self.key,
                snake=self.snake,
                fruit=self.prev_fruit,
                x=self.x,
                y=self.y)
            self.prev_fruit = None
        else:
            self.snapshot = Statistic.create_snapshot(
                current_direction=self.snake.current_key,
                next_direction=self.key,
                snake=self.snake,
                fruit=self.fruit,
                x=self.x,
                y=self.y)

        self.snake.move(self.key)
        if self.snake.collapse(x, y):
            self.killTimer(self.timer_id)

            self.run = False
            self.fruit = None
            self.key = None
            self.prev_key = None
            self.setWindowTitle("Game over")

            time.sleep(2)

            self.setWindowTitle("Snake")
            self.snake = Snake(self.x // 2, self.y // 2)
            self.set_fruit()
            self.timer = DEFAULT_TIMER
            self.timer_id = self.startTimer(self.timer)

        if self.snake.check_fruit(self.fruit):
            self.prev_fruit = deepcopy(self.fruit)
            self.set_fruit()
            self.killTimer(self.timer_id)
            self.timer = max(DEFAULT_TIMER, self.timer - self.timer_delta)
            self.timer_id = self.startTimer(self.timer)

        if self.run and not self.auto:
            self.statistic.save_snapshot(self.snapshot)

        self.prev_key = self.key

        cells = [(cell.x, cell.y, Qt.green) for cell in self.snake]
        cells.append((self.fruit.x, self.fruit.y, Qt.red))
        self.openGL.animate(cells)
Exemplo n.º 9
0
class SnakeGame(Window):
    def __init__(self, x, y, ai=None, auto=False, scale=10):
        self.snake = Snake(x // 2, y // 2)
        self.fruit = None
        super(SnakeGame, self).__init__(x, y, scale)

        self.run = False
        self.key = None
        self.prev_key = None
        self.prev_fruit = None
        self.ai = ai
        self.auto = auto
        self.statistic = Statistic()
        self.set_fruit()
        self.snapshot = None
        self.timer_delta = 0

    def keyPressEvent(self, event):
        if not self.auto and self.fruit is not None:
            self.key = event.key()

    def set_fruit(self):
        self.fruit = Cell(3, 0)
        return
        self.fruit = None
        while not self.fruit:
            self.fruit = Cell(random.randrange(0, self.x),
                              random.randrange(0, self.y))
            for cell in self.snake:
                if cell.x == self.fruit.x and cell.y == self.fruit.y:
                    self.fruit = None
                    break

    def timerEvent(self, event):
        if not self.run and self.key:
            self.run = True

        if self.auto:
            if self.key and self.ai.weights is not None:
                np_array_map = Statistic.create_map(self.snake, self.fruit,
                                                    self.x, self.y)
                obstacles = Statistic.snapshot_prepare_data_1(
                    np_array_map, self.snake.current_key)
                move = self.ai.predict(obstacles)
                self.key = keys_mapping.mapping_3_to_4(
                    next_move=move,
                    current_key=self.key,
                    previous_key=self.prev_key)
            else:
                self.key = random.choice(
                    (Qt.Key_Right, Qt.Key_Left, Qt.Key_Up, Qt.Key_Down))

        if self.prev_fruit:
            self.snapshot = Statistic.create_snapshot(
                current_direction=self.snake.current_key,
                next_direction=self.key,
                snake=self.snake,
                fruit=self.prev_fruit,
                x=self.x,
                y=self.y)
            self.prev_fruit = None
        else:
            self.snapshot = Statistic.create_snapshot(
                current_direction=self.snake.current_key,
                next_direction=self.key,
                snake=self.snake,
                fruit=self.fruit,
                x=self.x,
                y=self.y)

        self.snake.move(self.key)
        if self.snake.collapse(x, y):
            self.killTimer(self.timer_id)

            self.run = False
            self.fruit = None
            self.key = None
            self.prev_key = None
            self.setWindowTitle("Game over")

            time.sleep(2)

            self.setWindowTitle("Snake")
            self.snake = Snake(self.x // 2, self.y // 2)
            self.set_fruit()
            self.timer = DEFAULT_TIMER
            self.timer_id = self.startTimer(self.timer)

        if self.snake.check_fruit(self.fruit):
            self.prev_fruit = deepcopy(self.fruit)
            self.set_fruit()
            self.killTimer(self.timer_id)
            self.timer = max(DEFAULT_TIMER, self.timer - self.timer_delta)
            self.timer_id = self.startTimer(self.timer)

        if self.run and not self.auto:
            self.statistic.save_snapshot(self.snapshot)

        self.prev_key = self.key

        cells = [(cell.x, cell.y, Qt.green) for cell in self.snake]
        cells.append((self.fruit.x, self.fruit.y, Qt.red))
        self.openGL.animate(cells)
Exemplo n.º 10
0
focus = -1
redraw_dna = 0

pg.init()

window = pg.display.set_mode((Win_W, Win_H))
screen = window.subsurface((Set_W, 0, SCR_W, SCR_H))
set_pan = window.subsurface((0, 0, Set_W, SCR_H))
btn_mas = [
    Button(186, 2, "img/pause.png"),
    Button(218, 2, "img/reset.png"),
    Button(2, 5, " Statistic", 93, 22)
]

stat_w = subwindow(95, 27, 900, 510)
stat = Statistic()
visible = 0

run = 1

fd_gr = pg.sprite.Group()
crtb_gr = pg.sprite.Group()
crts_gr = pg.sprite.Group()
deadb_gr = pg.sprite.Group()
deads_gr = pg.sprite.Group()
curs_gr = pg.sprite.Group()
btn_gr = pg.sprite.Group()

vis_gr = []
crt_mas = [Creature(WCR, HCR, SENS) for i in range(count_crt)]
fd_mas = [Food() for i in range(COUNT_FD)]
Exemplo n.º 11
0
class Scheduler:
    def __init__(self, sensors_list, target_list, sensor_range, paint):
        """
		:param sensors_list:lista obiektów typu Sensor
		:param sensing_range:
		:param targets_list:pytanie czy będziemy obserwować cele czy jakiś obszar
		jeśli obszar to parametr jest niepotrzebny
		:param duration: czas trwania symulacji (czas życia sieci sensorowej)
		:param paint: obiekt łączący z interfacem, uaktualnia ekran
		z symulacja, najlepiej użyj self.paint.paint(self)
		za każdym razem kiedy włączysz lub wyłączysz jakiś sensor,
		możesz też użyć tej funkcji np. w jakiejś głównej pętli symulacji
		:param percent_observed_targets: procent obserwowanych celów
		"""
        self.start = time.time()
        self.sensor_list = sensors_list  #type: list[Sensor]
        self.target_list = target_list  #type: list[Target]
        self.statistics = Statistic(target_list,
                                    sensors_list)  # type: Statistic
        self.duration = 0
        self.paint = paint
        self.percent_observed_targets = 0
        self.sensor_range = sensor_range
        self.compute_sensors_targets(self.sensor_list)
        self.fields_list = []  #type:list[Field]
        #zliczam targety zanim usunę z listy wszystkie te które nie są pokryte
        self.target_number = len(self.target_list)
        self.old_list = self.target_list.copy()
        self.target_list = list(
            filter(lambda x: len(x.covering_sensors) != 0, self.target_list))
        self.build_fields_list(self.target_list)

        self.q = 90

    def run(self):
        """
		odpowiada za egzekucje całej symulacji. uruchamia metody obliczające
		pokrycia a nastepnie przeporwadza symulacje, wywołuje funkcje
		odpowiedzialne za wyświetlanie wszytskiego na ekranie
		"""
        #Tu algorytm symulacji

        #Przykładowy kod prezentujący interface, musisz podać co najmniej
        #Przykładowe dane do przetestowania tego kodu
        #400 sensorów, 100 targetów, 20 zasięg, 2 bateria,
        #100 wysokość, 100 szerokość

        # i=0
        # while i < 1000:
        # 	self.paint.paint(self)
        # 	self.sensor_list[i].set_sensor_state(False)
        # 	i+=1
        self.target_list = self.old_list
        covers = self.get_covers_list()
        if len(covers) == 0:
            print("zbyt mało sensorów by osiągnąć 90% pokrycia tych celów")
            self.paint.paint(self)
        base_battery_level = self.sensor_list[0].battery
        self.disable_cover(self.sensor_list)
        for sensor in self.sensor_list:
            sensor.battery = base_battery_level
        print("czas obliczeń" + str(time.time() - self.start))
        self.statistics.start_time = time.time()
        for cover in covers:
            cover = self.activate_covers_sensors(cover)
            if self.statistics.get_percent_observed_targets() < self.q:
                break
            cover_time_start = time.time()
            while (time.time() - cover_time_start < base_battery_level):
                self.paint.paint(self)
            self.disable_cover(cover)
            for sensor in cover:
                sensor.battery = 0

        self.statistics.stop_time()
        #pokazuje pozostałe naładowane sensory żeby było wiadomo że wypalone
        #zostrało wszystko co możliwe
        # for sensor in self.sensor_list:
        # 	if sensor.battery>0:
        # 		sensor.active=True
        # self.paint.paint(self)
        # time.sleep(10)

    def build_fields_list(self, target_list):
        """
		tworzy liste pól na podstwie listy sensorów i targetów
		:param target_list:
		"""
        #czyszczenie
        self.fields_list = []
        for sensor in self.sensor_list:
            sensor.fields = []

        for target in target_list:
            field_exist = False
            # target_sensors=list(filter(lambda x:x in self.sensor_list,target.covering_sensors))

            # if len(target_sensors)==0:
            # 	continue
            try:
                target_fields = self.get_target_fields(target)
            except Exception:
                continue

            # jeśli pole dla targeta istnieje to dodaj target
            field_exist = self.add_to_exist_field(target, target_fields)

            #jeśli pole dla targeta nie istnieje to utwórz nowe
            if not field_exist:
                self.add_to_new_field(target)

    def add_to_new_field(self, target):
        """
		tworzy nowe pole i dodaje do niego target
		:param target:
		"""
        for sensor in target.covering_sensors:
            if sensor.active == True:
                self.add_field_for_target(target)
                break

    def add_to_exist_field(self, target, target_fields):
        """
		dodaje target do pola które już istnieje
		:param target:
		:param target_fields:
		:return:
		"""
        field_exist = False
        for field in target_fields:
            if field.sensors == target.covering_sensors:
                field.targets.append(target)
                field_exist = True
        return field_exist

    def get_target_fields(self, target) -> list:
        """
		zwraca pola w których może sie znaleźć target
		:param target:
		"""
        for sensor in target.covering_sensors:
            if sensor.active == True:
                return sensor.fields
        raise Exception()

    def add_field_for_target(self, target):
        if len(target.covering_sensors) == 0:
            return

        field = Field(target)
        self.fields_list.append(field)

    def activate_covers_sensors(self, cover) -> list:
        """
		Zmienia wartość atrybutu active na True we wszystkich
		sensorach nalezących do listy cover
		:param cover:
		:return:
		"""
        cover = list(filter(lambda x: x in cover, self.sensor_list))
        for sensor in cover:
            sensor.active = True
        return cover

    def disable_cover(selfs, cover):
        """
		Zmienia wartość atrybutu active na False we wszystkich
		sensorach nalezących do listy cover
		:param cover:
		:return:
		"""
        for sensor in cover:
            sensor.active = False
        return cover

    def compute_sensors_targets(self, sensor_list):
        """
		przypisuje sensory do targetów i targety do sensorów
		"""
        for sensor in sensor_list:
            sensor.covering_targets = []
        for target in self.target_list:
            target.covering_sensors = []
        for sensor in sensor_list:
            target: Target
            for target in self.target_list:
                if target.localization.distance_to(
                        sensor.localization) <= sensor.sensing_range:
                    sensor.covering_targets.append(target)
                    target.covering_sensors.append(sensor)

    def get_percent_observed_targets(self):
        """
		zwraca procent obserwowanych celów
		:return:
		"""
        return self.statistics.get_percent_observed_targets()

    def get_critical_field(self, fields_list):
        """
		zwraca element krytyczny
		:param fields_list:
		:return:
		"""
        min = len(self.fields_list[0].sensors)
        critical_field = fields_list[0]
        for field in fields_list:
            if len(field.sensors) < min:
                critical_field = field
                min = len(field.sensors)
        return critical_field

    def get_covers_list(self) -> list:
        """
		Zwraca liste pokryc dla senosorów, targetów i pól znajdujacych się obiekcie
		Scheduler
		:return:
		"""
        covers = []

        sensors = self.sensor_list
        self.activate_covers_sensors(sensors)
        while (True):

            self.build_fields_list(self.get_avaiable_targets())
            if len(self.fields_list) == 0:
                break
            cover = self.get_best_cover(sensors)
            #gdy skończa sie sensory to tak bedzie
            if len(cover) == 0:
                break

            procent = self.get_cover_procent(cover)

            self.clean_cover(cover)

            print(str(procent) + " procent")
            if procent < self.q:
                return covers
            covers.append(cover)
            cover = list(filter(lambda x: x in cover, sensors))
            sensors = list(filter(lambda x: x not in cover, sensors))

            self.disable_cover(cover)

            print("cover " + str(len(covers)))

        return covers

    def get_best_cover(self, sensors):
        """
		Zwraca najbardziej opytmalny podzbiór sensorów z listy sensors.
		Podzbiór jest tym bardziej optymalny im bliżej mu do pkrywania q procent targetów
		:param sensors:
		:return:
		"""
        cover = []
        fields_list = self.fields_list.copy()
        sensor_list = sensors.copy()
        while (len(fields_list) != 0):
            critical_field = self.get_critical_field(fields_list)
            best_sensor = self.get_best_sensor(critical_field, cover,
                                               fields_list)
            self.best_sensor_to_cover(best_sensor, cover, fields_list,
                                      sensor_list)
        self.optimization(cover)
        procent = self.get_cover_procent(cover)
        return cover

    def best_sensor_to_cover(self, best_sensor, cover, fields_list,
                             sensor_list):
        """
		dodaje najlepszy sensor do covera
		:param best_sensor:
		:param cover:
		:param fields_list:
		:param sensor_list:
		"""
        cover.append(best_sensor)
        for field in best_sensor.fields:
            if field in fields_list:
                fields_list.remove(field)

        sensor_list.remove(best_sensor)

    def get_one_sensor_targets(self):
        """
		zwraca targety pokryte przez tylko jeden sensor
		:param sensor_list_test:
		"""
        return list(
            filter(
                lambda x: len(x.covering_sensors) == 1 and x.covering_sensors[
                    0].battery > 0, self.target_list))

    def get_avaiable_targets(self):
        """
		zwraca liste targetów które są pokryte przez conajmniej jeden aktywny sensor
		:return:
		"""
        targets = []
        # self.compute_sensors_targets(sensor_list)
        for target in self.target_list:
            for sensor in target.covering_sensors:

                if sensor.active == True:
                    targets.append(target)
                    break
        return targets

    def get_best_sensor(self, critical_field, cover,
                        uncovered_fields) -> Sensor:
        """
		zwraca najlepszy sensor pkrywający element krytyczny. sensor jest najlepszy gdy ma najwyższą wartość
		funkcji f (patrz wzór \ref{wzor}).
		Pod uwagę brane są tylko sensory pokrywające element
		krytyczny(critical\_ field)
		:param critical_field:
		:param cover:
		:param uncovered_fields:
		:return:
		"""
        available_sensors = []
        for sensor in critical_field.sensors:
            if sensor.active == True:
                available_sensors.append(sensor)
        max_value = self.get_sensor_value(available_sensors[0],
                                          uncovered_fields, critical_field,
                                          cover)
        max_sensor = available_sensors[0]
        available_sensors.remove(max_sensor)
        for sensor in available_sensors:
            sensor_value = self.get_sensor_value(sensor, uncovered_fields,
                                                 critical_field, cover)
            if sensor_value > max_value:
                max_sensor = sensor
                max_value = sensor_value

        return max_sensor

    def get_sensor_value(self, sensor, uncovered_fields, critical_field,
                         cover):
        """
		Zwraca wage sensora sensor.
		:param sensor:
		:param uncovered_fields:
		:param critical_field:
		:param cover:
		:return:
		"""
        value = 0
        for field in sensor.fields:
            if field != critical_field:
                if (field in uncovered_fields):
                    value = value + len(
                        field.targets) - (len(field.sensors) - 1)
                else:
                    sensors_from_cover_number = self.sensors_from_cover_number(
                        field, cover)
                    value = value - len(
                        self.sensor_list) - sensors_from_cover_number + len(
                            field.sensors)
        return value

    def sensors_from_cover_number(self, field, cover):
        """
		Zwrca liczbe sensorów z covera które pokrywają pole field
		:param field:
		:param cover:
		:return:
		"""
        number = 0

        for sensor in cover:
            if field in sensor.fields:
                number = number + 1
        return number

    def optimization(self, cover):
        """
		usuwa z pokrycia(cover) jak najwięcej sensorów, tak by pozostałe sonsory nadal
		pokrywały co najmniej q procent celów
		:param cover:
		"""
        #usuwa sensory ktorych wyłączenie nie zmienia poziomu pokrycia
        # fields_list=set()
        # for sensor in cover:
        # 	fields_list.update(sensor.fields)
        # value=len(fields_list)
        # for sensor in cover:
        # 	fields_list = set()
        # 	for sensor2 in cover:
        # 		if sensor!=sensor2:
        # 			fields_list.update(sensor2.fields)
        # 	if value==len(fields_list):
        # 		cover.remove(sensor)
        #usuwamy maksymalną liczbe sensorów by procent pokrycia był większy od q

        while (self.get_cover_procent(cover) > self.q):
            max_value = 0
            max_sensor = None
            for sensor in cover:
                test_cover = cover.copy()
                test_sensor = sensor
                test_cover.remove(sensor)
                value = self.get_cover_procent(test_cover)
                if value > max_value:
                    max_value = value
                    max_sensor = test_sensor
            if max_value >= self.q:
                cover.remove(max_sensor)

            else:
                break

    def get_cover_targets(self, cover):
        """
		zwraca liste targetów pokrywanych przez sensorvry z cover
		:param cover:
		:return:
		"""
        targets = set()
        for sensor in cover:
            targets.update(sensor.covering_targets)
        return list(targets)

    def get_cover_procent(self, cover):
        """
		zwraca procent targetów pokrytych przez cover
		:param cover:
		:return:
		"""
        return len(self.get_cover_targets(cover)) / self.target_number * 100

    def clean_cover(self, cover):
        """
		czysci liste pól sensora
		:param cover:
		"""
        for sensor in cover:
            sensor.fields = []
Exemplo n.º 12
0
    def __init__(self, x, y, w, h, stat=Statistic()):
        super().__init__()

        self.x = x
        self.y = y
        self.w = w
        self.h = h

        self.bg = create_sprite(x, y, w, h, (220, 220, 220))
        self.hr_g = create_sprite(x + 10, y + h // 2 - 10, w - 20, 2,
                                  (150, 150, 150))
        self.hr_v = create_sprite(x + w // 2, y + 10, 2, h // 2 - 30,
                                  (150, 150, 150))
        self.r_hr1 = create_sprite(x + 145, y + 40, 180, 2, (255, 0, 0))
        self.r_hr2 = create_sprite(x + w // 2 + 132, y + 40, 180, 2,
                                   (255, 0, 0))
        self.r_hr3 = create_sprite(x + w // 2 - 125, y + h // 2 + 40, 275, 2,
                                   (255, 0, 0))

        per_day_str = F1.render("Per Day", 1, (0, 0, 0))
        digits_str = F1.render("Digits", 1, (0, 0, 0))
        adv_set = F1.render("Advanced Settings", 1, (0, 0, 0))

        oldest_alive_breed_str = F2.render(
            "The Oldest Alive Breed - " + str(stat.oldest_alive_breed), 1,
            (0, 0, 0))
        youngest_alive_breed_str = F2.render(
            "The Youngest Alive Breed - " + str(stat.youngest_alive_breed), 1,
            (0, 0, 0))
        average_day_str = F2.render("Averange Day - " + str(stat.avarage_day),
                                    1, (0, 0, 0))
        oldest_creature_str = F2.render(
            "The Oldest Creature - " + str(stat.oldest_creature), 1, (0, 0, 0))
        mut_str = F2.render("Mutation", 1, (0, 0, 0))

        self.add(self.bg)
        self.add(self.hr_g)
        self.add(self.hr_v)
        self.add(self.r_hr1)
        self.add(self.r_hr2)
        self.add(self.r_hr3)

        self.bg.image.blit(per_day_str, (190, 10))
        self.bg.image.blit(digits_str, (190 + w // 2, 10))
        self.bg.image.blit(adv_set, (w // 2 - 100, h // 2 + 10))

        # Статистичесие данные
        self.buttons = []
        self.buttons.append(Button(x + 10, y + 50, " Count of Birth", 143, 25))
        self.buttons.append(Button(x + 10, y + 80, " Count of Alive", 143, 25))
        self.buttons.append(Button(x + 10, y + 110, " Count of Dead", 143, 25))
        self.buttons.append(
            Button(x + 10, y + 140, " Count of Mutation", 178, 25))

        # Кнопки настроек
        self.buttons.append(
            Radio_Button(x + 40, y + h // 2 + 75, " Speed", 157, 25))
        self.buttons.append(
            Radio_Button(x + 40, y + h // 2 + 100, " Reproduction", 157, 25))
        self.buttons.append(
            Radio_Button(x + 40, y + h // 2 + 125, " Width", 157, 25))
        self.buttons.append(
            Radio_Button(x + 40, y + h // 2 + 150, " Height", 157, 25))
        self.buttons.append(
            Radio_Button(x + 40, y + h // 2 + 175, " Sense", 157, 25))

        self.add(self.buttons)

        # Численные данные
        self.bg.image.blit(oldest_alive_breed_str, (10 + w // 2, 50))
        self.bg.image.blit(youngest_alive_breed_str, (10 + w // 2, 75))
        self.bg.image.blit(average_day_str, (10 + w // 2, 100))
        self.bg.image.blit(oldest_creature_str, (10 + w // 2, 125))

        # Расг=ширенные настройки
        self.bg.image.blit(mut_str, (w // 16 + 22, y + h // 2 + 25))