swarm-sim.py 4.99 KB
Newer Older
1
"""This is the main module of the Opportunistic Robotics Network Simulator"""
Ahmad Reza's avatar
Ahmad Reza committed
2

Ahmad Reza's avatar
Ahmad Reza committed
3
import importlib
Ahmad Reza's avatar
Ahmad Reza committed
4
5
6
7
8
9
import configparser
import getopt
import logging
import os
import sys
from datetime import datetime
Ahmad Reza's avatar
Ahmad Reza committed
10
11
from lib import world
from lib.gnuplot_generator import gnuplot_generator
Ahmad Reza's avatar
Ahmad Reza committed
12
13


Ahmad Reza's avatar
Ahmad Reza committed
14
class ConfigData:
Ahmad Reza's avatar
Ahmad Reza committed
15
16

    def __init__(self, config):
Ahmad Reza's avatar
Ahmad Reza committed
17
        self.seed_value = config.getint("Simulator", "seedvalue")
Ahmad Reza's avatar
Ahmad Reza committed
18
19
20
21
22
23
24
25
26
27
28
29
        self.max_round = config.getint("Simulator", "max_round")
        self.random_order = config.getboolean("Simulator", "random_order")
        self.visualization = config.getint("Simulator", "visualization")
        try:
            self.scenario = config.get("File", "scenario")
        except (configparser.NoOptionError) as noe:
            self.scenario = "init_scenario.py"

        try:
            self.solution = config.get("File", "solution")
        except (configparser.NoOptionError) as noe:
            self.solution = "solution.py"
30
31
        self.size_x = config.getfloat("Simulator", "size_x")
        self.size_y = config.getfloat("Simulator", "size_y")
Ahmad Reza's avatar
Ahmad Reza committed
32
33
        self.window_size_x = config.getint("Simulator", "window_size_x")
        self.window_size_y = config.getint("Simulator", "window_size_y")
34
        self.border = config.getfloat("Simulator", "border")
Ahmad Reza's avatar
Ahmad Reza committed
35
36
37
38
        self.max_particles = config.getint("Simulator", "max_particles")
        self.mm_limitation = config.getboolean("Matter", "mm_limitation")
        self.particle_mm_size = config.getint("Matter", "particle_mm_size")
        self.tile_mm_size = config.getint("Matter", "tile_mm_size")
39
        self.marker_mm_size = config.getint("Matter", "marker_mm_size")
Ahmad Reza's avatar
Ahmad Reza committed
40
41
42
        self.local_time = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')[:-1]
        self.multiple_sim = 0

Ahmad Reza's avatar
Ahmad Reza committed
43
44

def swarm_sim( argv ):
Ahmad Reza's avatar
Ahmad Reza committed
45
    """In the main function first the config is getting parsed and than
Ahmad Reza's avatar
Ahmad Reza committed
46
    the swarm_world and the swarm_world object is created. Afterwards the run method of the swarm_world
Ahmad Reza's avatar
Ahmad Reza committed
47
    is called in which the simlator is going to start to run"""
Ahmad Reza's avatar
Ahmad Reza committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
    logging.basicConfig(filename='system.log', filemode='w', level=logging.INFO, format='%(message)s')
    logging.info('Started')

    config_data = init_swarm_sim(argv)

    swarm_world = world.World(config_data)

    while swarm_world.get_actual_round() <= swarm_world.get_max_round() and swarm_world.get_end() is False:
        solution(swarm_world)
        if config_data.visualization and swarm_world.window.window_active is False:
            break
    swarm_world.csv_aggregator()
    gnuplot_generator(config_data.dir_name)
    logging.info('Finished')
Ahmad Reza's avatar
Ahmad Reza committed
62

Ahmad Reza's avatar
Ahmad Reza committed
63
64
65
66
67
68
69
70
71
72

