1
0
mirror of https://github.com/gsi-upm/soil synced 2024-11-22 19:22:29 +00:00

Code organized

This commit is contained in:
Tasio Mendez 2018-04-16 10:55:27 +02:00
parent 563587193a
commit 788af57da2
4 changed files with 20 additions and 83 deletions

14
run.py
View File

@ -1,12 +1,11 @@
import argparse import argparse
from server import ModularServer from server import ModularServer
from visualization import GraphVisualization, Model from simulator import Simulator
def run(model, name="SOIL Model", verbose=False, params=None): def run(simulator, name="SOIL", port=8001, verbose=False):
graphVisualization = GraphVisualization(params) server = ModularServer(simulator, name=(name[0] if isinstance(name, list) else name), verbose=verbose)
server = ModularServer(model, graphVisualization, name=(name[0] if isinstance(name, list) else name), verbose=verbose) server.port = port
server.port = 8001
server.launch() server.launch()
@ -16,8 +15,9 @@ if __name__ == "__main__":
parser.add_argument('--name', '-n', nargs=1, default='SOIL', help='name of the simulation') parser.add_argument('--name', '-n', nargs=1, default='SOIL', help='name of the simulation')
parser.add_argument('--dump', '-d', help='dumping results in folder output', action='store_true') parser.add_argument('--dump', '-d', help='dumping results in folder output', action='store_true')
parser.add_argument('--port', '-p', nargs=1, default=8001, help='port for launching the server')
parser.add_argument('--verbose', '-v', help='verbose mode', action='store_true') parser.add_argument('--verbose', '-v', help='verbose mode', action='store_true')
args = parser.parse_args() args = parser.parse_args()
soil = Model(dump=args.dump) soil = Simulator(dump=args.dump)
run(soil, name=args.name, verbose=args.verbose) run(soil, name=args.name, port=(args.port[0] if isinstance(args.port, list) else args.port), verbose=args.verbose)

View File

