Exemple #1
0
 def __init__(self, restore=False):
     self.p = param.Param()
     self.train_ds, self.test_ds = io.get_dataset(
         epoch=self.p.epochs, batchsize=self.p.batchsize)
     self.session = tf.Session()
     self.model_init()
     self.writer = tf.summary.FileWriter(logdir=self.p.log_path,
                                         graph=self.session.graph)
     self.saver = tf.train.Saver()
     #Variable Initialization
     with self.session.as_default():
         if (restore == False):
             self.initializer.run()
         else:
             self.saver.restore(self.session, save_path=self.p.model_path)
def run(ffield, params, train, geo):
    ''' An optimizer for LAMMPS files. '''

    #Create a log file for the optimizer
    logging.basicConfig(filename='log.opt', filemode='w', level=logging.INFO)
    lvl_set = {
        0: 'NOTSET',
        10: 'DEBUG',
        20: 'INFO',
        30: 'WARNING',
        40: 'ERROR',
        50: 'CRITICAL'
    }
    lvl = logging.getLogger().getEffectiveLevel()
    if lvl in lvl_set:
        logging.info('Logging level - string: %s, integer: %d' %
                     (lvl_set[lvl], lvl))
    else:
        logging.info('Logging level not set.')

    # --------------------------------------------------------------------------------------

    train_read = trainset.Trainset(train)  # Read in the trainset file
    ff_read = forcefield.ForceField(
        ffield)  # Read in the force field using an object
    param_read = param.Param(params)  # Read in the param file

    #if geo != None:                                              # Create data files if geo file supplied with proper valence
    #    if ff_read.get_optimizer()['valence'] == '0':
    #        geotodatalammps.data_file_complete(geo)
    #    elif ff_Read.get_optimizer()['valence'] == '1':
    #        geotodatalammps.data_file_simple(geo)

    if geo != None:  # Create data files if geo file supplied
        name = ff_read.get_name()
        if name == 'uffqm':
            geotodatalammps.data_file_complete(geo)
            #geotodatalammps.data_file_simple(geo)
        elif name == 'rexpon':
            geotodatalammps.data_file_simple(geo)
        elif name == 'morse':
            geotodatalammps.data_file_complete(geo)
        elif name == 'ljcut':
            geotodatalammps.data_file_simple(geo)
        elif name == 'exryd':
            geotodatalammps.data_file_simple(geo)
        elif name == 'exrydc':
            #geotodatalammps.data_file_libattery(geo)
            geotodatalammps.data_file_simple(geo)
        elif name == 'pprlg':
            #geotodatalammps.data_file_libattery(geo)
            geotodatalammps.data_file_simple(geo)
        else:
            logging.error(
                'ERROR: no geo file supplied, and neither uffqm, rexpon, morse, exryd, or lj/cut selected.'
            )
            print 'ERROR: no geo file supplied and neither uffqm, rexpon, morse, exryd, or lj/cut selected!'
            sys.exit()

    data_read = readData()  # Read in the data files

    logging.debug('%s' % str(ff_read.get_ffield()))

    # --------------------------------------------------------------------------------------

    init = []  # Pull the initial values of the parameters from the force field
    try:
        for k in range(len(param_read.get_bounds())):
            init.append(
                float(ff_read.get_ffield()[param_read.get_bounds()[k][0]]
                      [param_read.get_bounds()[k][1] -
                       1][param_read.get_bounds()[k][2] - 1]))
    except Exception as e:
        print "Error reading param file: ", e
        logging.error("Error reading param file: %s" % e)
        sys.exit()
    logging.info('Initial parameters read.')

    # --------------------------------------------------------------------------------------

    to_write = ""
    for i in range(len(init)):
        to_write += 'param[%d]\t' % i
    to_write += 'error\n'
    g = open('history', 'w')  # Set up the history file
    g.write(to_write)
    g.close()
    logging.info('history file created.')

    # --------------------------------------------------------------------------------------

    method = ff_read.get_optimizer()['method']
    polar = False if ff_read.get_optimizer()['polar'] == '0' else True
    algorithm = ff_read.get_optimizer()['algorithm']
    finish = ff_read.get_optimizer()['finish']

    if method == '0':  # Run without optimization
        logging.info('Optimization flag turned off.')

        res = optimizer(init,
                        data_read,
                        train_read,
                        ff_read,
                        param_read.get_bounds(),
                        polar,
                        res_print=True,
                        debugging=True,
                        disp_screen=True)

    elif method == '1':  # Call optimizer on ffield parameters

        logging.info('Optimization flag turned on, preparing to optimize.')

        bnds = ()  # Get the bounds from params
        for i in range(len(param_read.get_bounds())):
            bnds = bnds + ((param_read.get_bounds()[i][-2],
                            param_read.get_bounds()[i][-1]), )

        con = ()  # Set constraints for parameters
        for i in range(len(param_read.get_constraints())):
            con = con + ({
                'type':
                'eq',
                'fun':
                lambda x: x[param_read.get_constraints()[i][0]] - x[
                    param_read.get_constraints()[i][1]]
            }, )

        # Run the optimization
        start_time = time.time()
        if algorithm == 'slsqp':
            res = minimize(optimizer,
                           init,
                           args=(data_read, train_read, ff_read,
                                 param_read.get_bounds(), polar),
                           method='SLSQP',
                           bounds=bnds,
                           constraints=con)
        elif algorithm == 'nelder-mead':
            res = minimize(optimizer,
                           init,
                           args=(data_read, train_read, ff_read,
                                 param_read.get_bounds(), True),
                           method='Nelder-Mead',
                           options={'eps': 1e-9})  #, options={'fatol':0.01})
        else:
            print 'Error: Algorithm not supplied. Options \'None\', \'SLSQP\', and \'Nelder-Mead\''
            logging.error(
                'Error: Algorithm not supplied. Options \'None\', \'SLSQP\', and \'Nelder-Mead\''
            )
            sys.exit()
        final_time = time.time()

        write_out(
            ff_read, res.x,
            param_read.get_bounds())  # Create the fort.4 result force field

        # Create a fort.99 type file using optimized values
        optimizer(res.x,
                  data_read,
                  train_read,
                  ff_read,
                  param_read.get_bounds(),
                  polar,
                  res_print=True,
                  debugging=False)

        logging.info("Optimal parameters: %s" % res)
        logging.info('Time of optimization: %0.3f' % (final_time - start_time))

    elif method == '2':  # Perform a map
        logging.info('Optimization flag turned on, preparing to optimize.')

        rrange = ()  # Get the bounds from params
        for i in range(len(param_read.get_bounds())):
            lower = param_read.get_bounds()[i][-3]
            upper = param_read.get_bounds()[i][-2]
            steps = param_read.get_bounds()[i][-1]
            rrange = rrange + ((lower, upper, steps), )

        # Run the optimization
        start_time = time.time()
        if finish == 'none':
            res = brute(optimizer,
                        rrange,
                        args=(data_read, train_read, ff_read,
                              param_read.get_bounds(), polar),
                        finish=None)
        elif finish == 'slsqp':
            res = brute(optimizer,
                        rrange,
                        args=(data_read, train_read, ff_read,
                              param_read.get_bounds(), polar),
                        finish='SLSQP')
        elif finish == 'nelder-mead':
            res = brute(optimizer,
                        rrange,
                        args=(data_read, train_read, ff_read,
                              param_read.get_bounds(), polar),
                        finish='Nelder-Mead')
        else:
            print 'Error: Finish not supplied. Options \'None\', \'SLSQP\', and \'Nelder-Mead\''
            logging.error(
                'Error: Finish not supplied. Options \'None\', \'SLSQP\', and \'Nelder-Mead\''
            )
            sys.exit()
        final_time = time.time()

        write_out(
            ff_read, res.x,
            param_read.get_bounds())  # Create the fort.4 result force field

        # Create a fort.99 type file using optimized values
        optimizer(res.x,
                  data_read,
                  train_read,
                  ff_read,
                  param_read.get_bounds(),
                  polar,
                  res_print=True,
                  debugging=False)

        logging.info("Optimal parameters: %s" % res)

    else:
        print 'ERROR: No valid method supplied'
        logging.error('ERROR: No valid method supplied')
        sys.exit()

    return res