def init_swarm_sim(argv):
    config_data = read_config_file()
    read_cmd_args(argv, config_data)
    create_dir(config_data)
    return config_data


def read_config_file():
    config = configparser.ConfigParser(allow_no_value=True)
Ahmad Reza's avatar
Ahmad Reza committed
73
    config.read("config.ini")
Ahmad Reza's avatar
Ahmad Reza committed
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
    config_data = ConfigData(config)
    return config_data


def create_dir(config_data):
    if config_data.multiple_sim == 1:
        config_data.dir_name = config_data.local_time + "_" + config_data.scenario.rsplit('.', 1)[0] + \
                               "_" + config_data.solution.rsplit('.', 1)[0] + "/" + \
                               str(config_data.seed_value)

        config_data.dir_name = "./outputs/mulitple/" + config_data.dir_name

    else:
        config_data.dir_name = config_data.local_time + "_" + config_data.scenario.rsplit('.', 1)[0] + \
                               "_" + config_data.solution.rsplit('.', 1)[0] + "_" + \
                               str(config_data.seed_value)
        config_data.dir_name = "./outputs/" + config_data.dir_name
    if not os.path.exists(config_data.dir_name):
        os.makedirs(config_data.dir_name)


def solution(swarm_world):
    if swarm_world.config_data.visualization:
        swarm_world.window.draw_world()
    mod = importlib.import_module('solution.' + swarm_world.config_data.solution)
    mod.solution(swarm_world)
    swarm_world.csv_round.next_line(swarm_world.get_actual_round())
    swarm_world.inc_round_cnter()
Ahmad Reza's avatar
Ahmad Reza committed
102

Ahmad Reza's avatar
Ahmad Reza committed
103
104

def read_cmd_args(argv, config_data):
Ahmad Reza's avatar
Ahmad Reza committed
105
    try:
106
        opts, args = getopt.getopt(argv, "hs:w:r:n:m:d:v:", ["solution=", "scenario="])
Ahmad Reza's avatar
Ahmad Reza committed
107
    except getopt.GetoptError:
Ahmad Reza's avatar
Ahmad Reza committed
108
        print('Error: swarm-swarm_world.py -r <seed> -w <scenario> -s <solution> -n <maxRounds>')
Ahmad Reza's avatar
Ahmad Reza committed
109
110
111
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
Ahmad Reza's avatar
Ahmad Reza committed
112
            print('swarm-swarm_world.py -r <seed> -w <scenario> -s <solution> -n <maxRounds>')
Ahmad Reza's avatar
Ahmad Reza committed
113
114
            sys.exit()
        elif opt in ("-s", "--solution"):
Ahmad Reza's avatar
Ahmad Reza committed
115
            config_data.solution = arg
116
        elif opt in ("-w", "--scenario"):
Ahmad Reza's avatar
Ahmad Reza committed
117
            config_data.scenario = arg
Ahmad Reza's avatar
Ahmad Reza committed
118
        elif opt in ("-r", "--seed"):
Ahmad Reza's avatar
Ahmad Reza committed
119
            config_data.seed_value = int(arg)
Ahmad Reza's avatar
Ahmad Reza committed
120
        elif opt in ("-n", "--maxrounds"):
Ahmad Reza's avatar
Ahmad Reza committed
121
122
123
124
            config_data.max_round = int(arg)
        elif opt in "-m":
            config_data.multiple_sim = int(arg)
        elif opt in "-v":
Ahmad Reza's avatar
Ahmad Reza committed
125
            config_data.visualization = int(arg)
Ahmad Reza's avatar
Ahmad Reza committed
126
127
        elif opt in "-d":
            config_data.local_time = str(arg)
Ahmad Reza's avatar
Ahmad Reza committed
128
129
130


if __name__ == "__main__":
Ahmad Reza's avatar
Ahmad Reza committed
131
    swarm_sim(sys.argv[1:])
Ahmad Reza's avatar
Ahmad Reza committed
132