Commit 21fe8a0a authored by Ahmad Reza's avatar Ahmad Reza
Browse files

Many changes:

sim.py renamed to world.py
run.py renamed to swarm-sim.py
swarm-sim.py got a new structure for initializing the swarm-sim and calling the solution. The solution calling is independent from vis.py
vis.py: The run method is renamed to draw_world. Solution is not called anymore inside of this method. A new variable called refresh_time is added. The draw window is getting refreshed after each solution has been called and refresh_time is over.

header.py: in the lib a header.py is inserted. In this file all the standards color and direcotries are defined. As well some standard methods for checking or changing the directions.
parent 5a639804
......@@ -2,7 +2,7 @@ For Linux:
-unzip the source code:
unzip swarm-sim.zip
unzip swarm-world.zip
-install the following python packages:
......@@ -34,7 +34,7 @@ For Windows:
- install python3.6
- install pycharm
- run pycharm
- open swarm-sim as a project
- open swarm-world as a project
- Open File->Settings-"Project-Interpreter"
- Chose python3.6 as an interpreter
- Chose the plus sign and install:
......
......@@ -3,7 +3,7 @@
## Different number creates a different random sequence
seedvalue = 12
## Maximum round number in swarm-sim
## Maximum round number in swarm-world
max_round = 100
# Visualization 1 = On, 0 = Off
......@@ -17,11 +17,11 @@ random_order = 1
window_size_x = 600
window_size_y = 800
## 0 = Unlimited sim size
## 1 = limited sim size
## 0 = Unlimited world size
## 1 = limited world size
border = 0.0
## Swarm-Sim sim size in points
## Swarm-World world size in points
## Works only with border flag set on 1
size_x = 2000.0
size_y = 2000.0
......@@ -44,8 +44,8 @@ tile_mm_size = 2
##Moving
#scenario = lonely_particle
scenario = n_particle_in_line
solution = random_walk
#scenario = n_particle_in_line
#solution = random_walk
#solution = round_walk
## Creating and Deleting
......@@ -65,6 +65,6 @@ solution = random_walk
#solution= scanning_for_all_aims
## All interfaces
#scenario = test_interfaces
#solution = test_all_the_interfaces
scenario = test_interfaces
solution = test_all_the_interfaces
from enum import Enum
class Colors(Enum):
black = 1
gray = 2
red = 3
green = 4
blue = 5
......@@ -109,14 +109,13 @@ class CsvParticleData:
class CsvRoundData:
def __init__(self, sim, task=0, scenario=0, solution=0, seed=20, particle_num=0, tiles_num=0, markers_num=0,
def __init__(self, task=0, scenario=0, solution=0, seed=20, particle_num=0, tiles_num=0, markers_num=0,
steps=0, directory="outputs/"):
self.sim = sim
self.task = task
self.scenario = scenario
self.solution = solution
self.actual_round=sim.get_actual_round()
self.actual_round= 1
self.seed = seed
self.steps = steps
self.steps_sum = steps
......@@ -155,7 +154,7 @@ class CsvRoundData:
self.marker_deleted_sum = 0
self.memory_read_sum = 0
self.memory_write_sum = 0
self.success_round = None
self.success_round = 0
self.success_counter = 0
self.tiles_taken = 0
self.tiles_dropped = 0
......@@ -231,51 +230,30 @@ class CsvRoundData:
self.particles_taken_sum = self.particles_taken_sum + particles_taken
self.particles_dropped_sum = self.particles_dropped_sum + particles_dropped
if self.actual_round == self.sim.get_actual_round():
self.steps = self.steps + steps
self.particle_read = self.particle_read + particle_read
self.tile_read = self.tile_read + tile_read
self.marker_read = self.marker_read + marker_read
self.memory_read = self.memory_read + memory_read
self.particle_write = self.particle_write + particle_write
self.tile_write = self.tile_write + tile_write
self.marker_write = self.marker_write + marker_write
self.memory_write = self.memory_write + memory_write
self.particle_created = self.particle_created + particle_created
self.tile_created = self.tile_created + tile_created
self.marker_created = self.marker_created + marker_created
self.particle_deleted = self.particle_deleted + particle_deleted
self.tile_deleted = self.tile_deleted + tile_deleted
self.marker_deleted = self.marker_deleted + marker_deleted
self.tiles_dropped = self.tiles_dropped + tiles_dropped
self.tiles_taken = self.tiles_taken + tiles_taken
self.particles_taken= self.particles_taken + particles_taken
self.particles_dropped = self.particles_dropped + particles_dropped
elif self.actual_round !=self.sim.get_actual_round():
self.actual_round = self.sim.get_actual_round()
self.steps = steps
self.particle_read = particle_read
self.tile_read = tile_read
self.marker_read = marker_read
self.memory_read = memory_read
self.particle_write = particle_write
self.tile_write = tile_write
self.marker_write = marker_write
self.memory_write = memory_write
self.particle_created = particle_created
self.tile_created = tile_created
self.marker_created = marker_created
self.particle_deleted = particle_deleted
self.tile_deleted = tile_deleted
self.marker_deleted = marker_deleted
self.tiles_dropped = tiles_dropped
self.tiles_taken = tiles_taken
self.particles_taken = particles_taken
self.particles_dropped = particles_dropped
self.steps = self.steps + steps
self.particle_read = self.particle_read + particle_read
self.tile_read = self.tile_read + tile_read
self.marker_read = self.marker_read + marker_read
self.memory_read = self.memory_read + memory_read
self.particle_write = self.particle_write + particle_write
self.tile_write = self.tile_write + tile_write
self.marker_write = self.marker_write + marker_write
self.memory_write = self.memory_write + memory_write
self.particle_created = self.particle_created + particle_created
self.tile_created = self.tile_created + tile_created
self.marker_created = self.marker_created + marker_created
self.particle_deleted = self.particle_deleted + particle_deleted
self.tile_deleted = self.tile_deleted + tile_deleted
self.marker_deleted = self.marker_deleted + marker_deleted
self.tiles_dropped = self.tiles_dropped + tiles_dropped
self.tiles_taken = self.tiles_taken + tiles_taken
self.particles_taken= self.particles_taken + particles_taken
self.particles_dropped = self.particles_dropped + particles_dropped
logging.debug("CSV: Ending writing_rounds")
def next_line(self, round):
csv_iterator = ['', self.scenario, self.solution, self.seed, round,
def next_line(self, sim_round):
csv_iterator = ['', self.scenario, self.solution, self.seed, sim_round,
self.success_counter, self.success_round,
self.particle_num, self.particle_created, self.particle_created_sum,
self.particle_deleted, self.particle_deleted_sum,
......@@ -294,7 +272,7 @@ class CsvRoundData:
self.tile_read, self.tile_read_sum, self.tiles_taken, self.tiles_taken_sum,
self.tile_write, self.tile_write_sum]
self.writer_round.writerow(csv_iterator)
self.actual_round = round
self.actual_round = sim_round
self.steps=0
self.particle_read=0
self.tile_read=0
......@@ -312,7 +290,7 @@ class CsvRoundData:
self.marker_deleted = 0
self.tiles_dropped = 0
self.tiles_taken = 0
self.success_round = None
self.success_round = 0
self.success_counter = 0
self.particles_taken = 0
self.particles_dropped = 0
......
......@@ -2,7 +2,7 @@ import subprocess, os
import pandas as pd
def generate_gnuplot(directory):
def gnuplot_generator(directory):
data = pd.read_csv(directory+"/rounds.csv")
i = 1
plot = subprocess.Popen(['gnuplot', '--persist'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
......
from enum import Enum
class Colors(Enum):
black = 1
gray = 2
red = 3
green = 4
blue = 5
yellow = 6
orange = 7
cyan = 8
violett = 9
black = 1
gray = 2
red = 3
green = 4
blue = 5
yellow = 6
orange = 7
cyan = 8
violett = 9
color_map = {
black: [0.0, 0.0, 0.0],
gray: [0.3, 0.3, 0.3],
red: [0.8, 0.0, 0.0],
green: [0.0, 0.8, 0.0],
blue: [0.0, 0.0, 0.8],
yellow: [0.8, 0.8, 0.0],
orange: [0.8, 0.3, 0.0],
cyan: [0.0, 0.8, 0.8],
violett: [0.8, 0.2, 0.6]
}
NE=0
E = 1
SE = 2
SW = 3
W = 4
NW = 5
direction = [NE, E, SE, SW, W, NW]
x_offset = [0.5, 1, 0.5, -0.5, -1, -0.5 ]
y_offset = [ 1, 0, -1, -1, 0, 1]
def dir_to_str(dir):
"""
:param dir: the direction that should get converted to a string
:return: the string of the direction
"""
if dir == 0:
return "NE"
elif dir == 1:
return "E"
elif dir == 2:
return "SE"
elif dir == 3:
return "SW"
elif dir == 4:
return "W"
elif dir == 5:
return "NW"
else:
return "Error"
def get_the_invert(dir):
return (dir + 3) % 6
def dir_in_range(dir):
return dir % 6
"""The marker module provides the interface to the markers. A marker is any point on
the coordinate system of the simulators sim"""
the coordinate system of the simulators world"""
from lib import matter
from lib.header import *
black = 1
gray = 2
red = 3
green = 4
blue = 5
class Marker(matter.Matter):
"""In the classe marker all the methods for the characterstic of a marker is included"""
def __init__(self, sim, x, y, color=black, alpha=1):
def __init__(self, world, x, y, color=black, alpha=1):
"""Initializing the marker constructor"""
super().__init__( sim, (x, y), color, alpha, type="marker", mm_size=sim.config_data.marker_mm_size)
super().__init__( world, (x, y), color, alpha, type="marker", mm_size=world.config_data.marker_mm_size)
"""The marker module provides the interface to the markers. A marker is any point on
the coordinate system of the simulators sim"""
the coordinate system of the simulators world"""
import uuid
import logging
from datetime import datetime
from lib.header import *
black = 1
gray = 2
red = 3
green = 4
blue = 5
yellow = 6
orange = 7
cyan = 8
violett = 9
color_map = {
black: [0.0, 0.0, 0.0],
gray: [0.3, 0.3, 0.3],
red: [0.8, 0.0, 0.0],
green: [0.0, 0.8, 0.0],
blue: [0.0, 0.0, 0.8],
yellow: [0.8, 0.8, 0.0],
orange: [0.8, 0.3, 0.0],
cyan: [0.0, 0.8, 0.8],
violett: [0.8, 0.2, 0.6]
}
class Matter():
class Matter:
"""In the classe marker all the methods for the characterstic of a marker is included"""
def __init__(self, sim, coords, color=black, alpha=1, type=None, mm_size=100):
def __init__(self, world, coords, color=black, alpha=1, type=None, mm_size=100):
"""Initializing the marker constructor"""
self.coords = coords
self.color = color_map[color]
......@@ -42,13 +16,14 @@ class Matter():
self.memory_delay=True
self.memory_buffer=[]
self._tmp_memory=[]
self.sim = sim
self.world = world
self._memory={}
self.__modified=False
self.__alpha=alpha
self.type = type
self.mm_limit = sim.config_data.mm_limitation
self.mm_limit = world.config_data.mm_limitation
self.mm_size = mm_size
self.modified = False
def set_alpha(self, alpha):
"""
......@@ -85,7 +60,7 @@ class Matter():
# if key ==
if key in self._memory:
tmp_memory = self._memory[key]
self.sim.csv_round_writer.update_metrics( memory_read=1)
self.world.csv_round.update_metrics( memory_read=1)
if isinstance(tmp_memory, list) and len(str(tmp_memory)) == 0:
return None
if isinstance(tmp_memory, str) and len(str(tmp_memory)) == 0:
......@@ -100,7 +75,7 @@ class Matter():
:return: The founded memory; None: When nothing is written based on the keywoard
"""
if self._memory != None :
self.sim.csv_round_writer.update_metrics(memory_read=1)
self.world.csv_round.update_metrics(memory_read=1)
return self._memory
else:
return None
......@@ -116,13 +91,12 @@ class Matter():
if (self.mm_limit == True and len( self._memory) < self.mm_size) or not self.mm_limit:
self._memory[key] = data
self.sim.csv_round_writer.update_metrics(memory_write=1)
self.world.csv_round.update_metrics(memory_write=1)
return True
else:
return False
#write csv
def write_memory(self, data):
"""
Write on its own memory a data with a keywoard
......@@ -134,20 +108,18 @@ class Matter():
if (self.mm_limit == True and len( self._memory) < self.mm_size) or not self.mm_limit:
self._memory[datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-1]] = data
self.sim.csv_round_writer.update_metrics(memory_write=1)
self.world.csv_round.update_metrics(memory_write=1)
return True
else:
return False
#write csv
def delete_memeory_with(self, key):
del self._memory[key]
def delete_whole_memeory(self):
self._memory.clear()
def get_id(self):
"""
Gets the marker id
......@@ -168,7 +140,6 @@ class Matter():
self.color = color
self.touch()
def get_color(self):
"""
Sets the marker color
......
This diff is collapsed.
"""The tile module provides the interface for the tiles. A tile is a hexogon that can be taken or dropped
and be connected to each other to buld up islands"""
import logging
from lib import matter
black = 1
gray = 2
red = 3
green = 4
blue = 5
read=0
write=1
from lib.header import *
class Tile(matter.Matter):
"""In the classe marker all the methods for the characterstic of a marker is included"""
def __init__(self, sim, x, y, color=gray, alpha=1):
def __init__(self, world, x, y, color=gray, alpha=1):
"""Initializing the marker constructor"""
super().__init__( sim, (x, y), color, alpha, type="tile", mm_size=sim.config_data.tile_mm_size)
super().__init__( world, (x, y), color, alpha, type="tile", mm_size=world.config_data.tile_mm_size)
self.__isCarried = False
self.created = False
def get_tile_status(self):
"""
Get the tile status if it taken or not
......@@ -41,7 +29,6 @@ class Tile(matter.Matter):
"""
self.__isCarried = status
def take(self, coords=0):
"""
Takes the tile on the given coordinate if it is not taken
......@@ -51,8 +38,8 @@ class Tile(matter.Matter):
"""
if coords==0:
if self.__isCarried == False:
if self.coords in self.sim.tile_map:
del self.sim.tile_map_coords[self.coords]
if self.coords in self.world.tile_map:
del self.world.tile_map_coords[self.coords]
self.__isCarried = True
self.set_alpha(0.5)
self.touch()
......@@ -61,8 +48,8 @@ class Tile(matter.Matter):
return False
else:
if self.__isCarried == False:
if self.coords in self.sim.tile_map_coords:
del self.sim.tile_map_coords[self.coords]
if self.coords in self.world.tile_map_coords:
del self.world.tile_map_coords[self.coords]
self.__isCarried = True
self.coords = coords
self.set_alpha(0.5)
......@@ -71,8 +58,6 @@ class Tile(matter.Matter):
else:
return False
def drop_me(self, coords):
"""
Drops the tile
......@@ -80,7 +65,7 @@ class Tile(matter.Matter):
:param coords: the given position
:return: None
"""
self.sim.tile_map_coords[coords] = self
self.world.tile_map_coords[coords] = self
self.coords = coords
self.__isCarried = False
self.set_alpha(1)
......
......@@ -2,9 +2,6 @@ import datetime, math, os, time
from pyglet.gl import *
from pyglet.window import mouse
import pyglet.window.key as key
import importlib
import subprocess
import pandas as pd
# screenshot manager parameters
screenshot_directory = 'screenshots/'
......@@ -28,12 +25,16 @@ show_grid = True
rotate_thirty_degree = False # the grid is not drawn correctly if the view is rotated!
# rendering parameters
target_frame_rate = 60
busy_waiting_time = 0.0015
target_frame_rate = 10
busy_waiting_time = 1
print_frame_stats = False
# simulation parameters
rounds_per_second = 10
rounds_per_second = 40
refresh_time = 1 #how many seconds to wait for a new round and a new frame. 1 means one round and frame every 1 second
#0.25 means one round and frame every 0.25 sec (250ms)
# tile_alpha = 0.6
particle_alpha = 1
......@@ -60,6 +61,7 @@ class ScreenshotManager:
dt = datetime.datetime.now()
#prefix = dt.isoformat(sep = '_', timespec = 'seconds').replace(':', '') + '_'
prefix = dt.isoformat(sep='_').replace(':', '') + '_'
def takeScreenshot():
if not os.path.exists(screenshot_directory):
os.makedirs(screenshot_directory)
......@@ -73,6 +75,7 @@ class View:
def __init__(self):
self.focusPos = translation_init
self.zoom = zoom_init
halfZoomRec = 0.5 / self.zoom
def setDimensions(self, width, height):
self.width = width
......@@ -108,19 +111,20 @@ class View:
class VisWindow(pyglet.window.Window):
def __init__(self, window_size_x, window_size_y, sim):
#super().__init__(sim.get_sim_x_size(), sim.get_sim_y_size(), resizable=window_resizable, vsync=False, caption="Simulator")
def __init__(self, window_size_x, window_size_y, world):
#super().__init__(world.get_sim_x_size(), world.get_sim_y_size(), resizable=window_resizable, vsync=False, caption="Simulator")
super().__init__(window_size_x, window_size_y , resizable=window_resizable, vsync=False, caption="Simulator")
self.window_active = True
glClearColor(0.0, 0.0, 0.0, 0.0)
glClearDepth(1.0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
self.sim = sim
self.world = world
self.init_tile_vertex_list()
self.init_particle_vertex_list()
self.init_marker_vertex_list()
self.view = View()
self.view.setDimensions(window_size_x, window_size_y)
self.elapsed_frame_time = 0
self.particleTexture = pyglet.image.load('lib/images/particle.png').get_mipmapped_texture()
self.gridTexture = pyglet.image.load('lib/images/grid.png').get_mipmapped_texture()
......@@ -142,6 +146,8 @@ class VisWindow(pyglet.window.Window):
self.simulation_running = False
self.video_mode = False
self.draw()
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
if buttons & mouse.LEFT:
......@@ -162,19 +168,19 @@ class VisWindow(pyglet.window.Window):
rounded_coords = round(coords_coords[0],0) + 0.5
else:
rounded_coords =round(coords_coords[0], 0)
if (rounded_coords,coords_coords[1]) not in self.sim.tile_map_coords:
if (rounded_coords,coords_coords[1]) not in self.world.tile_map_coords:
# add tile and vertices
if self.sim.add_tile_vis(rounded_coords, coords_coords[1]):
self.tile_vertex_list.resize(4 * len(self.sim.tiles), 4 * len(self.sim.tiles))
#self.tile_vertex_list.resize(4 * len(self.sim.tiles), 8 * len(self.sim.tiles))
self.tile_vertex_list.indices[4 * (len(self.sim.tiles) - 1) : 4 * (len(self.sim.tiles) - 1) + 4] = range(4 * (len(self.sim.tiles) - 1), 4 * (len(self.sim.tiles) - 1) + 4)
# self.tile_vertex_list.indices = list(range(0, 8 * len(self.sim.tiles)))
# self.update_tile(len(self.sim.tiles) - 1, tile)
if self.world.add_tile_vis(rounded_coords, coords_coords[1]):
self.tile_vertex_list.resize(4 * len(self.world.tiles), 4 * len(self.world.tiles))
#self.tile_vertex_list.resize(4 * len(self.world.tiles), 8 * len(self.world.tiles))
self.tile_vertex_list.indices[4 * (len(self.world.tiles) - 1) : 4 * (len(self.world.tiles) - 1) + 4] = range(4 * (len(self.world.tiles) - 1), 4 * (len(self.world.tiles) - 1) + 4)
# self.tile_vertex_list.indices = list(range(0, 8 * len(self.world.tiles)))
# self.update_tile(len(self.world.tiles) - 1, tile)
self.update_tiles(True)
else:
# delete tile
self.sim.remove_tile_on((rounded_coords,coords_coords[1]))
self.tile_vertex_list.resize(4 * len(self.sim.tiles), 4 * len(self.sim.tiles))
self.world.remove_tile_on((rounded_coords,coords_coords[1]))
self.tile_vertex_list.resize(4 * len(self.world.tiles), 4 * len(self.world.tiles))
self.update_tiles(True)
def on_resize(self, width, height):
......@@ -219,7 +225,7 @@ class VisWindow(pyglet.window.Window):
glBindTexture(self.particleTexture.target, self.particleTexture.id)