def upload_file():

	if request.method == 'POST':
		file = request.files['file']

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            if Simulation(filename).process_all_habitat_simulations():
            	return redirect('/static/output/sample_output.txt')
            else:
        		redirect("/?error=Something went wrong on the server")

	return redirect("/?error=Something went wrong on the server")
 def post(self, model_id):
     session = Session()
     try:
         socket_id = str(uuid.uuid4())
         q = session.query(Model) \
                    .filter_by(id=model_id) \
                    .with_for_update().one()
         data = pickle.dumps(
             wrapper.create(q.name, q.system, q.inputs, q.outputs,
                            model_id))
         sim = Simulation(model_id=model_id,
                          socket_id=socket_id,
                          locked=False,
                          data=data)
         session.add(sim)
         session.flush()
         session.commit()
         # TODO: update sim.data.sim_id field with sim.id
         self.write(
             json.dumps({
                 'status': 'success',
                 'sim_id': sim.id,
                 'model_id': model_id,
                 'socket_id': socket_id,
             }))
     except sqlalchemy.orm.exc.NoResultFound:
         self.set_status(404)
         self.write(
             json.dumps({
                 'status': 'error',
                 'error': f'no model found',
             }))
         session.rollback()
     except sqlalchemy.orm.exc.MultipleResultsFound:
         self.set_status(500)
         self.write(
             json.dumps({
                 'status': 'error',
                 'error': f'multiple models found',
             }))
         session.rollback()
     except Exception as e:
         self.set_status(500)
         self.write(json.dumps({
             'status': 'error',
             'error': str(e),
         }))
         session.rollback()
     finally:
         session.close()
Exemple #3
0
def simulate(season: Season) -> Simulation:
    week_outcomes = [WeekOutcome(0, collections.defaultdict(int)) for week in season.weeks]

    if season.teams[0] == season.teams[1]:
        combinations = all_combinations_single(season.teams[0])
    else:
        combinations = all_combinations(season.teams[0], season.teams[1])

    counter = 0
    for combination in combinations:
        counter += 1
        pairing_set = set(combination)
    
        for week, is_feasible in feasible_season(season, pairing_set):
            week_outcome = week_outcomes[week.id]
            if is_feasible:
                week_outcome.total_counts += 1
                for pairing in pairing_set:
                    week_outcome.counts[pairing] += 1

    return Simulation(season, week_outcomes)
    t.populate_next_series()
    t.set_first_series_elo(elo_i)
    t.play(elo)
    elo_f = t.final_elos()
    elo_i = regressfunc(merge_elo(elo_i,elo_f))

t0 = perf_counter()
first = pd.DataFrame()
second = pd.DataFrame()
third = pd.DataFrame()
for i in range(1000):
    tc = copy.deepcopy(Tournament(season.tourneys[-1]['data']))
    tc.build_tournament()
    tc.populate_next_series()
    tc.set_first_series_elo(elo_i)
    sim = Simulation(tc)
    sim.run(elo)
    finals = sim.tournament[-1]['data']
    semis = sim.tournament[-3:-2][0]['data']
    first = first.append(finals[finals.win_b == 1])
    second = second.append(finals[finals.win_b == 0])
    third = third.append(semis[semis.win_b == 0])
t1 = perf_counter()
print('simulation time: ', round(t1-t0,1))
first.elo = first.elo.astype('float')
first.groupby('team').agg({'win_b' : 'sum','elo' : 'mean'}) \
    .sort_values('win_b',ascending=False) \
    .to_csv('../generated_data/1000_sim_champs_first.csv')
second.elo = second.elo.astype('float')
second.groupby('team').agg({'win_b' : 'count','elo' : 'mean'}) \
    .sort_values('win_b',ascending=False) \
Exemple #5
0
def parseFile(filename):
    lines = [line.rstrip('\n') for line in open(filename)]
    steps = []
    while len(lines) > 0:
        steps.append(parseStep(lines))
    return Simulation(steps, os.path.basename(filename))
Exemple #6
0
def info(bin):
    # Insert new simulation
    sim_name = basename(bin)[:-1*len('.out')]
    sim = None
    if exist(Simulation, name=sim_name):
        print 'Updating existing simulation: ' + sim_name
        sim = fetch(Simulation, name=sim_name)[0]
    else:
        # Create new simulation
        sim = Simulation(name=sim_name)
        db_session.add(sim)
        db_session.commit()

    # Delete old params
    print sim.id, sim_name

    # Get info from executable
    status, out = getstatusoutput('%s --info' % bin)
    if status != 0:
        raise RuntimeWarning('Could not get info from %s' % bin)
    lines = out.split('\n')

    # Extract types and defaults
    types    = dict(RE_types.findall(filter(lambda x: 'Parameters:' in x, lines)[0]))
    defaults = {}
    map(lambda s: defaults.update(dict([RE_default.match(s).groups()])),
        filter(lambda x: 'Param:' in x, lines))

    # Extract priority, unit information and description messages
    infos = read_params('%s.instr' % bin[:-1*len('.out')])

    # Insert param default
    convertfns = {'string' : lambda x: x,
                  'double' : float
                  }

    # Insert new params
    for param in sorted(types.keys()):
        if not exist(Param, sim_id=sim.id, name=param):
            print 'new param: ', param
            p = Param(sim=sim, name=param)
            db_session.add(p)
            db_session.commit()
        else:
            [p] = fetch(Param, sim_id=sim.id, name=param)

        if param.lower() in infos:
            priority, unit, msg = infos[param.lower()]
        else:
            priority = 100000
            unit = DEFAULT_UNIT
            msg  = DEFAULT_MSG

        p.priority = priority
        p.unit = unit
        p.msg = msg

        p.default_value = convertfns[types[param]](defaults[param])

    # Commit work so far
    db_session.commit()
Exemple #7
0
    def post(self, model_id):
        model_id = int(model_id)
        session = Session()
        try:
            # Get the pickled model from the database
            model_row = session.query(Model) \
                               .filter_by(id=model_id) \
                               .with_for_update().one()

            # Generate a unique socket_id
            socket_id = str(uuid.uuid4())

            # Create a new row in the database
            sim_row = Simulation(
                model_id=model_id,
                socket_id=socket_id,
                locked=False,
            )

            # Get the id of the row in the database
            session.add(sim_row)
            session.flush()
            sim_id = sim_row.id

            # Create a new simulation object in Python
            sim_obj = wrapper.create(
                model_id,
                sim_id,
                model_row.name,
                model_row.system,
                model_row.inputs,
                model_row.outputs,
            )

            # Pickle the simulation object into the database
            sim_row.data = pickle.dumps(sim_obj)
            session.commit()

            self.send({
                'status': 'success',
                'message': 'created new simulation',
                'sim_id': sim_id,
                'model_id': model_id,
                'socket_id': socket_id,
            })
        except sqlalchemy.orm.exc.NoResultFound:
            self.set_status(404)
            self.send({
                'status': 'error',
                'message': 'no model found',
            })
            session.rollback()
        except sqlalchemy.orm.exc.MultipleResultsFound:
            self.set_status(500)
            self.send({
                'status': 'error',
                'message': 'multiple models found',
            })
            session.rollback()
        except Exception as e:
            self.set_status(500)
            self.send({
                'status': 'error',
                'message': str(e),
            })
            session.rollback()
        finally:
            session.close()