Exemple #3
0
import numpy as np

import os, sys, inspect
currentdir = os.path.dirname(
    os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)

import param as prm

param = prm.Param("test.param")
print param.get_float("a")
print param.get_float_list("a")
print param.get_int64("b")

cparam = prm.CosmoParam("indat.params")

print "%E" % cparam.get_particle_mass()
print "%E" % cparam.get_rho_crit()
print cparam.get_z(499)
print cparam.get_z(1)
print cparam.get_step(0)
print cparam.get_step(1)
Exemple #4
0
#!/usr/bin/python
# -*-coding:Latin-1 -*

from __future__ import print_function
import time
import param as p
import move as m

import sys
sys.path.append('../../')
# from utils.communication import Communication
# import utils.Switch as s
# déclaration des variables utiles :
param = p.Param()
move = m.Move(param.odrv0)


def demo_simple(odrv0):

    time.sleep(1)
    move.translation(500, [False, False, False, False, False])
    time.sleep(0.5)
    move.rotation(-360, [False, False, False, False, False])
    time.sleep(1)
    move.translation(-500, [False, False, False, False, False])


def test_calib_bis(odrv0):
    move.translation(100, [False, False, False, False, False])

from __future__ import absolute_import
import tensorflow as tf
import layers
import param

p = param.Param()


def build_model(inp, label):
    y1 = layers.fully_connected(inp=inp,
                                nout=p.hidden_units[0],
                                activation=tf.nn.relu,
                                scope="fc-1")
    out = layers.fully_connected(inp=y1,
                                 nout=p.num_labels,
                                 activation=tf.nn.softmax,
                                 scope="fc-2")
    with tf.variable_scope('loss'):
        loss = tf.losses.softmax_cross_entropy(logits=out, onehot_labels=label)
        tf.summary.scalar('loss', loss)
    with tf.variable_scope('accuracy'):
        accuracy = tf.reduce_mean(
            tf.cast(tf.equal(tf.argmax(label, 1), tf.argmax(out, 1)),
                    tf.float64))
        tf.summary.scalar('accuracy', accuracy)

    return out, loss, accuracy
Exemple #6
0
def create_hearbeat_param():
	return param.Param("Status:Meaner3:program_uruchomiony", "short", 0, 4, True)
Exemple #7
0
def create_meaner4_heartbeat_param():
	return param.Param(meaner4_heartbeat_param_name, "short", 0, 4, True)
Exemple #8
0
def create_hearbeat_param():
	return param.Param(heartbeat_param_name, "short", 0, 4, True)