@ -17,41 +17,13 @@ from xml.etree.ElementTree import tostring
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
class VisualizationElement:
"""
Defines an element of the visualization.
Attributes:
package_includes: A list of external JavaScript files to include that
are part of the packages.
local_includes: A list of JavaScript files that are local to the
directory that the server is being run in.
js_code: A JavaScript code string to instantiate the element.
Methods:
render: Takes a model object, and produces JSON data which can be sent
to the client.
"""
package_includes = []
local_includes = []
js_code = ''
render_args = {}
def __init__(self):
pass
def render(self, model):
return '<b>VisualizationElement goes here</b>.'
class PageHandler(tornado.web.RequestHandler): class PageHandler(tornado.web.RequestHandler):
""" Handler for the HTML template which holds the visualization. """ """ Handler for the HTML template which holds the visualization. """
def get(self): def get(self):
self.render('index.html', port=self.application.port, self.render('index.html', port=self.application.port,
model_name=self.application.model_name, name=self.application.name)
package_includes=self.application.package_includes,
local_includes=self.application.local_includes,
scripts=self.application.js_code)
class SocketHandler(tornado.websocket.WebSocketHandler): class SocketHandler(tornado.websocket.WebSocketHandler):
@ -85,7 +57,7 @@ class SocketHandler(tornado.websocket.WebSocketHandler):
return return
else: else:
self.config = self.config[0] self.config = self.config[0]
self.send_log('INFO.soil', 'Using config: {name}'.format(name=self.config['name'])) self.send_log('INFO.' + self.application.simulator.name, 'Using config: {name}'.format(name=self.config['name']))
if 'visualization_params' in self.config: if 'visualization_params' in self.config:
self.write_message({'type': 'visualization_params', self.write_message({'type': 'visualization_params',
@ -124,7 +96,7 @@ class SocketHandler(tornado.websocket.WebSocketHandler):
elif msg['type'] == 'run_simulation': elif msg['type'] == 'run_simulation':
if self.application.verbose: if self.application.verbose:
logger.info('Running new simulation for {name}'.format(name=self.config['name'])) logger.info('Running new simulation for {name}'.format(name=self.config['name']))
self.send_log('INFO.soil', 'Running new simulation for {name}'.format(name=self.config['name'])) self.send_log('INFO.' + self.application.simulator.name, 'Running new simulation for {name}'.format(name=self.config['name']))
self.config['environment_params'] = msg['data'] self.config['environment_params'] = msg['data']
self.run_simulation() self.run_simulation()
@ -158,7 +130,7 @@ class SocketHandler(tornado.websocket.WebSocketHandler):
try: try:
if (not self.log_capture_string.closed and self.log_capture_string.getvalue()): if (not self.log_capture_string.closed and self.log_capture_string.getvalue()):
for i in range(len(self.log_capture_string.getvalue().split('\n')) - 1): for i in range(len(self.log_capture_string.getvalue().split('\n')) - 1):
self.send_log('INFO.soil', self.log_capture_string.getvalue().split('\n')[i]) self.send_log('INFO.' + self.application.simulator.name, self.log_capture_string.getvalue().split('\n')[i])
self.log_capture_string.truncate(0) self.log_capture_string.truncate(0)
self.log_capture_string.seek(0) self.log_capture_string.seek(0)
finally: finally:
@ -179,9 +151,9 @@ class SocketHandler(tornado.websocket.WebSocketHandler):
# Run simulation and capture logs # Run simulation and capture logs
if 'visualization_params' in self.config: if 'visualization_params' in self.config:
del self.config['visualization_params'] del self.config['visualization_params']
with self.logging(self.application.model.name): with self.logging(self.application.simulator.name):
try: try:
self.simulation = self.application.model.run(self.config) self.simulation = self.application.simulator.run(self.config)
except: except:
error = 'Something went wrong. Please, try again.' error = 'Something went wrong. Please, try again.'
self.write_message({'type': 'error', self.write_message({'type': 'error',
@ -217,10 +189,7 @@ class SocketHandler(tornado.websocket.WebSocketHandler):
class ModularServer(tornado.web.Application): class ModularServer(tornado.web.Application):
""" Main visualization application. """ """ Main visualization application. """
portrayal_method = None
port = 8001 port = 8001
model_args = ()
model_kwargs = {}
page_handler = (r'/', PageHandler) page_handler = (r'/', PageHandler)
socket_handler = (r'/ws', SocketHandler) socket_handler = (r'/ws', SocketHandler)
static_handler = (r'/(.*)', tornado.web.StaticFileHandler, static_handler = (r'/(.*)', tornado.web.StaticFileHandler,
@ -232,33 +201,15 @@ class ModularServer(tornado.web.Application):
settings = {'debug': True, settings = {'debug': True,
'template_path': os.path.dirname(__file__) + '/templates'} 'template_path': os.path.dirname(__file__) + '/templates'}
def __init__(self, model, visualization_element, name='SOIL', verbose=True, def __init__(self, simulator, name='SOIL', verbose=True, *args, **kwargs):
*args, **kwargs):
self.verbose = verbose self.verbose = verbose
self.package_includes = set() self.name = name
self.local_includes = set() self.simulator = simulator
self.js_code = []
self.visualization_element = visualization_element
self.model_name = name
self.model = model
self.model_args = args
self.model_kwargs = kwargs
#self.reset_model()
# Initializing the application itself: # Initializing the application itself:
super().__init__(self.handlers, **self.settings) super().__init__(self.handlers, **self.settings)
'''
def reset_model(self):
self.model = self.model_cls(*self.model_args, **self.model_kwargs)
'''
def render_model(self):
return self.visualization_element.render(self.model)
def launch(self, port=None): def launch(self, port=None):
""" Run the app. """ """ Run the app. """

View File

@ -1,17 +1,15 @@
import os import os
import networkx as nx import networkx as nx
from server import VisualizationElement
from soil.simulation import SoilSimulation from soil.simulation import SoilSimulation
from xml.etree import ElementTree
class Model(): class Simulator():
""" Simulator for running simulations. Using SOIL."""
def __init__(self, dump=False, dir_path='output'): def __init__(self, dump=False, dir_path='output'):
self.name = 'soil' self.name = 'soil'
self.dump = dump self.dump = dump
self.dir_path = dir_path self.dir_path = dir_path
self.simulation = list()
def run(self, config): def run(self, config):
name = config['name'] name = config['name']
@ -36,15 +34,3 @@ class Model():
def reset(self): def reset(self):
pass pass
class GraphVisualization(VisualizationElement):
package_includes = []
# TODO: esta por definir todos los ajustes de simulacion
def __init__(self, params=None):
new_element = ("new funcion()")
self.js_code = "elements.push(" + new_element + ");"
def render(self, model):
pass

View File

@ -35,7 +35,7 @@
<link rel="stylesheet" type="text/css" href="css/timeline.css"> <link rel="stylesheet" type="text/css" href="css/timeline.css">
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Ubuntu+Mono" /> <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Ubuntu+Mono" />
<title>{{ model_name }}</title> <title>{{ name }}</title>
<script type="text/javascript">//<![CDATA[ <script type="text/javascript">//<![CDATA[
@ -184,7 +184,7 @@
<nav class="navbar navbar-default navbar-fixed-bottom"> <nav class="navbar navbar-default navbar-fixed-bottom">
<div class="container-fluid"> <div class="container-fluid">
<div class="navbar-header"> <div class="navbar-header">
<a class="navbar-brand" href="#">{{ model_name }}</a> <a class="navbar-brand" href="#">{{ name }}</a>
</div> </div>
<div class="collapse navbar-collapse"> <div class="collapse navbar-collapse">
<ul class="nav navbar-nav"> <ul class="nav navbar-nav">