示例#1
0
    def test_getAllItemsInAuction_Ordering(self):
        datasetAuction = Dataset(
                self.logger, './',
                self.sessionFile.getFilename(),
                self.itemFileAuctionOnly.getFilename(),
                self.currencyFile.getFilename())
        datasetAuction.restore()
        modelAuction = Model(
                self.logger,
                datasetAuction,
                self.currency)

        auctionItems = modelAuction.getAllItemsInAuction()
        auctionItems.sort(key=lambda item: item[ItemField.AUCTION_SORT_CODE])

        for item in auctionItems:
            print('{0} - {1}'.format(item[ItemField.AUTHOR], item[ItemField.AMOUNT]))

        # Check that there is no block authors larger than two
        largestBlockSize = 0
        largestBlockAuthor = None
        blockAuthor = None
        blockSize = 0
        for item in auctionItems:
            if blockAuthor is not None and item[ItemField.AUTHOR] == blockAuthor:
                blockSize = blockSize + 1
            else:
                if blockSize > largestBlockSize:
                    largestBlockSize = blockSize
                    largestBlockAuthor = blockAuthor
                blockAuthor = item[ItemField.AUTHOR]
                blockSize = 1
        self.assertGreaterEqual(2, largestBlockSize, 'Author: ' + str(largestBlockAuthor))
示例#2
0
def main(args, defaults):
    parameters = process_args(args, defaults)
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)-15s %(name)-5s %(levelname)-8s %(message)s',
        filename=parameters.log_path)
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)-15s %(name)-5s %(levelname)-8s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)

    with sess.as_default():
        model = Model(
                phase = parameters.phase,
                visualize = parameters.visualize,
                data_path = parameters.data_path,
                data_base_dir = parameters.data_base_dir,
                output_dir = parameters.output_dir,
                batch_size = parameters.batch_size,
                initial_learning_rate = parameters.initial_learning_rate,
                num_epoch = parameters.num_epoch,
                steps_per_checkpoint = parameters.steps_per_checkpoint,
                target_vocab_size = parameters.target_vocab_size, 
                model_dir = parameters.model_dir,
                target_embedding_size = parameters.target_embedding_size,
                attn_num_hidden = parameters.attn_num_hidden,
                attn_num_layers = parameters.attn_num_layers,
                load_model = parameters.load_model,
                valid_target_length = float('inf'),
                gpu_id=parameters.gpu_id,
                use_gru=parameters.use_gru,
                session = sess,
                old_model_version = parameters.old_model_version)
        model.launch()
示例#3
0
    def setUp(self):
        self.logger = logging.getLogger()

        self.testFiles = []

        self.itemFile = Datafile('test.model.items.xml', self.id())
        self.itemFileAuctionOnly = Datafile('test.model.items.auction_only.xml', self.id())
        self.sessionFile = Datafile('test.model.session.xml', self.id())
        self.currencyFile = Datafile('test.model.currency.xml', self.id())
        self.importFileCsv = Datafile('test.model.import.csv', self.id())
        self.importFileTxt = Datafile('test.model.import.txt', self.id())

        self.dataset = Dataset(
                self.logger, './',
                self.sessionFile.getFilename(),
                self.itemFile.getFilename(),
                self.currencyFile.getFilename())
        self.dataset.restore()

        self.currency = Currency(
                self.logger,
                self.dataset,
                currencyCodes=['czk', 'eur'])
        self.model = Model(
                self.logger,
                self.dataset,
                self.currency)
示例#4
0
 def __init__(self):
     self.layout = Layout(Const.WORLD)
     Display.initGraphics(self.layout)
     self.model = Model(self.layout)
     self.carChanges = {}
     self.errorCounter = Counter()
     self.consecutiveLate = 0
示例#5
0
    def __init__(self, sys_argv):

        super(App, self).__init__(sys_argv)

        self.model = Model()
        self.main_ctrl = MainController(self.model)
        self.main_view = MainView(self.model, self.main_ctrl)

        self.main_view.show()
示例#6
0
def run(data, Lambda, num_topics, num_initialization, args,
        initial_topic_centers, initial_topic_covar, track_params):

    print("\n=== [k = {0}] INITIALIZATION NUMBER {1} ===\n\n".format(num_topics,
        num_initialization))

    # TODO add explanation in comment
    seed = int(time.time() * 1e6 * (num_initialization + 1)) % int(time.time())
    np.random.seed(seed)

    # Initialize model
    model = Model(Lambda, num_topics, args.iter, args.rel_change,
        initial_topic_centers, initial_topic_covar,
        track_params=track_params, verbose=args.verbose)

    model.fit(data)

    return model
示例#7
0
class ModelTest(TestCase):
    def setUp(self):
        self.volume = 1e-18
        self.model = Model()
        self.function_maker = FunctionMaker()

    def test_basic(self):
        S1 = self.model.new_species_type(name='S1')
        S2 = self.model.new_species_type(name='S2')
        P = self.model.new_species_type(name='P')

        # S1 + S2 -> P    k=.3
        self.model.network_rules.add([S1, S2], [P], k=.3)
        # P -> S1 + S2    k=.1 (inverse reaction)
        self.model.network_rules.add([P], [S1, S2], k=.1)

        # Make Function list
        functions = self.function_maker.make_functions(self.model, self.volume)

        species = list(self.model.network_rules.all_species())
        self.assertEqual(len(functions), len(species))
示例#8
0
class App(QtGui.QApplication):
    def __init__(self, sys_argv):

        super(App, self).__init__(sys_argv)

        self.model = Model()
        self.main_ctrl = MainController(self.model)
        self.main_view = MainView(self.model, self.main_ctrl)

        self.main_view.show()

    "Attempt to enable global key presses and key releases"

    def notify(self, receiver, event):

        if self.model.get_output_popup_open_status() == False:

            if event.type() == QtCore.QEvent.KeyPress:
                self.main_view.keyboard.keyPressEvent(event)

            elif event.type() == QtCore.QEvent.KeyRelease:
                self.main_view.keyboard.keyReleaseEvent(event)

        # Call Base Class Method to Continue Normal Event Processing

        return super(App, self).notify(receiver, event)

    def closeEvent(self, event):

        quit_msg = "Are you sure you want to exit the program?"
        reply = QtGui.QMessageBox.question(self, "Message", quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            if self.main_ctrl.output_ctrl.midi_port_open() is True:
                self.main_ctrl.output_ctrl.midiout.close()

            event.accept()
        else:
            event.ignore()
def compute_feature_contribution(db, model_path: str, venue_extractors, checkin_extractors):
    """
    Loads model files under given folder and computes likelihood drops for each model and for each feature,
    when the respective etas are set to zero.

    Querying of the database is done by reading .desc files and finding from there the query used to train the model.

    :param db: Mongo database instance to load data points from (use get_mongo_database_with_auth)
    :param model_path: path to directory where model files reside
    :return:
    """
    model_prefixes = [model_path + "/" + e[:-4:] for e in os.listdir(model_path) if ".mdl" in e]

    total_results = {}

    prev_dbquery = ""
    for model_prefix in model_prefixes:
        # Find the query for given model and fetch relevant data from the DB
        dbquery = ""
        with open(model_prefix + ".desc") as f:
            content = f.readlines()

            for line in content:
                if line[0:6] == "Query:":
                    dbquery = line[7::]

        model = pickle.load(open(model_prefix + ".mdl", "rb"))
        scaler = pickle.load(open(model_prefix + ".scaler", "rb"))
        unigrams = pickle.load(open(model_prefix + ".unigrams", "rb"))

        print("Processing {}.".format(model_prefix))
        # Do not load the data twice if we are operating on the same data.
        if dbquery != prev_dbquery:
            raw_data = io.fetch_data_from_mongo(db["venues"], db["checkins_gte5"], dbquery, venue_extractors,
                                                checkin_extractors)

            # Normalize geographical coordinates
            raw_data["coordinates"] = scaler.transform(raw_data["coordinates"])

            # Construct sparse matrices
            features = [feature for feature in raw_data.keys() if feature not in ["coordinates", "counts", "unigrams"]]

        data = {"coordinates": raw_data["coordinates"]}

        for feature in features:
            if feature == 'user' and os.path.isfile(model_prefix + ".svdfeatmap"):
                svdfeatmap = pickle.load(open(model_prefix + ".svdfeatmap", "rb"))

                data[feature] = io.get_sparse_occur_matrix(raw_data[feature], svdfeatmap)[:, 0:len(unigrams[feature])]
            else:
                unigram_ids = dict([(w, i) for i, w in enumerate(unigrams[feature])])
                data[feature] = io.get_sparse_occur_matrix(raw_data[feature], unigram_ids)

        # Compute likelihoods
        orig_ll = model.predict_log_probs(data)

        results = {"orig": orig_ll}
        for feature in features:
            betas = model.beta_arrays[feature]
            model.beta_arrays[feature] = Model.get_topic_unigram(model.m_arrays[feature], np.zeros_like(betas))
            ll = model.predict_log_probs(data)
            results[feature] = ll
            model.beta_arrays[feature] = betas

        without_geo = compute_probabilities_from_mixture(model, data)

        results["geo"] = without_geo
        total_results[model_prefix] = results

        prev_dbquery = dbquery
    return total_results
示例#10
0
from arch.Word2Vec import Word2Vec
from pipe.ConvertWordIds import convertWordIds
from model.model import Model
from pipe.DownSample import DownSample
from pipe.createInputTasks import createW2VInputTasks
from tools.word2vec import save
from tools.worddict import buildvocab
from pipe.ContextWindows import contextWindow

# Word2Vec uses Skipgram by default, set negative > 0 to use negative sampling instead of Hierarchical Softmax
if __name__ == "__main__":
    m = Model(alpha=0.025, vectorsize=100,
                 input="data/text8",
                 inputrange=None, # means all
                 build=[ buildvocab ],
                 pipeline=[ createW2VInputTasks, convertWordIds, DownSample, contextWindow, Word2Vec ],
                 mintf=5, cores=2, threads=3, windowsize=5, downsample=0.001, iterations=1, negative=5)
    m.run()
    save("results/vectors.sgns.bin", m, binary=True)

示例#11
0
class Controller:
    def __init__(self):
        self.model = Model()
        self.view = View()

    def start(self):
        self.view.start()
        self.menu_inicio()

    def menu_inicio(self):
        o = '0'
        while o != '3':
            self.view.menu_inicio()
            self.view.option('3')
            o = input()
            if o == '1':
                c = self.comprobacion_creeciales()
                if c:
                    self.main_menu()
                else:
                    self.start()
            elif o == '2':
                self.main_menu_not_admin()
            elif o == '3':
                self.view.end()
            else:
                self.view.not_valid_option()
        return

    def main_menu(self):
        o = '0'
        while o != '7':
            self.view.main_menu()
            self.view.option('7')
            o = input()
            if o == '1':
                self.menu_peliculas()
            elif o == '2':
                self.menu_salas()
            elif o == '3':
                self.menu_proyecciones()
            elif o == '4':
                self.menu_asientos()
            elif o == '5':
                self.menu_boletos()
            elif o == '6':
                self.menu_usuarios()
            elif o == '7':
                self.view.end()
            else:
                self.view.not_valid_option()
        return

    def main_menu_not_admin(self):
        o = '0'
        while o != '5':
            self.view.menu_not_admin()
            self.view.option('5')
            o = input()
            if o == '1':
                self.menu_peliculas_not_admin()
            elif o == '2':
                self.menu_salas_not_admin()
            elif o == '3':
                self.menu_proyecciones_not_amin()
            elif o == '4':
                self.menu_asientos_not_admin()
            elif o == '5':
                self.view.end()
            else:
                self.view.not_valid_option()
        return

    def update_lists(self, fs, vs):
        fields = []
        vals = []
        for f, v in zip(fs, vs):
            if v != '':
                fields.append(f + ' = %s')
                vals.append(v)
        return fields, vals

# Controllers for Peliculas

    def menu_peliculas(self):
        o = '0'
        while o != '8':
            self.view.peliculas_menu()
            self.view.option('8')
            o = input()
            if o == '1':
                self.create_pelicula()
            elif o == '2':
                self.read_a_pelicula()
            elif o == '3':
                self.read_peliculas()
            elif o == '4':
                self.read_peliculas_genero()
            elif o == '5':
                self.read_peliculas_director()
            elif o == '6':
                self.update_pelicula()
            elif o == '7':
                self.delete_pelicula()
            elif o == '8':
                return
            else:
                self.view.not_valid_option()
        return

    def menu_peliculas_not_admin(self):
        o = '0'
        while o != '5':
            self.view.peliculas_menu_not_admin()
            self.view.option('5')
            o = input()
            if o == '1':
                self.read_a_pelicula()
            elif o == '2':
                self.read_peliculas()
            elif o == '3':
                self.read_peliculas_genero()
            elif o == '4':
                self.read_peliculas_director()
            elif o == '5':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_pelicula(self):
        self.view.ask('Titulo: ')
        titulo = input()
        self.view.ask('Nacionalidad: ')
        nacionalidad = input()
        self.view.ask('Director: ')
        director = input()
        self.view.ask('Clasificacion: ')
        clasificacion = input()
        self.view.ask('Sinopsis: ')
        sinopsis = input()
        self.view.ask('Duracion: ')
        duracion = input()
        self.view.ask('Fecha Estreno: ')
        f_estreno = input()
        self.view.ask('Genero: ')
        genero = input()
        return [
            titulo, nacionalidad, director, clasificacion, sinopsis, duracion,
            f_estreno, genero
        ]

    def create_pelicula(self):
        titulo, nacionalidad, director, clasificacion, sinopsis, duracion, f_estreno, genero = self.ask_pelicula(
        )
        out = self.model.create_pelicula(titulo, nacionalidad, director,
                                         clasificacion, sinopsis, duracion,
                                         f_estreno, genero)
        if out == True:
            self.view.ok(titulo + ' ' + f_estreno, 'agrego')
        else:
            self.view.error('No se pudo agregar la pelicula. REVISA')
        return

    def read_a_pelicula(self):
        self.view.ask('ID Pelicula: ')
        id_pelicula = input()
        pelicula = self.model.read_a_pelicula(id_pelicula)
        if type(pelicula) == tuple:
            self.view.show_pelicula_header('  Datos de la Pelicula ' +
                                           id_pelicula + ' ')
            self.view.show_a_pelicula(pelicula)
            self.view.show_peliculas_midder()
            self.view.show_peliculas_footer()
        else:
            if pelicula == None:
                self.view.error('LA PELICULA NO EXISTE')
            else:
                self.view.error('PROBLEMA AL LEER LA PELICULA. REVISA.')
        return

    def read_peliculas(self):
        peliculas = self.model.read_peliculas()
        if type(peliculas) == list:
            self.view.show_pelicula_header('Todas las peliculas')
            for pelicula in peliculas:
                self.view.show_a_pelicula(pelicula)
            self.view.show_peliculas_midder()
            self.view.show_peliculas_footer()
        else:
            self.view.error('PROBLEMA AL LEER  LAS PELICULAS. REVISA')
        return

    def read_peliculas_director(self):
        self.view.ask('Director: ')
        director = input()
        peliculas = self.model.read_peliculas_director(director)
        if type(peliculas) == list:
            self.view.show_pelicula_header('  Peliculas de ' + director + ' ')
            for pelicula in peliculas:
                self.view.show_a_pelicula(pelicula)
            self.view.show_peliculas_midder()
            self.view.show_peliculas_footer()
        else:
            self.view.error('PROBLEMA AL LEER  LAS PELICULAS. REVISA')
        return

    def read_peliculas_genero(self):
        self.view.ask('Genero: ')
        genero = input()
        peliculas = self.model.read_peliculas_genero(genero)
        if type(peliculas) == list:
            self.view.show_pelicula_header('  Peliculas de ' + genero + ' ')
            for pelicula in peliculas:
                self.view.show_a_pelicula(pelicula)
            self.view.show_peliculas_midder()
            self.view.show_peliculas_footer()
        else:
            self.view.error('PROBLEMA AL LEER  LAS PELICULAS. REVISA')
        return

    def update_pelicula(self):
        self.view.ask('ID de la pelucula a modificar: ')
        id_pelicula = input()
        pelicula = self.model.read_a_pelicula(id_pelicula)
        if type(pelicula) == tuple:
            self.view.show_pelicula_header('  Datos de la Pelicula ' +
                                           id_pelicula + ' ')
            self.view.show_a_pelicula(pelicula)
            self.view.show_peliculas_midder()
            self.view.show_peliculas_footer()
        else:
            if pelicula == None:
                self.view.error('La pelicula no existe')
            else:
                self.view.error('Problemas al leer la pelicula, REVISA')
            return
        self.view.msg(
            'Ingresa los valores a modificar:(vacio para dejarlo igual)')
        whole_vals = self.ask_pelicula()
        fields, vals = self.update_lists([
            'titulo', 'nacionalidad', 'director', 'clasificacion', 'sinopsis',
            'duracion', 'f_estreno', 'genero'
        ], whole_vals)
        vals.append(id_pelicula)
        vals = tuple(vals)
        out = self.model.update_pelicula(fields, vals)
        if out == True:
            self.view.ok(id_pelicula, 'actualizo')
        else:
            self.view.error('No se pudo actualizar la pelucula. REVISA')
        return

    def delete_pelicula(self):
        self.view.ask('ID Pelicula a borrar: ')
        id_pelicula = input()
        count = self.model.delete_pelicula(id_pelicula)
        if count != 0:
            self.view.ok(id_pelicula, 'borro')
        else:
            if count == 0:
                self.view.error('La pelicula no existe')
            else:
                self.view.error('Problemas al leer la pelicula. REVISA')
        return

#Controllers for salas

    def menu_salas(self):
        o = '0'
        while o != '6':
            self.view.salas_menu()
            self.view.option('6')
            o = input()
            if o == '1':
                self.create_sala()
            elif o == '2':
                self.read_a_sala()
            elif o == '3':
                self.read_salas()
            elif o == '4':
                self.update_sala()
            elif o == '5':
                self.delete_sala()
            elif o == '6':
                return
            else:
                self.view.not_valid_option()
        return

    def menu_salas_not_admin(self):
        o = '0'
        while o != '3':
            self.view.salas_menu_not_admin()
            self.view.option('3')
            o = input()
            if o == '1':
                self.read_a_sala()
            elif o == '2':
                self.read_salas()
            elif o == '3':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_sala(self):
        self.view.ask('Tipo: ')
        tipo = input()
        self.view.ask('Numero Asientos: ')
        no_asientos = input()
        return [tipo, no_asientos]

    def create_sala(self):
        tipo, no_asientos = self.ask_sala()
        out = self.model.create_salas(tipo, no_asientos)
        if out == True:
            self.view.ok(tipo + ' con asientos: ' + no_asientos, '  agrego')
        else:
            self.view.error('No se pudo agregar la sala. REVISA')
        return

    def read_a_sala(self):
        self.view.ask('ID Sala: ')
        id_sala = input()
        sala = self.model.read_a_sala(id_sala)
        if type(sala) == tuple:
            self.view.show_salas_header('  Datos de la sala ' + id_sala + ' ')
            self.view.show_a_sala(sala)
            self.view.show_salas_midder()
            self.view.show_salas_footer()
        else:
            if sala == None:
                self.view.error('LA SALA NO EXISTE')
            else:
                self.view.error('PROBLEMA AL LEER LA SALA. REVISA.')
        return

    def read_salas(self):
        salas = self.model.read_salas()
        if type(salas) == list:
            self.view.show_salas_header('Todas las Salas')
            for sala in salas:
                self.view.show_a_sala(sala)
            self.view.show_salas_midder()
            self.view.show_salas_footer()
        else:
            self.view.error('PROBLEMA AL LEER  LAS SALAS. REVISA')
        return

    def update_sala(self):
        self.view.ask('ID de la sala a modificar: ')
        id_sala = input()
        sala = self.model.read_a_sala(id_sala)
        if type(sala) == tuple:
            self.view.show_salas_header('  Datos de la sala ' + id_sala + ' ')
            self.view.show_a_sala(sala)
            self.view.show_salas_midder()
            self.view.show_salas_footer()
        else:
            if sala == None:
                self.view.error('La sala no existe')
            else:
                self.view.error('Problemas al leer la sala, REVISA')
            return
        self.view.msg(
            'Ingresa los valores a modificar:(vacio para dejarlo igual)')
        whole_vals = self.ask_sala()
        fields, vals = self.update_lists(['tipo', 'no_asientos'], whole_vals)
        vals.append(id_sala)
        vals = tuple(vals)
        out = self.model.update_sala(fields, vals)
        if out == True:
            self.view.ok(id_sala, 'actualizo')
        else:
            self.view.error('No se pudo actualizar la sala. REVISA')
        return

    def delete_sala(self):
        self.view.ask('ID sala a borrar: ')
        id_sala = input()
        count = self.model.delete_sala(id_sala)
        if count != 0:
            self.view.ok(id_sala, 'borro')
        else:
            if count == 0:
                self.view.error('La sala no existe')
            else:
                self.view.error('Problemas al leer la sala. REVISA')
        return

    #Controllers for proyecciones
    def menu_proyecciones(self):
        o = '0'
        while o != '6':
            self.view.proyecciones_menu()
            self.view.option('6')
            o = input()
            if o == '1':
                self.create_proyeccion()
            elif o == '2':
                self.read_a_proyeccion()
            elif o == '3':
                self.read_proyecciones()
            elif o == '4':
                self.update_proyeccion()
            elif o == '5':
                self.delete_proyeccion()
            elif o == '6':
                return
            else:
                self.view.not_valid_option()
        return

    def menu_proyecciones_not_amin(self):
        o = '0'
        while o != '3':
            self.view.proyecciones_menu_not_admin()
            self.view.option('3')
            o = input()
            if o == '1':
                self.read_a_proyeccion()
            elif o == '2':
                self.read_proyecciones()
            elif o == '3':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_proyeccion(self):
        self.view.ask('Hora: ')
        hora = input()
        self.view.ask('Lenguaje: ')
        lenguaje = input()
        self.view.ask('Costo: ')
        costo = input()
        self.view.ask('Fecha Proyeccion: ')
        f_proyeccion = input()
        self.view.ask('ID pelicula: ')
        id_pelicula = input()
        self.view.ask('ID sala: ')
        id_sala = input()
        return [hora, lenguaje, costo, f_proyeccion, id_pelicula, id_sala]

    def create_proyeccion(self):
        hora, lenguaje, costo, f_proyeccion, id_pelicula, id_sala = self.ask_proyeccion(
        )
        out = self.model.create_proyeccion(hora, lenguaje, costo, f_proyeccion,
                                           id_pelicula, id_sala)
        if out == True:
            self.view.ok(hora + ' ' + f_proyeccion, ' agrego')
        else:
            self.view.error('No se pudo agregar la proyeccion. REVISA')
        return

    def read_a_proyeccion(self):
        self.view.ask('ID Proyeccion: ')
        id_proyeccion = input()
        proyeccion = self.model.read_a_proyeccion(id_proyeccion)
        if type(proyeccion) == tuple:
            self.view.show_proyecciones_header('  Datos de la proyeccion ' +
                                               id_proyeccion + ' ')
            self.view.show_a_proyeccion(proyeccion)
            self.view.show_proyecciones_midder()
            self.view.show_proyecciones_footer()
        else:
            if proyeccion == None:
                self.view.error('LA PROYECCION NO EXISTE')
            else:
                self.view.error('PROBLEMA AL LEER LA proyeccion. REVISA.')
        return

    def read_proyecciones(self):
        proyecciones = self.model.read_proyecciones()
        if type(proyecciones) == list:
            self.view.show_proyecciones_header('Todas las Proyecciones')
            for proyeccion in proyecciones:
                self.view.show_a_proyeccion(proyeccion)
            self.view.show_proyecciones_midder()
            self.view.show_proyecciones_footer()
        else:
            self.view.error('PROBLEMA AL LEER  LAS PROYECCIONES. REVISA')
        return

    def update_proyeccion(self):
        self.view.ask('ID de la proyeccion a modificar: ')
        id_proyeccion = input()
        proyeccion = self.model.read_a_proyeccion(id_proyeccion)
        if type(proyeccion) == tuple:
            self.view.show_proyecciones_header('  Datos de la proyeccion ' +
                                               id_proyeccion + ' ')
            self.view.show_a_proyeccion(proyeccion)
            self.view.show_proyecciones_midder()
            self.view.show_proyecciones_footer()
        else:
            if proyeccion == None:
                self.view.error('La proyeccion no existe')
            else:
                self.view.error('Problemas al leer la proyeccion, REVISA')
            return
        self.view.msg(
            'Ingresa los valores a modificar:(vacio para dejarlo igual)')
        whole_vals = self.ask_proyeccion()
        fields, vals = self.update_lists([
            'hora', 'lenguaje', 'costo', 'f_proyeccion', 'id_pelicula',
            'id_sala'
        ], whole_vals)
        vals.append(id_proyeccion)
        vals = tuple(vals)
        out = self.model.update_proyeccion(fields, vals)
        if out == True:
            self.view.ok(id_proyeccion, 'actualizo')
        else:
            self.view.error('No se pudo actualizar la proyeccion. REVISA')
        return

    def delete_proyeccion(self):
        self.view.ask('ID proyeccion a borrar: ')
        id_proyeccion = input()
        count = self.model.delete_proyeccion(id_proyeccion)
        if count != 0:
            self.view.ok(id_proyeccion, 'borro')
        else:
            if count == 0:
                self.view.error('La proyeccion no existe')
            else:
                self.view.error('Problemas al leer la proyeccion. REVISA')
        return

    #Controllers for asientos
    def menu_asientos(self):
        o = '0'
        while o != '6':
            self.view.asientos_menu()
            self.view.option('6')
            o = input()
            if o == '1':
                self.create_asiento()
            elif o == '2':
                self.read_a_asiento()
            elif o == '3':
                self.read_asientos()
            elif o == '4':
                self.update_asiento()
            elif o == '5':
                self.delete_asiento()
            elif o == '6':
                return
            else:
                self.view.not_valid_option()
        return

    def menu_asientos_not_admin(self):
        o = '0'
        while o != '3':
            self.view.asientos_menu_not_admin()
            self.view.option('3')
            o = input()
            if o == '1':
                self.read_a_asiento()
            elif o == '2':
                self.read_asientos()
            elif o == '3':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_asiento(self):
        self.view.ask('Disponible: ')
        disponible = input()
        self.view.ask('ID Sala: ')
        id_sala = input()
        return [disponible, id_sala]

    def create_asiento(self):
        disponible, id_sala = self.ask_asiento()
        out = self.model.create_asiento(disponible, id_sala)
        if out == True:
            self.view.ok(id_sala + ' ' + disponible, ' agrego')
        else:
            self.view.error('No se pudo agregar el asiento. REVISA')
        return

    def read_a_asiento(self):
        self.view.ask('ID Asiento: ')
        id_asiento = input()
        asiento = self.model.read_a_asiento(id_asiento)
        if type(asiento) == tuple:
            self.view.show_asiento_header('  Datos de el asieneto ' +
                                          id_asiento + ' ')
            self.view.show_a_asiento(asiento)
            self.view.show_asiento_midder()
            self.view.show_asiento_footer()
        else:
            if asiento == None:
                self.view.error('EL ASIENTO NO EXISTE')
            else:
                self.view.error('PROBLEMA AL LEER EL ASIENTO. REVISA.')
        return

    def read_asientos(self):
        asientos = self.model.read_asientos()
        if type(asientos) == list:
            self.view.show_salas_header('Todas los Asientos')
            for asiento in asientos:
                self.view.show_a_asiento(asiento)
            self.view.show_asiento_midder()
            self.view.show_asiento_footer()
        else:
            self.view.error('PROBLEMA AL LEER  LAOS ASIENTOS. REVISA')
        return

    def update_asiento(self):
        self.view.ask('ID de el asiento a modificar: ')
        id_asiento = input()
        asiento = self.model.read_a_asiento(id_asiento)
        if type(asiento) == tuple:
            self.view.show_asiento_header('  Datos de el asiento ' +
                                          id_asiento + ' ')
            self.view.show_a_asiento(asiento)
            self.view.show_asiento_midder()
            self.view.show_asiento_footer()
        else:
            if asiento == None:
                self.view.error('El asiento no existe')
            else:
                self.view.error('Problemas al leer el asiento, REVISA')
            return
        self.view.msg(
            'Ingresa los valores a modificar:(vacio para dejarlo igual)')
        whole_vals = self.ask_asiento()
        fields, vals = self.update_lists(['disponible', 'id_sala'], whole_vals)
        vals.append(id_asiento)
        vals = tuple(vals)
        out = self.model.update_asiento(fields, vals)
        if out == True:
            self.view.ok(id_asiento, 'actualizo')
        else:
            self.view.error('No se pudo actualizar el asiento. REVISA')
        return

    def delete_asiento(self):
        self.view.ask('ID asiento a borrar: ')
        id_asiento = input()
        count = self.model.delete_asiento(id_asiento)
        if count != 0:
            self.view.ok(id_asiento, 'borro')
        else:
            if count == 0:
                self.view.error('El asiento no existe')
            else:
                self.view.error('Problemas al leer el asiento. REVISA')
        return

    #Controllers for boletos
    def menu_boletos(self):
        o = '0'
        while o != '6':
            self.view.boletos_menu()
            self.view.option('6')
            o = input()
            if o == '1':
                self.create_boleto()
            elif o == '2':
                self.read_a_boleto()
            elif o == '3':
                self.read_boletos()
            elif o == '4':
                self.update_boleto()
            elif o == '5':
                self.delete_boleto()
            elif o == '6':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_boleto(self):
        self.view.ask('ID proyeccion: ')
        id_proyeccion = input()
        self.view.ask('ID asiento: ')
        id_asiento = input()
        self.view.ask('ID sala: ')
        id_sala = input()
        return [id_proyeccion, id_asiento, id_sala]

    def create_boleto(self):
        id_proyeccion, id_asiento, id_sala = self.ask_boleto()
        out = self.model.create_boleto(id_proyeccion, id_asiento, id_sala)
        if out == True:
            self.view.ok(id_proyeccion + ' ' + id_asiento, ' agrego')
        else:
            self.view.error('No se pudo agregar el boleto. REVISA')
        return

    def read_a_boleto(self):
        self.view.ask('ID boleto: ')
        id_boleto = input()
        boleto = self.model.read_a_boleto(id_boleto)
        if type(boleto) == tuple:
            self.view.show_boleto_header('  Datos de el boleto ' + id_boleto +
                                         ' ')
            self.view.show_a_boleto(boleto)
            self.view.show_boleto_midder()
            self.view.show_boleto_footer()
        else:
            if boleto == None:
                self.view.error('EL BOLETO NO EXISTE')
            else:
                self.view.error('PROBLEMA AL LEER EL BOLETO. REVISA.')
        return

    def read_boletos(self):
        boletos = self.model.read_boletos()
        if type(boletos) == list:
            self.view.show_boleto_header('Todas los Asientos')
            for boleto in boletos:
                self.view.show_a_boleto(boleto)
            self.view.show_boleto_midder()
            self.view.show_boleto_footer()
        else:
            self.view.error('PROBLEMA AL LEER  LOS BOLETOS. REVISA')
        return

    def update_boleto(self):
        self.view.ask('ID de el boleto a modificar: ')
        id_boleto = input()
        boleto = self.model.read_a_boleto(id_boleto)
        if type(boleto) == tuple:
            self.view.show_boleto_header('  Datos de el boleto ' + id_boleto +
                                         ' ')
            self.view.show_a_boleto(boleto)
            self.view.show_boleto_midder()
            self.view.show_boleto_footer()
        else:
            if boleto == None:
                self.view.error('El boleto no existe')
            else:
                self.view.error('Problemas al leer el boleto, REVISA')
            return
        self.view.msg(
            'Ingresa los valores a modificar:(vacio para dejarlo igual)')
        whole_vals = self.ask_boleto()
        fields, vals = self.update_lists(
            ['id_proyeccion', 'id_asiento', 'id_sala'], whole_vals)
        vals.append(id_boleto)
        vals = tuple(vals)
        out = self.model.update_boleto(fields, vals)
        if out == True:
            self.view.ok(id_boleto, 'actualizo')
        else:
            self.view.error('No se pudo actualizar el boleto. REVISA')
        return

    def delete_boleto(self):
        self.view.ask('ID boleto a borrar: ')
        id_boleto = input()
        count = self.model.delete_boleto(id_boleto)
        if count != 0:
            self.view.ok(id_boleto, 'borro')
        else:
            if count == 0:
                self.view.error('El boleto no existe')
            else:
                self.view.error('Problemas al leer el boleto. REVISA')
        return

    #Controllers for USuarios
    def menu_usuarios(self):
        o = '0'
        while o != '6':
            self.view.usuarios_menu()
            self.view.option('6')
            o = input()
            if o == '1':
                self.create_usuario()
            elif o == '2':
                self.read_a_usuario()
            elif o == '3':
                self.read_usuarios()
            elif o == '4':
                self.update_usuario()
            elif o == '5':
                self.delete_usuario()
            elif o == '6':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_usuario(self):
        self.view.ask('Username: '******'Contraseña: ')
        contraseña = input()
        return [username, contraseña]

    def inicio_sesion(self):
        self.view.ask('Username: '******'Contraseña: ')
        contraseña = getpass.getpass("Contraseña: ")
        return [username, contraseña]

    def comprobacion_creeciales(self):
        usuario, contraseña = self.inicio_sesion()
        c = self.model.comprobacion_usuario(usuario, contraseña)
        return c

    def create_usuario(self):
        username, contraseña = self.ask_usuario()
        out = self.model.create_user(username, contraseña)
        if out == True:
            self.view.ok(username + ' ' + contraseña, ' agrego')
        else:
            self.view.error('No se pudo agregar el usuario. REVISA')
        return

    def read_a_usuario(self):
        self.view.ask('ID usuario: ')
        id_usuario = input()
        usuario = self.model.read_a_user(id_usuario)
        if type(usuario) == tuple:
            self.view.show_usuario_header('  Datos de el usuario ' +
                                          id_usuario + ' ')
            self.view.show_a_usuario(usuario)
            self.view.show_usuario_midder()
            self.view.show_usuario_footer()
        else:
            if usuario == None:
                self.view.error('EL USUARIO NO EXISTE')
            else:
                self.view.error('PROBLEMA AL LEER EL USUSARIO. REVISA.')
        return

    def read_usuarios(self):
        usuarios = self.model.read_users()
        if type(usuarios) == list:
            self.view.show_usuario_header('Todos los Usuarios')
            for usuario in usuarios:
                self.view.show_a_usuario(usuario)
            self.view.show_usuario_midder()
            self.view.show_usuario_footer()
        else:
            self.view.error('PROBLEMA AL LEER  LOS USUARIOS. REVISA')
        return

    def update_usuario(self):
        self.view.ask('ID de el usuario a modificar: ')
        id_usuario = input()
        usuario = self.model.read_a_user(id_usuario)
        if type(usuario) == tuple:
            self.view.show_usuario_header('  Datos de el usuario ' +
                                          id_usuario + ' ')
            self.view.show_a_usuario(usuario)
            self.view.show_usuario_midder()
            self.view.show_usuario_footer()
        else:
            if usuario == None:
                self.view.error('El usuario no existe')
            else:
                self.view.error('Problemas al leer el usuario, REVISA')
            return
        self.view.msg(
            'Ingresa los valores a modificar:(vacio para dejarlo igual)')
        whole_vals = self.ask_usuario()
        fields, vals = self.update_lists(['username', 'contraseña'],
                                         whole_vals)
        vals.append(id_usuario)
        vals = tuple(vals)
        out = self.model.update_user(fields, vals)
        if out == True:
            self.view.ok(id_usuario, 'actualizo')
        else:
            self.view.error('No se pudo actualizar el usuario. REVISA')
        return

    def delete_usuario(self):
        self.view.ask('ID usuario a borrar: ')
        id_usuario = input()
        count = self.model.delete_user(id_usuario)
        if count != 0:
            self.view.ok(id_usuario, 'borro')
        else:
            if count == 0:
                self.view.error('El usuario no existe')
            else:
                self.view.error('Problemas al leer el usuario. REVISA')
        return
示例#12
0
class Controller:
    def __init__(self):
        self.root = tk.Tk()
        self.view = View(self.root, self)
        # initialize states:
        self.still_playing = True
        self.parameters_game = None
        self.success = True

    def run(self):
        ''' Starts running out the tkinter application. '''
        self.root.mainloop()

    def start_game(self):
        ''' Starts the game.
        Start by collecting the parameters of the game chosen by the user.
        If these are new parameters then the current record is restarted.
        The model is then initialized, and the first round launched. '''
        logger.info('The game starts')
        if self.parameters_game != self.view.collect_parameters(
        ):  # new parameters => new record
            self.view.update_record('-')
        self.parameters_game = self.view.collect_parameters()
        self.model = Model(*self.parameters_game)  # init the model
        self.launch_round()  # first round

    def launch_round(self):
        ''' Launchs a new round. 
        If the user failed the last round, then self.success is False and the current challenge remains the same: 
        the user has to succeed the calculation to get a new one. '''
        logger.info('New rounds launched.')
        if self.success:
            self.current_challenge = self.model.generate_challenge()
        logger.info('The current challenge is {}.'.format(
            self.current_challenge))
        self.view.display_message(self.current_challenge, 1)

    def _check_answer(self, user_answer):
        ''' Sends the user answer to the Model in order to assess it. '''
        self.success, self.still_playing = self.model.assess_answer(
            user_answer)
        if self.success:
            logger.info('The player succeeded the round.')
            self.view.display_message('congratulations!')
        else:
            logger.info('The player failed the round.')
            self.view.display_message('sorry bro ...  you failed!')

    def handle_answer(self, user_answer):
        logger.info('The player user answer is {}.'.format(user_answer))
        self._check_answer(user_answer)
        if self.still_playing:
            self.launch_round()
        else:
            time_played = self.view.get_time()
            current_record = self.view.get_record()
            if current_record == '-' or time_played < current_record:  # new record
                self.view.update_record(time_played)
                self.view.display_message(
                    'The game is now finished. \nYour time performance is {}! NEW RECORD ! \nYour percentage of success is {}%'
                    .format(time_played, self.model.percentage_success))
            else:
                self.view.display_message(
                    'The game is now finished. \nYour time performance is {}! \nYour percentage of success is {}%'
                    .format(time_played, self.model.percentage_success))
            self.view.restart()
示例#13
0
 def __init__(self):
     self.model = Model()
     self.view = View()
示例#14
0
class Agent:
    def __init__(self,
                 sims,
                 init_nodes=500000,
                 backend='tensorflow',
                 env=None,
                 env_args=((22, 10), 1),
                 n_actions=7,
                 saver=None,
                 stochastic_inference=False,
                 min_visits=30):

        self.sims = sims

        self.init_nodes = init_nodes
        self.backend = backend

        self.env = env
        self.env_args = env_args

        self.episode = 0

        self.min_visits = min_visits

        self.n_actions = n_actions

        self.saver = saver

        self.stochastic_inference = stochastic_inference

        self.init_array()
        self.init_model()

    def init_array(self):

        child_arr = np.zeros((self.init_nodes, self.n_actions), dtype=np.int32)
        child_stats_arr = np.zeros((self.init_nodes, 6, self.n_actions),
                                   dtype=np.float32)
        node_stats_arr = np.zeros((self.init_nodes, 5), dtype=np.float32)
        node_ep_arr = np.zeros((self.init_nodes, ), dtype=np.int32)
        self.arrs = {
            'child': child_arr,
            'child_stats': child_stats_arr,
            'node_stats': node_stats_arr,
            'node_ep': node_ep_arr,
        }

        self.game_arr = [
            self.env(*self.env_args) for i in range(self.init_nodes)
        ]

        self.available = deque(range(1, self.init_nodes),
                               maxlen=self.init_nodes)
        self.occupied = deque([0], maxlen=self.init_nodes)

        self.node_index_dict = dict()

        self.max_nodes = self.init_nodes

    def init_model(self):

        if self.backend == 'tensorflow':
            from model.model import Model
            import tensorflow as tf

            self.sess = tf.Session()

            self.model = Model()
            self.model.load(self.sess)

            self.inference = lambda state: self.model.inference(
                self.sess, state[None, :, :, None])

        elif self.backend == 'pytorch':
            from model.model_pytorch import Model
            self.model = Model()
            self.model.load()

            if self.stochastic_inference:
                self.inference = lambda state: self.model.inference_stochastic(
                    state[None, None, :, :])
            else:
                self.inference = lambda state: self.model.inference(state[
                    None, None, :, :])

        else:
            self.model = None

    def evaluate(self, node):

        state = node.game.getState()

        return self.evaluate_state(state)

    def evaluate_state(self, state):

        v, var, p = self.inference(state)

        return v[0][0], var[0][0], p[0]

    def expand_nodes(self, n_nodes=10000):

        sys.stderr.write('\nWATNING: ADDING EXTRA NODES...\n')

        for k, arr in self.arrs.items():
            _s = arr.shape
            _new_s = [_ for _ in _s]
            _new_s[0] = n_nodes
            _temp_arr = np.zeros(_new_s, dtype=arr.dtype)
            self.arrs[k] = np.concatenate([arr, _temp_arr])

        self.game_arr += [self.env(*self.env_args) for i in range(n_nodes)]
        self.available += [
            i for i in range(self.max_nodes, self.max_nodes + n_nodes)
        ]
        self.max_nodes += n_nodes

    def new_node(self, game):

        idx = self.node_index_dict.get(game)

        if not idx:

            if self.available:
                idx = self.available.pop()
            else:
                self.remove_nodes()
                if self.available:
                    idx = self.available.pop()
                else:
                    self.expand_nodes()
                    idx = self.available.pop()

            _g = self.game_arr[idx]

            _g.copy_from(game)

            self.arrs['node_ep'][idx] = self.episode

            self.node_index_dict[_g] = idx

            self.occupied.append(idx)

        return idx

    def mcts(self, root_index):
        pass

    def play(self):

        for i in range(self.sims):
            self.mcts(self.root)

        self.stats = self.compute_stats()

        if np.all(self.stats[3] == 0):
            action = np.random.choice(self.n_actions)
        else:
            action = np.argmax(self.stats[3])

        return action

    def compute_stats(self):
        _stats = np.zeros((6, self.n_actions))

        _childs = self.arrs['child'][self.root]
        _ns = self.arrs['node_stats']

        for i in range(self.n_actions):
            _idx = _childs[i]
            _stats[0][i] = _ns[_idx][0]
            _stats[1][i] = _ns[_idx][1]
            _stats[2][i] = 0
            _stats[3][i] = _ns[_idx][1] / _ns[_idx][0]
            _stats[4][i] = _ns[_idx][3]
            _stats[5][i] = _ns[_idx][4]

        return _stats

    def get_prob(self):

        return self.stats[0] / np.sum(self.stats[0])

    def get_stats(self):

        return np.copy(self.stats)

    def get_value(self):

        sys.stderr.write(
            '\nWATNING: get_value not implemented for this agent\n')

        return 0, 0

    def remove_nodes(self):

        sys.stderr.write('\nWARNING: REMOVING UNUSED NODES...\n')

        _c = get_all_childs(self.root, self.arrs['child'])
        self.occupied.clear()
        self.occupied.extend(_c)
        self.available.clear()
        a_app = self.available.append
        for i in range(self.max_nodes):
            if i not in _c:
                a_app(i)
        sys.stderr.write('Number of occupied nodes: ' +
                         str(len(self.occupied)) + '\n')
        sys.stderr.write('Number of available nodes: ' +
                         str(len(self.available)) + '\n')
        sys.stderr.flush()

        if self.saver:
            self.save_nodes(self.available)

        for idx in self.available:
            _g = self.game_arr[idx]

            self.node_index_dict.pop(_g, None)

            self.arrs['child'][idx].fill(0)
            self.arrs['child_stats'][idx].fill(0)
            self.arrs['node_stats'][idx].fill(0)

    def save_nodes(self, nodes_to_save):

        saver = self.saver

        node_stats = self.arrs['node_stats']

        node_ep = self.arrs['node_ep']

        for idx in nodes_to_save:

            if node_stats[idx][0] < self.min_visits:
                continue

            _tmp_stats = self.compute_stats(idx)
            if _tmp_stats is False:
                continue

            _g = self.game_arr[idx]

            v, var = self.get_value(idx)

            saver.add_raw(node_ep[idx], _g.getState(),
                          _tmp_stats[0] / _tmp_stats[0].sum(),
                          np.argmax(_tmp_stats[1]), _g.getCombo(),
                          _g.getLines(), _g.getScore(), _tmp_stats, v, var)

    def save_occupied(self):

        if self.saver:
            self.save_nodes(self.occupied)

    def set_root(self, game):

        self.root = self.new_node(game)

    def update_root(self, game, episode=0):

        self.episode = episode

        self.set_root(game)

        self.arrs['node_stats'][self.root][2] = game.getScore()

    def close(self):

        if self.saver:
            self.save_occupied()
            self.saver.close()
示例#15
0
def main():
    trainset, validset, testset = [], [], []
    if args.inference:  # 测试时只载入测试集
        with open(args.testset_path, 'r', encoding='utf8') as fr:
            for line in fr:
                testset.append(json.loads(line))
        print(f'载入测试集{len(testset)}条')
    else:  # 训练时载入训练集和验证集
        with open(args.trainset_path, 'r', encoding='utf8') as fr:
            for line in fr:
                trainset.append(json.loads(line))
        print(f'载入训练集{len(trainset)}条')
        with open(args.validset_path, 'r', encoding='utf8') as fr:
            for line in fr:
                validset.append(json.loads(line))
        print(f'载入验证集{len(validset)}条')

    vocab, embeds = [], []
    with open(args.embed_path, 'r', encoding='utf8') as fr:
        for line in fr:
            line = line.strip()
            word = line[:line.find(' ')]
            vec = line[line.find(' ') + 1:].split()
            embed = [float(v) for v in vec]
            assert len(embed) == config.embedding_size  # 检测词向量维度
            vocab.append(word)
            embeds.append(embed)
    print(f'载入词汇表: {len(vocab)}个')
    print(f'词向量维度: {config.embedding_size}')

    vads = []
    with open(args.vad_path, 'r', encoding='utf8') as fr:
        for line in fr:
            line = line.strip()
            vad = line[line.find(' ') + 1:].split()
            vad = [float(item) for item in vad]
            assert len(vad) == config.affect_embedding_size
            vads.append(vad)
    print(f'载入vad字典: {len(vads)}个')
    print(f'vad维度: {config.affect_embedding_size}')

    sentence_processor = SentenceProcessor(vocab, vads, config.pad_id,
                                           config.start_id, config.end_id,
                                           config.unk_id)

    model = Model(config)
    model.print_parameters()  # 输出模型参数个数
    epoch = 0  # 训练集迭代次数
    global_step = 0  # 参数更新次数

    # 载入模型
    if os.path.isfile(args.model_path):  # 如果载入模型的位置存在则载入模型
        epoch, global_step = model.load_model(args.model_path)
        model.affect_embedding.embedding.weight.requires_grad = False
        print('载入模型完成')
        log_dir = os.path.split(args.model_path)[0]
    elif args.inference:  # 如果载入模型的位置不存在,但是又要测试,这是没有意义的
        print('请测试一个训练过的模型!')
        return
    else:  # 如果载入模型的位置不存在,重新开始训练,则载入预训练的词向量
        model.embedding.embedding.weight = torch.nn.Parameter(
            torch.tensor(embeds).float())
        model.affect_embedding.embedding.weight = torch.nn.Parameter(
            torch.tensor(vads).float())
        model.affect_embedding.embedding.weight.requires_grad = False
        print('初始化模型完成')
        log_dir = os.path.join(args.log_path, 'run' + str(int(time.time())))
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)

    if args.gpu:
        model.to('cuda')  # 将模型参数转到gpu

    # 定义优化器参数
    optim = Optim(config.method, config.lr, config.lr_decay,
                  config.weight_decay, config.eps, config.max_grad_norm)
    optim.set_parameters(model.parameters())  # 给优化器设置参数
    optim.update_lr(epoch)  # 每个epoch更新学习率

    # 训练
    if not args.inference:
        summary_writer = SummaryWriter(os.path.join(
            log_dir, 'summary'))  # 创建tensorboard记录的文件夹
        dp_train = DataProcessor(trainset, config.batch_size,
                                 sentence_processor)  # 数据的迭代器
        dp_valid = DataProcessor(validset,
                                 config.batch_size,
                                 sentence_processor,
                                 shuffle=False)

        while epoch < args.max_epoch:  # 最大训练轮数
            model.train()  # 切换到训练模式
            for data in dp_train.get_batch_data():
                start_time = time.time()
                feed_data = prepare_feed_data(data)
                loss, nll_loss, affect_loss, kld_loss, kld_weight, ppl = train(
                    model, feed_data, global_step)
                loss.mean().backward()  # 反向传播
                optim.step()  # 更新参数
                optim.optimizer.zero_grad()  # 清空梯度
                use_time = time.time() - start_time

                global_step += 1  # 参数更新次数+1
                if global_step % args.print_per_step == 0:
                    print(
                        'epoch: {:d}, global_step: {:d}, lr: {:g}, nll_loss: {:.2f}, affect_loss: {:.2f},'
                        ' kld_loss: {:.2f}, kld_weight: {:g}, ppl: {:.2f}, time: {:.2f}s/step'
                        .format(epoch, global_step, optim.lr,
                                nll_loss.mean().item(),
                                affect_loss.mean().item(),
                                kld_loss.mean().item(), kld_weight,
                                ppl.mean().exp().item(), use_time))
                    summary_writer.add_scalar('train_nll',
                                              nll_loss.mean().item(),
                                              global_step)
                    summary_writer.add_scalar('train_affect',
                                              affect_loss.mean().item(),
                                              global_step)
                    summary_writer.add_scalar('train_kld',
                                              kld_loss.mean().item(),
                                              global_step)
                    summary_writer.add_scalar('train_weight', kld_weight,
                                              global_step)
                    summary_writer.add_scalar('train_ppl',
                                              ppl.mean().exp().item(),
                                              global_step)
                    summary_writer.flush()  # 将缓冲区写入文件

                if global_step % args.log_per_step == 0 or \
                        (global_step % (2*config.kl_step) - config.kl_step) == config.kl_step // 2:
                    log_file = os.path.join(
                        log_dir,
                        '{:03d}{:012d}.model'.format(epoch, global_step))
                    model.save_model(epoch, global_step, log_file)
                    model.eval()
                    nll_loss, affect_loss, kld_loss, ppl = valid(
                        model, dp_valid, global_step - 1)
                    model.train()
                    print(
                        '在验证集上的NLL损失为: {:g}, affect损失为: {:g}, KL损失为: {:g}, PPL为: {:g}'
                        .format(nll_loss, affect_loss, kld_loss, np.exp(ppl)))
                    summary_writer.add_scalar('valid_nll', nll_loss,
                                              global_step)
                    summary_writer.add_scalar('valid_affect', affect_loss,
                                              global_step)
                    summary_writer.add_scalar('valid_kld', kld_loss,
                                              global_step)
                    summary_writer.add_scalar('valid_ppl', np.exp(ppl),
                                              global_step)
                    summary_writer.flush()  # 将缓冲区写入文件

            epoch += 1  # 数据集迭代次数+1
            optim.update_lr(epoch)  # 调整学习率

            log_file = os.path.join(
                log_dir, '{:03d}{:012d}.model'.format(epoch, global_step))
            model.save_model(epoch, global_step, log_file)
            model.eval()
            nll_loss, affect_loss, kld_loss, ppl = valid(
                model, dp_valid, global_step - 1)
            print(
                '在验证集上的NLL损失为: {:g}, affect损失为: {:g}, KL损失为: {:g}, PPL为: {:g}'.
                format(nll_loss, affect_loss, kld_loss, np.exp(ppl)))
            summary_writer.add_scalar('valid_nll', nll_loss, global_step)
            summary_writer.add_scalar('valid_affect', affect_loss, global_step)
            summary_writer.add_scalar('valid_kld', kld_loss, global_step)
            summary_writer.add_scalar('valid_ppl', np.exp(ppl), global_step)
            summary_writer.flush()  # 将缓冲区写入文件

        summary_writer.close()
    else:  # 测试
        if not os.path.exists(args.result_path):  # 创建结果文件夹
            os.makedirs(args.result_path)

        dp_test = DataProcessor(testset,
                                config.batch_size,
                                sentence_processor,
                                shuffle=False)

        model.eval()  # 切换到测试模式,会停用dropout等等
        for t in tqdm(range(args.sample_times)):
            nll_loss, affect_loss, kld_loss, ppl = valid(
                model, dp_test, global_step - 1)
            print(
                '在测试集上的NLL损失为: {:g}, affect损失为: {:g}, KL损失为: {:g}, PPL为: {:g}'.
                format(nll_loss, affect_loss, kld_loss, np.exp(ppl)))
            fw = open(os.path.join(args.result_path, f'sample_{t}.txt'),
                      'w',
                      encoding='utf8')
            len_results = []
            for data in dp_test.get_batch_data():
                posts = data['str_posts']
                responses = data['str_responses']
                feed_data = prepare_feed_data(data, inference=True)
                results = test(model, feed_data)

                for idx, result in enumerate(results):
                    new_data = dict()
                    new_data['post'] = posts[idx]
                    new_data['response'] = responses[idx]
                    new_data['result'] = sentence_processor.index2word(
                        result)  # 将输出的句子转回单词的形式
                    len_results.append(len(new_data['result']))
                    fw.write(json.dumps(new_data, ensure_ascii=False) + '\n')

            fw.close()
            print(f'生成句子平均长度: {1.0 * sum(len_results) / len(len_results)}')
示例#16
0
 def _initModel(self, **kwargs):
     model = Model()
     model.loadScatterers(self.filename2)
     return model
示例#17
0
class Controller:
    def __init__(self):
        self.model = Model()
        self.view = View()
    
    def start(self):
        self.view.start()
        self.login_user()

    "Login controllers"

    def login_user(self):
        self.view.msg('Introduce tu usuario')
        username = input()
        self.view.msg('Introduce tu contraseña')
        password = input()
        user = self.model.auth_user(username, password)
        if type(user) == tuple:
            self.user_id = user[0]
            self.is_admin = user[3]
            self.main_menu(user[3])
        else:
            if user == None:
                self.view.error('El usuario no existe o la contraseña es incorrecta')
            else:
                self.view.error('Error interno')
        return

    "Menus"
    def main_menu(self, isAdmin):
        if isAdmin:
            o = '0'
            while o != '5':
                self.view.main_menu(isAdmin)
                o = input()
                if o == '1':
                    self.movies_menu()
                elif o == '2':
                    self.halls_menu()
                elif o == '3':
                    self.schedules_menu()
                elif o == '4':
                    self.admins_menu()
                elif o == '5':
                    return self.view.end()
                else:
                    self.view.not_valid_option()
            return
        else:
            o = '0'
            while o != '4':
                self.view.main_menu(isAdmin)
                o = input()
                if o == '1':
                    self.show_schedules()
                elif o == '2':
                    self.buy_ticket_menu()
                elif o == '3':
                    self.show_user_tickets(self.user_id)
                elif o == '4':
                    return self.view.end()
                else:
                    self.view.not_valid_option()
            return

    "** Admin methods"
    "Granted users"
    def admins_menu(self):
        o = '0'
        while o == '0':
            self.view.show_admin_methods()
            o = input()
            if o == '1':
                self.show_admins()
            if o == '2':
                self.add_admin()
            elif o == '3':
                self.delete_admin()
            elif o == '4':
                self.main_menu(1)
        return
    def delete_admin(self):
        admins = self.model.get_admins_list()
        self.view.show_indexed_admins(admins)
        self.view.msg('Selecciona un numero de administrador')
        number_selected = input()
        admin_selected = admins[int(number_selected)-1][0]

        result = self.model.delete_admin(admin_selected)
        self.view.success('eliminar administrador') if result else self.view.error('eliminar administrador')

    def show_admins(self):
        admins = self.model.get_admins_list()
        self.view.show_admins(admins)

    def add_admin(self):
        self.view.msg('Introduce el nombre de usuario del administrador')
        new_user = input()
        self.view.msg('Introduce la contraseña del administrador nuevo')
        new_password = input()

        result = self.model.add_admin(new_user, new_password)
        self.view.success('agregar administrador') if result else self.view.error('agregar administrador')
        self.admins_menu()
        
    "Halls"
    def halls_menu(self):
        o = '0'
        while o == '0':
            self.view.show_halls_methods()
            o = input()
            if o == '1':
                self.show_halls()
            if o == '2':
                self.add_hall()
            elif o == '3':
                self.edit_hall()
            elif o == '4':
                self.delete_hall()
            elif o == '5':
                self.main_menu(1)
        return

    def show_halls(self):
        halls = self.model.get_halls_list()
        self.view.show_halls(halls)
        self.halls_menu()

    def add_hall(self):
        self.view.msg('Introduce el nombre de la sala')
        new_name = input()
        self.view.msg('Introduce el numero de columnas de asientos')
        new_x = input()
        self.view.msg('Introduce el numero de filas de asientos')
        new_y = input()

        result = self.model.insert_hall(new_name, new_x, new_y)
        self.view.success('agregar sala') if result else self.view.error('agregar sala')

    def edit_hall(self):
        halls = self.model.get_halls_list()
        self.view.show_halls(halls)
        self.view.msg('Selecciona un numero de sala a editar')
        number_selected = input()
        hall_selected = halls[int(number_selected)-1][0]
        seats_x = halls[int(number_selected)-1][1]
        seats_y = halls[int(number_selected)-1][2]

        self.view.msg('Introduce el nuevo nombre de la sala: (deja en blanco para dejar igual)')
        input_text = input()
        new_name = input_text if input_text != '' else hall_selected
        self.view.msg('Introduce el nuevo numero de columnas: (deja en blanco para dejar igual)')
        input_text = input()
        new_seats_x = input_text if input_text != '' else seats_x
        self.view.msg('Introduce el nuevo numero de filas: (deja en blanco para dejar igual)')
        input_text = input()
        new_seats_y = input_text if input_text != '' else seats_y

        result = self.model.update_hall(hall_selected, new_name, new_seats_x, new_seats_y)
        self.view.success('modificar sala') if result else self.view.error('modificar sala')

    def delete_hall(self):
        halls = self.model.get_halls_list()
        self.view.show_halls(halls)
        self.view.msg('Selecciona un numero de sala a eliminar')
        number_selected = input()
        hall_selected = halls[int(number_selected)-1][0]

        result = self.model.delete_hall(hall_selected)
        self.view.success('eliminar sala') if result else self.view.error('eliminar sala')

    "Schedules"
    def schedules_menu(self):
        o = '0'
        while o == '0':
            self.view.show_schedules_methods()
            o = input()
            if o == '1':
                self.show_schedules()
            if o == '2':
                self.add_schedule()
            elif o == '3':
                self.edit_schedule()
            elif o == '4':
                self.delete_schedule()
            elif o == '5':
                self.main_menu(1)
        return
    def delete_schedule(self):
        movie_schedules = self.model.get_detailed_schedules_list()
        self.view.show_detailed_movie_schedules(movie_schedules)
        self.view.msg('Selecciona el numero de horario a eliminar')
        number_selected = input()
        movie_schedule_id = movie_schedules[int(number_selected)-1][0]
        result = self.model.delete_schedule(movie_schedule_id)
        self.view.success('eliminar horario') if result else self.view.error('eliminar horario')
        self.schedules_menu()
    def add_schedule(self):
        movies = self.model.get_movies_list()
        self.view.show_movies(movies)
        self.view.msg('Introduce el numero de la pelicula a asignar horario')
        number_selected = input()
        movie_selected = movies[int(number_selected)-1][0]
        halls = self.model.get_halls_list()
        self.view.show_halls(halls)
        self.view.msg('Selecciona un numero de sala a asignar horario')
        number_selected = input()
        hall_selected = halls[int(number_selected)-1][0]
        self.view.msg('Introduce un horario a asignar con el formato hh:mm pm/am (ejemplo: 08:10 pm)')
        date = input()
        result = self.model.insert_schedule(movie_selected, hall_selected, date)
        self.view.success('agregar horario') if result else self.view.error('agregar horario')
        self.schedules_menu()
    def edit_schedule(self):
        movie_schedules = self.model.get_detailed_schedules_list()
        self.view.show_detailed_movie_schedules(movie_schedules)
        self.view.msg('Selecciona el numero de horario a editar')
        number_selected = input()
        movie_schedule_id = movie_schedules[int(number_selected)-1][0]
        movie_selected = movie_schedules[int(number_selected)-1][1]
        hall_selected = movie_schedules[int(number_selected)-1][2]
        schedule_selected = movie_schedules[int(number_selected)-1][3]

        movies = self.model.get_movies_list()
        self.view.show_movies(movies)
        self.view.msg('Selecciona un numero de pelicula en caso de querer cambiarla: (deja en blanco para no hacer cambios)')
        input_text = input()
        new_movie = movies[int(input_text)-1][0] if input_text != '' else movie_selected

        halls = self.model.get_halls_list()
        self.view.show_halls(halls)
        self.view.msg('Selecciona un numero de sala nuevo: (deja en blanco para no hacer cambios)')
        input_text = input()
        new_hall = halls[int(input_text)-1][0] if input_text != '' else hall_selected

        self.view.msg('Introduce el horario nuevo: (deja en blanco para no hacer cambios)')
        input_text = input()
        new_schedule = input_text if input_text != '' else schedule_selected

        result = self.model.update_schedule(movie_schedule_id, new_hall, new_movie, new_schedule)
        self.view.success('modificar horario') if result else self.view.error('modificar horario')

    "Movies"
    def movies_menu(self):
        o = '0'
        while o == '0':
            self.view.show_movies_methods()
            o = input()
            if o == '1':
                self.show_movies()
            if o == '2':
                self.add_movie()
            elif o == '3':
                self.edit_movie()
            elif o == '4':
                self.delete_movie()
            elif o == '5':
                self.main_menu(1)
        return

    def show_movies(self):
        movies = self.model.get_movies_list()
        self.view.show_movies(movies)
        self.movies_menu()

    def delete_movie(self):
        movies = self.model.get_movies_list()
        self.view.show_movies(movies)
        self.view.msg('Selecciona un numero de pelicula a eliminar')
        number_selected = input()
        movie_selected = movies[int(number_selected)-1][0]

        result = self.model.delete_movie(movie_selected)
        self.view.success('eliminar película') if result else self.view.error('eliminar película')

    def add_movie(self):
        self.view.msg('Introduce el nombre de la pelicula')
        new_name = input()
        self.view.msg('Introduce la clasificacion de la pelicula')
        new_classification = input()

        result = self.model.insert_movie(new_name, new_classification)
        self.view.success('agregar película') if result else self.view.error('agregar película')

    def edit_movie(self):
        movies = self.model.get_movies_list()
        self.view.show_movies(movies)
        self.view.msg('Selecciona un numero de pelicula a editar')
        number_selected = input()
        movie_selected = movies[int(number_selected)-1][0]
        movie_classification = movies[int(number_selected)-1][1]

        self.view.msg('Introduce el nuevo nombre de la pelicula: (deja en blanco para dejar igual)')
        input_text = input()
        new_name = input_text if input_text != '' else movie_selected
        self.view.msg('Introduce la nueva clasificacion de la pelicula: (deja en blanco para dejar igual)')
        input_text = input()
        new_classification = input_text if input_text != '' else movie_classification
        result = self.model.update_movie(movie_selected, new_name, new_classification)
        self.view.success('modificar película') if result else self.view.error('modificar película')

    "User methods"
    def show_schedules(self):
        schedules = self.model.get_schedules_list()
        if type(schedules) == list:
            self.view.show_schedules(schedules)
        else:
            self.view.error('Error interno')
        return
    
    def buy_ticket_menu(self):
        movies = self.model.get_schedules()
        self.view.show_movies(movies)
        self.view.msg('Introduce el numero de la pelicula para la que deseas comprar el boleto:')
        number_selected = input()
        movie_selected = movies[int(number_selected)-1][0]

        self.view.msg('Introduce el numero del horario en la que quieres reservar:')
        movie_schedules = movies[int(number_selected)-1][2]
        self.view.show_movie_schedules(movie_schedules)
        number_selected = input()
        schedule_selected = movie_schedules.split(',')[int(number_selected)-1]

        self.view.msg('Introduce el numero de la fecha en la que quieres reservar:')
        next_days = self.model.get_next_days()
        self.view.show_next_days(next_days)
        number_selected = input()
        date_selected = next_days[int(number_selected)-1]

        self.view.msg('Introduce el asiento que quieres reservar, ejemplo: B6')
        schedule_exists = self.model.schedule_exists(date_selected, schedule_selected)
        occupied_seats = ''
        if schedule_exists:
            data = self.model.get_occupied_seats(movie_selected, date_selected, schedule_selected)
            occupied_seats = data[1].split(',')
        else:
            occupied_seats = ['ZZZ',]
        seats = []
        hall_capacity = self.model.get_hall_capacity(movie_selected,schedule_selected.strip())
        for x in range(hall_capacity[0]):
            for y in range(hall_capacity[1]):
                seats.append(f'{string.ascii_lowercase[x].upper()}{y+1}')
        available_seats = [b for b in seats if
            all(a not in b for a in occupied_seats)]
        self.view.msg(', '.join(available_seats))
        seat_selected = '0'
        while seat_selected.upper() not in available_seats:
            seat_selected = input().upper()
            if seat_selected == '0':
                seat_selected = input().upper()
            elif seat_selected.upper() not in available_seats:
                self.view.error('El asiento no está disponible, escoge otro:')
                self.view.msg(', '.join(available_seats))

        if not schedule_exists:
            movie_schedule_id = hall_capacity[2]
            self.model.create_function_schedule(movie_schedule_id, date_selected)

        function_schedule_id = self.model.get_function_schedule_id(movie_selected, date_selected, schedule_selected.strip())
        self.model.create_ticket(function_schedule_id, self.user_id, seat_selected)
        self.view.show_order_details(movie_selected, date_selected, schedule_selected, seat_selected)
        self.view.msg('¡Compraste el boleto de manera exitosa!, presiona cualquier tecla para continuar.')
        tmp = input()
        self.main_menu(self.is_admin)

    def show_user_tickets(self, user_id):
        user_tickets = self.model.get_user_tickets(user_id)
        self.view.msg('A continuación se muestran tus boletos reservados:')
        self.view.show_user_tickets(user_tickets)
示例#18
0
with open(args.labelJson, 'r') as f:
    label = ujson.load(f)

## ImageNet Pre-processing
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224,
                                                          0.225]),
])

## Model Initialize
strideNet = 16
minNet = 15
featChannel = 256
net = Model(args.finetunePath, args.architecture)
if args.cuda:
    net.cuda()
optimizer = torch.optim.Adam(net.parameters(), lr=args.lr, betas=(0.5, 0.999))

## Scales
scales = outils.ScaleList(args.featScaleBase, args.nbOctave,
                          args.scalePerOctave)
msg = 'We search to match in {:d} scales, the max dimensions in the feature maps are:'.format(
    len(scales))
print msg
print scales
print '\n\n'

## Output
if not os.path.exists(args.outDir):
示例#19
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        # Set up the user interface from Designer.
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.loadDataDialog = QFileDialog()
        self.loadDataDialog.setFileMode(QFileDialog.DirectoryOnly)
        self.loadDataDialog.setOption(QFileDialog.ShowDirsOnly, True)
        self.loadDataDialog.setAcceptMode(QFileDialog.AcceptOpen)
        self.loadDataDialog.fileSelected.connect(self.directorySelected)

        self.ui.loadDataButton.clicked.connect(self.loadDataDialog.show)
        self.ui.calculateButton.clicked.connect(self.calculateClicked)
        self.ui.actionAbout.triggered.connect(self.actionAboutTriggered)

    @pyqtSlot(str)
    def directorySelected(self, dataDirectory):
        print("Selected data directory: {0}".format(dataDirectory))
        self.loadData(dataDirectory)

    def loadData(self, dataDirectory):
        print("Loading model with data from: {0}".format(dataDirectory))
        self.ui.loadDataButton.setEnabled(False)
        self.ui.statusLabel.setText("Loading model, please wait...")

        try:
            self.model = Model(dataDirectory)
        except Exception as ex:
            print("Model load error: {0}".format(ex))
            self.ui.statusLabel.setText(
                "Error occured during loading the model. Please, try again.")
            self.ui.statusLabel.setStyleSheet("color: red")
            self.ui.loadDataButton.setEnabled(True)
            return

        self.triggerModelLoaded()

        print("Model loaded successfully")

    def triggerModelLoaded(self):
        self.ui.statusLabel.setStyleSheet("color: orange")
        self.ui.statusLabel.setText(
            "Model loaded sucessfully. Now you can start calculations.")
        self.ui.loadDataButton.setEnabled(True)
        self.ui.calculateButton.setEnabled(True)

    @pyqtSlot()
    def calculateClicked(self):
        print("Running model")

        if self.ui.useSweepRadioButton.isChecked():
            algorithmType = Model.AlgorithmType.Sweep
        elif self.ui.useClarkeWrightRadioButton.isChecked():
            algorithmType = Model.AlgorithmType.ClarkeWright
        else:
            assert False, "Either Sweep or ClarkeWright should be checked"

        self.ui.loadDataButton.setEnabled(False)
        self.ui.calculateButton.setEnabled(False)
        self.ui.useSweepRadioButton.setEnabled(False)
        self.ui.useClarkeWrightRadioButton.setEnabled(False)
        self.ui.statusLabel.setText("Running model, please wait...")

        try:
            carsUsage, _ = self.model.run(algorithmType)
        except Exception as ex:
            print("Model run error: {0}".format(ex))
            self.ui.statusLabel.setText(
                "Error occured during running the model. Please, try again.")
            self.ui.statusLabel.setStyleSheet("color: red")
            self.ui.loadDataButton.setEnabled(True)
            self.ui.useSweepRadioButton.setEnabled(True)
            self.ui.useClarkeWrightRadioButton.setEnabled(True)
            raise

        self.ui.statusLabel.setText("Model calculated successfully!")
        self.ui.statusLabel.setStyleSheet("color: green")

        self.openResultsDialog(carsUsage)

    def openResultsDialog(self, modelResults):
        print("Opening results dialog")

        self.ui.inputDataDialog = InputDataDialog(self.model.data, self)

        self.ui.resultsDialog = ResultsDialog(self.model.data, modelResults,
                                              self)
        self.ui.resultsDialog.finished.connect(self.resultsDialogFinished)

        self.ui.inputDataDialog.show()
        self.ui.resultsDialog.show()

        print("Results dialog opened")

    @pyqtSlot()
    def resultsDialogFinished(self):
        self.triggerModelLoaded()
        self.ui.useSweepRadioButton.setEnabled(True)
        self.ui.useClarkeWrightRadioButton.setEnabled(True)

    @pyqtSlot()
    def actionAboutTriggered(self):
        self.aboutDialog = AboutDialog(self)
        self.aboutDialog.show()
示例#20
0
class Controller:
    """
    ********************************
    * A controller for a cinema DB *
    ********************************
    """
    def __init__(self):
        self.model = Model()
        self.view = View()

    def start(self):
        self.view.start()
        self.menu_users()

    """
    ***********************
    * General Controllers *
    ***********************
    """

    def menu_users(self):
        o = '0'
        while o != '3':
            self.view.menu_users()
            self.view.option('3')
            o = input()
            if o == '1':
                self.menu_for_user()
            elif o == '2':
                self.main_menu_admin()
            elif o == '3':
                self.view.end()
            else:
                self.view.not_valid_option()
        return

    def update_list(self, fs, vs):
        fields = []
        vals = []
        for f, v in zip(fs, vs):
            if v != '':
                fields.append(f + ' = %s')
                vals.append(v)
        return fields, vals

    """
    ********************************
    * Controllers for General Users*
    ********************************
    """

    def menu_for_user(self):
        o = '0'
        while o != '3':
            self.view.menu_for_user()
            self.view.option('3')
            o = input()
            if o == '1':
                self.read_all_schedules()
            elif o == '2':
                self.create_ticket_user()
            elif o == '3':
                return
            else:
                self.view.not_valid_option()
        return

    def read_all_schedules(self):
        schedules = self.model.read_all_schedules()
        if type(schedules) == list:
            self.view.show_schedule_header('Todas las funciones')
            for schedule in schedules:
                self.view.show_schedule(schedule)
                self.view.show_schedule_midder()
            self.view.show_schedules_footer()
        else:
            self.view.error('PROBLEMAS AL LEER LA CARTELERA. REGRESA LUEGO')
        return

    def ask_ticket_user(self):
        self.view.ask('ID Pelicula: ')
        id_movie = input()
        self.view.ask('Sala: ')
        id_hall = input()
        self.view.ask('Usuario: ')
        id_user = input()
        today = date.today()
        loanDate = today.strftime('%d-%m-%y')
        self.view.ask('Asiento: ')
        id_seat = input()
        self.view.ask('Tipo boleto: ')
        name = input()
        return [id_movie, id_hall, id_user, loanDate, id_seat, name]

    def create_ticket_user(self):
        id_movie, id_hall, id_user, loanDate, id_seat, name = self.ask_ticket_user(
        )
        out = self.model.create_ticket_user(id_movie, id_hall, id_user,
                                            loanDate, id_seat, name)
        if out == True:
            self.view.ok(id_user, 'compro')
        else:
            self.view.error('NO SE PUDO REALIZAR LA COMPRA. REVISA')
        return

    """
    *********************************
    * Controllers for Administrator *
    *********************************
    """

    def main_menu_admin(self):
        o = '0'
        while o != '9':
            self.view.main_menu_admin()
            self.view.option('9')
            o = input()
            if o == '1':
                self.users_menu()
            elif o == '2':
                self.movies_menu()
            elif o == '3':
                self.halls_menu()
            elif o == '4':
                self.seats_menu()
            elif o == '5':
                self.schedules_menu()
            elif o == '6':
                self.type_tickets_menu()
            elif o == '7':
                self.tickets_menu()
            elif o == '8':
                self.admins_menu()
            elif o == '9':
                return
            else:
                self.view.not_valid_option()
        return

    """
    ********************************
    * Controllers for admin. users *
    ********************************
    """

    def users_menu(self):
        o = '0'
        while o != '7':
            self.view.users_menu()
            self.view.option('7')
            o = input()
            if o == '1':
                self.create_user()
            elif o == '2':
                self.read_user()
            elif o == '3':
                self.read_all_users()
            elif o == '4':
                self.read_user_name()
            elif o == '5':
                self.update_user()
            elif o == '6':
                self.delete_user()
            elif o == '7':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_user(self):
        self.view.ask('Nombre: ')
        name = input()
        self.view.ask('Apellido paterno: ')
        sname1 = input()
        self.view.ask('Apellido materno: ')
        sname2 = input()
        self.view.ask('Telefono: ')
        phone = input()
        self.view.ask('Email: ')
        email = input()
        self.view.ask('Tarjeta de Credito: ')
        credit_card = input()
        return [name, sname1, sname2, phone, email, credit_card]

    def create_user(self):
        name, sname1, sname2, phone, email, credit_card = self.ask_user()
        out = self.model.create_user(name, sname1, sname2, phone, email,
                                     credit_card)
        if out == True:
            self.view.ok(name + ' ' + sname1 + ' ' + sname2, 'agrego')
        else:
            self.view.error('PROBLEMAS AGREGAR EL USUARIO. REVISA')
        return

    def read_user(self):
        self.view.ask('ID usuario: ')
        id_user = input()
        user = self.model.read_user(id_user)
        if type(user) == tuple:
            self.view.show_user_header('Datos del usuario ' + id_user + ' ')
            self.view.show_user(user)
            self.view.show_user_midder()
            self.view.show_user_footer()
        else:
            if user == None:
                self.view.error('EL USUARIO NO EXISTE')
            else:
                self.view.error('PROBLEMAS AL MOSTRAR EL USUARIO. REVISA.')
        return

    def read_all_users(self):
        users = self.model.read_all_users()
        if type(users) == list:
            self.view.show_user_header('Todos los usuarios')
            for user in users:
                self.view.show_user(user)
                self.view.show_user_midder()
            self.view.show_user_footer()
        else:
            self.view.error('PROBLEMAS AL MOSTRAR TODOS LOS USUARIOS. REVISA.')

    def read_user_name(self):
        self.view.ask('Nombre: ')
        name = input()
        names = self.model.read_user_name(name)
        if type(names) == list:
            self.view.show_user_header('Usuarios con nombre ' + name + ' ')
            for name in names:
                self.view.show_user(name)
                self.view.show_user_midder()
            self.view.show_user_footer()
        else:
            self.view.error('PROBLEMAS AL MOSTAR LOS USUARIOS. REVISA')
        return

    def update_user(self):
        self.view.ask('ID de usuario a modificar: ')
        id_user = input()
        user = self.model.read_user(id_user)
        if type(user) == tuple:
            self.view.show_user_header('Datos del usuario ' + id_user + ' ')
            self.view.show_user(user)
            self.view.show_user_midder()
            self.view.show_user_footer()
        else:
            if user == None:
                self.view.error('EL USUARIO NO EXISTE')
            else:
                self.view.error('PROBLEMAS AL MOSTRAR EL USUARIO. REVISA.')
            return
        self.view.msg(
            'Ingresa los valores a modificar (vacio para dejarlo igual):')
        whole_vals = self.ask_user()
        fields, vals = self.update_list([
            'u_name', 'u_sname1', 'u_sname2', 'u_phone', 'u_email',
            'u_credit_card'
        ], whole_vals)
        vals.append(id_user)
        vals = tuple(vals)
        out = self.model.update_user(fields, vals)
        if out == True:
            self.view.ok(id_user, 'actualizo')
        else:
            self.view.error('PROBLEMAS ACTUALIZAR EL USUARIO. REVISA.')
        return

    def delete_user(self):
        self.view.ask('ID de usuario a eliminar: ')
        id_user = input()
        count = self.model.delete_user(id_user)
        if count != 0:
            self.view.ok(id_user, 'elimino')
        else:
            if count == 0:
                self.view.error('EL USUARIO NO EXISTE.')
            else:
                self.view.error('PROBLEMAS AL ELIMINAR EL USUARIO. REVISA.')
        return

    """
    *********************************
    * Controllers for admin. movies *
    *********************************
    """

    def movies_menu(self):
        o = '0'
        while o != '7':
            self.view.movies_menu()
            self.view.option('7')
            o = input()
            if o == '1':
                self.create_movie()
            elif o == '2':
                self.read_movie()
            elif o == '3':
                self.read_all_movies()
            elif o == '4':
                self.read_movie_name()
            elif o == '5':
                self.update_movie()
            elif o == '6':
                self.delete_movie()
            elif o == '7':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_movie(self):
        self.view.ask('Nombre: ')
        name = input()
        self.view.ask('Genero: ')
        genre = input()
        self.view.ask('Descripcion: ')
        description = input()
        self.view.ask('Duracion: ')
        duration = input()
        self.view.ask('Clasificacion: ')
        clasification = input()
        return [name, genre, description, duration, clasification]

    def create_movie(self):
        name, genre, description, duration, clasification = self.ask_movie()
        out = self.model.create_movie(name, genre, description, duration,
                                      clasification)
        if out == True:
            self.view.ok(name, 'agrego')
        else:
            self.view.error('PROBLEMAS AL AGREGAR LA PELICULA. REVISA.')
        return

    def read_movie(self):
        self.view.ask('ID pelicula: ')
        id_movie = input()
        movie = self.model.read_movie(id_movie)
        if type(movie) == tuple:
            self.view.show_movie_header('Datos de la pelicula' + id_movie +
                                        ' ')
            self.view.show_movies(movie)
            self.view.show_movie_midder()
            self.view.show_movie_footer()
        else:
            if movie == None:
                self.view.error('LA PELICULA NO EXISTE')
            else:
                self.view.error('PROBLEMAS AL MOSTRAR LA PELICULA. REVISA.')
        return

    def read_all_movies(self):
        movies = self.model.read_all_movies()
        if type(movies) == list:
            self.view.show_movie_header('Todas las peliculas')
            for movie in movies:
                self.view.show_movies(movie)
                self.view.show_movie_midder()
            self.view.show_movie_footer()
        else:
            self.view.error(
                'PROBLEMAS AL MOSTRAR TODAS LAS PELICULAS. REVISA.')
        return

    def read_movie_name(self):
        self.view.ask('Nombre: ')
        name = input()
        names = self.model.read_movie_name(name)
        if type(names) == list:
            self.view.show_movie_header('Datos de la pelicula ' + name + ' ')
            for name in names:
                self.view.show_movies(name)
                self.view.show_movie_midder()
            self.view.show_movie_footer()
        else:
            self.view.error('PROBLEMAS AL MOSTRAR LAS PELICULAS. REVISA.')
        return

    def update_movie(self):
        self.view.ask('ID de la pelicula a actualizar: ')
        id_movie = input()
        movie = self.model.read_movie(id_movie)
        if type(movie) == tuple:
            self.view.show_movie_header('Datos de la pelicula' + id_movie +
                                        ' ')
            self.view.show_movies(movie)
            self.view.show_movie_midder()
            self.view.show_movie_footer()
        else:
            if movie == None:
                self.view.error('LA PELICULA NO EXISTE')
            else:
                self.view.error('PROBLEMAS AL MOSTRAR LA PELICULA. REVISA.')
            return
        self.view.msg(
            'Ingresa los valores a modificar (vacio para dejarlo igual):')
        whole_vals = self.ask_movie()
        fields, vals = self.update_list([
            'm_name', 'm_genre', 'm_description', 'm_duration',
            'm_clasification'
        ], whole_vals)
        vals.append(id_movie)
        vals = tuple(vals)
        out = self.model.update_movie(fields, vals)
        if out == True:
            self.view.ok(id_movie, 'actualizo')
        else:
            self.view.error('PROBLEMAS AL ACTUALIZAR LA PELICULA. REVISA.')
        return

    def delete_movie(self):
        self.view.ask('ID de pelicula a eliminar: ')
        id_movie = input()
        count = self.model.delete_movie(id_movie)
        if count != 0:
            self.view.ok(id_movie, 'elimino')
        else:
            if count == 0:
                self.view.error('LA PELICULA NO EXISTE.')
            else:
                self.view.error('PROBLEMAS AL ELIMINAR LA PELICULA. REVISA.')
        return

    """
    ********************************
    * Controllers for admin. halls *
    ********************************
    """

    def halls_menu(self):
        o = '0'
        while o != '7':
            self.view.halls_menu()
            self.view.option('7')
            o = input()
            if o == '1':
                self.create_hall()
            elif o == '2':
                self.read_hall()
            elif o == '3':
                self.read_all_halls()
            elif o == '4':
                self.read_halls_name()
            elif o == '5':
                self.update_hall()
            elif o == '6':
                self.delete_hall()
            elif o == '7':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_hall(self):
        self.view.ask('Sala: ')
        id_hall = input()
        self.view.ask('Nombre: ')
        h_name = input()
        self.view.ask('Total de asientos: ')
        total_seats = input()
        return [id_hall, h_name, total_seats]

    def create_hall(self):
        id_hall, h_name, total_seats = self.ask_hall()
        out = self.model.create_hall(id_hall, h_name, total_seats)
        if out == True:
            self.view.ok(id_hall, 'agrego')
        else:
            if out.errno == 1062:
                self.view.error('LA SALA YA EXISTE.')
            else:
                self.view.error('PROBLEMAS AL AGREGAR. REVISA.')
        return

    def read_hall(self):
        self.view.ask('Sala: ')
        id_hall = input()
        hall = self.model.read_hall(id_hall)
        if type(hall) == tuple:
            self.view.show_hall_header('Datos de la sala ' + id_hall + ' ')
            self.view.show_hall(hall)
            self.view.show_hall_midder()
            self.view.show_hall_footer()
        else:
            if hall == None:
                self.view.error('LA SALA NO EXISTE.')
            else:
                self.view.error('PROBLEMAS AL MOSTRAR LA SALA. REVISA.')
        return

    def read_all_halls(self):
        halls = self.model.read_all_halls()
        if type(halls) == list:
            self.view.show_hall_header('Todas las salas')
            for hall in halls:
                self.view.show_hall(hall)
                self.view.show_hall_midder()
            self.view.show_hall_footer()
        else:
            self.view.error('PROBLEMAS AL LEER TODAS LAS SALAS. REVISA.')

    def read_halls_name(self):
        self.view.ask('Nombre de la sala: ')
        h_name = input()
        halls = self.model.read_halls_name(h_name)
        if type(halls) == list:
            self.view.show_hall_header('Salas con nombre ' + h_name + ' ')
            for hall in halls:
                self.view.show_hall(hall)
                self.view.show_hall_midder()
            self.view.show_hall_footer()
        else:
            self.view.error('PROBLEMAS AL LEER LAS SALAS. REVISA.')
        return

    def update_hall(self):
        self.view.ask('Sala a actualizar: ')
        id_hall = input()
        hall = self.model.read_hall(id_hall)
        if type(hall) == tuple:
            self.view.show_hall_header('Datos de la sala ' + id_hall + ' ')
            self.view.show_hall(hall)
            self.view.show_hall_midder()
            self.view.show_hall_footer()
        else:
            if hall == None:
                self.view.error('LA SALA NO EXISTE.')
            else:
                self.view.error('PROBLEMAS AL MOSTRAR LA SALA. REVISA.')
            return
        self.view.msg(
            'Ingresa los valores a modificar (vacio para dejarlo igual):')
        whole_vals = self.ask_hall()
        fields, vals = self.update_list(['id_hall', 'h_name', 'h_total_seats'],
                                        whole_vals)
        vals.append(id_hall)
        vals = tuple(vals)
        out = self.model.update_hall(fields, vals)
        if out == True:
            self.view.ok(id_hall, 'actualizo')
        else:
            self.view.error('PROBLEMAS AL ACTULIZAR LA SALA. REVISA.')
        return

    def delete_hall(self):
        self.view.ask('Sala a eliminar: ')
        id_hall = input()
        count = self.model.delete_hall(id_hall)
        if count != 0:
            self.view.ok(id_hall, 'elimino')
        else:
            if count == 0:
                self.view.error('LA SALA NO EXISTE.')
            else:
                self.view.error('PROBLEMAS AL ELIMINAR LA SALA. REVISA.')
        return

    """
    ************************************
    * Controllers for admin. schedules *
    ************************************
    """

    def schedules_menu(self):
        o = '0'
        while o != '6':
            self.view.schedules_menu()
            self.view.option('6')
            o = input()
            if o == '1':
                self.create_schedule()
            elif o == '2':
                self.read_schedule()
            elif o == '3':
                self.read_all_schedules()
            elif o == '4':
                self.update_schedule()
            elif o == '5':
                self.delete_schedule()
            elif o == '6':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_schedule(self):
        self.view.ask('ID Funcion: ')
        id_schedule = input()
        self.view.ask('ID pelicula: ')
        id_movie = input()
        self.view.ask('Sala: ')
        id_hall = input()
        self.view.ask('Hora de funcion: ')
        showtime = input()
        return [id_schedule, id_movie, id_hall, showtime]

    def create_schedule(self):
        id_schedule, id_movie, id_hall, showtime = self.ask_schedule()
        out = self.model.create_schedule(id_schedule, id_movie, id_hall,
                                         showtime)
        if out == True:
            self.view.ok(id_schedule, 'agrego')
        else:
            if out.errno == 1062:
                self.view.error('LA FUNCION YA EXISTE.')
            else:
                self.view.error('PROBLEMAS AL AGREGAR LA FUNCION. REVISA.')
        return

    def read_schedule(self):
        self.view.ask('ID Funcion: ')
        id_schedule = input()
        schedule = self.model.read_schedule(id_schedule)
        if type(schedule) == tuple:
            self.view.show_schedule_header('Datos de la funcion')
            self.view.show_schedule(schedule)
            self.view.show_schedule_midder()
            self.view.show_schedules_footer()
        else:
            if schedule == None:
                self.view.error('LA FUNCION NO EXISTE.')
            else:
                self.view.error('PROBLEMAS AL MOSTRAR LA FUNCION. REVISA.')
        return

    def update_schedule(self):
        self.view.ask('ID Funcion: ')
        id_schedule = input()
        schedule = self.model.read_schedule(id_schedule)
        if type(schedule) == tuple:
            self.view.show_schedule_header('Datos de la funcion')
            self.view.show_schedule(schedule)
            self.view.show_schedule_midder()
            self.view.show_schedules_footer()
        else:
            if schedule == None:
                self.view.error('LA FUNCION NO EXISTE.')
            else:
                self.view.error('PROBLEMAS AL MOSTRAR LA FUNCION. REVISA.')
            return
        self.view.msg(
            'Ingresa los valores a modificar (vacio para dejarlo igual):')
        whole_vals = self.ask_schedule()
        fields, vals = self.update_list(
            ['id_schedule', 'id_movie', 'id_hall', 's_showtime'], whole_vals)
        vals.append(id_schedule)
        vals = tuple(vals)
        out = self.model.update_schedule(fields, vals)
        if out == True:
            self.view.ok(id_schedule, 'actualizo')
        else:
            self.view.error('PROBLEMAS AL ACTUALIZAR LA FUNCION. REVISA.')
        return

    def delete_schedule(self):
        self.view.ask('ID Funcion a eliminar: ')
        id_schedule = input()
        count = self.model.delete_schedule(id_schedule)
        if count != 0:
            self.view.ok(id_schedule, 'elimino')
        else:
            if count == 0:
                self.view.error('LA FUNCION NO EXISTE.')
            else:
                self.view.error('PROBLEMAS AL ELIMINAR LA FUNCION. REVISA.')
        return

    """
    ********************************
    * Controllers for admin. seats *
    ********************************
    """

    def seats_menu(self):
        o = '0'
        while o != '6':
            self.view.seats_menu()
            self.view.option('6')
            o = input()
            if o == '1':
                self.create_seat()
            elif o == '2':
                self.read_seat()
            elif o == '3':
                self.read_all_seats()
            elif o == '4':
                self.update_seat()
            elif o == '5':
                self.delete_seat()
            elif o == '6':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_seat(self):
        self.view.ask('ID Asiento: ')
        id_seat = input()
        self.view.ask('Asiento: ')
        no_seat = input()
        s_state = 'free'
        self.view.ask('Sala: ')
        id_hall = input()
        return [id_seat, no_seat, s_state, id_hall]

    def create_seat(self):
        id_seat, no_seat, s_state, id_hall = self.ask_seat()
        out = self.model.create_seat(id_seat, no_seat, s_state, id_hall)
        if out == True:
            self.view.ok(id_seat, 'agrego')
        else:
            if out.errno == 1062:
                self.view.error('EL ASIENTO YA EXISTE.')
            else:
                self.view.error('PROBLEMAS AL AGREGAR EL ASIENTO. REVISA.')
        return

    def read_seat(self):
        self.view.ask('Asiento: ')
        id_seat = input()
        seat = self.model.read_seat(id_seat)
        if type(seat) == tuple:
            self.view.show_seat_header('Datos del asiento' + id_seat + ' ')
            self.view.show_seat(seat)
            self.view.show_seat_midder()
            self.view.show_seat_footer()
        else:
            if seat == None:
                self.view.error('EL ASIENTO NO EXISTE.')
            else:
                self.view.error('PROBLEMAS AL MOSTRAR EL ASIENTO. REVISA.')
        return

    def read_all_seats(self):
        self.view.ask('Sala: ')
        id_hall = input()
        seats = self.model.read_all_seats(id_hall)
        if type(seats) == list:
            self.view.show_seat_header(' Todos los asientos de la sala ' +
                                       id_hall + ' ')
            for seat in seats:
                self.view.show_seat(seat)
                self.view.show_seat_midder()
            self.view.show_seat_footer()
        else:
            self.view.error('PROBLEMAS AL MOSTRAR TODOS LOS ASIENTOS. REVISA.')
        return

    def update_seat(self):
        self.view.ask('Asiento a actualizar: ')
        id_seat = input()
        seat = self.model.read_seat(id_seat)
        if type(seat) == tuple:
            self.view.show_seat_header('Datos del asiento ' + id_seat + ' ')
            self.view.show_seat(seat)
            self.view.show_seat_midder()
            self.view.show_seat_footer()
        else:
            if seat == None:
                self.view.error('EL ASIENTO NO EXISTE.')
            else:
                self.view.error('PROBLEMAS AL MOSTRAR EL ASIENTO. REVISA.')
            return
        self.view.msg(
            'Ingresa los valores a modificar (vacio para dejarlo igual):')
        whole_vals = self.ask_seat()
        fields, vals = self.update_list(
            ['id_seat', 'no_seat', 's_state', 'id_hall'], whole_vals)
        vals.append(id_seat)
        vals = tuple(vals)
        out = self.model.update_seat(fields, vals)
        if out == True:
            self.view.ok(id_seat, 'actualizo')
        else:
            self.view.error('PROBLEMAS AL ACTULIZAR EL ASIENTO. REVISA.')
        return

    def delete_seat(self):
        self.view.ask('ID del Asiento a eliminar: ')
        id_seat = input()
        count = self.model.delete_seat(id_seat)
        if count != 0:
            self.view.ok(id_seat, 'elimino')
        else:
            if count == 0:
                self.view.error('EL ASIENTO NO EXISTE.')
            else:
                self.view.error('PROBLEMAS AL ELIMINAR EL ASIENTO. REVISA.')
        return

    """
    ***************************************
    * Controllers for admin. type tickets *
    ***************************************
    """

    def type_tickets_menu(self):
        o = '0'
        while o != '6':
            self.view.type_ticket_menu()
            self.view.option('6')
            o = input()
            if o == '1':
                self.create_type_ticket()
            elif o == '2':
                self.read_type_ticket()
            elif o == '3':
                self.read_all_type_tickets()
            elif o == '4':
                self.update_type_ticket()
            elif o == '5':
                self.delete_type_ticket()
            elif o == '6':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_type_ticket(self):
        self.view.ask('Nombre: ')
        tt_name = input()
        self.view.ask('Precio: ')
        tt_price = input()
        return [tt_name, tt_price]

    def create_type_ticket(self):
        tt_name, tt_price = self.ask_type_ticket()
        out = self.model.create_type_ticket(tt_name, tt_price)
        if out == True:
            self.view.ok(tt_name, 'agrego')
        else:
            if out.errno == 1062:
                self.view.error('EL TIPO DE BOLETO YA EXISTE.')
            else:
                self.view.error(
                    'PROBLEMAS AL AGREGAR EL TIPO DE BOLETO. REVISA.')
        return

    def read_type_ticket(self):
        self.view.ask('Tipo de boleto: ')
        tt_name = input()
        name = self.model.read_type_ticket(tt_name)
        if type(name) == tuple:
            self.view.show_type_ticket_header('Datos del tipo ' + tt_name +
                                              ' ')
            self.view.show_type_ticket(name)
            self.view.show_type_ticket_midder()
            self.view.show_type_ticket_footer()
        else:
            if name == None:
                self.view.error('EL TIPO DE BOLETO NO EXISTE.')
            else:
                self.view.error(
                    'PROBLEMAS AL MOSTRAR EL TIPO DE BOLETO. REVISA.')
        return

    def read_all_type_tickets(self):
        names = self.model.read_all_type_tickets()
        if type(names) == list:
            self.view.show_type_ticket_header('Todos los tipos de boletos')
            for name in names:
                self.view.show_type_ticket(name)
                self.view.show_type_ticket_midder()
            self.view.show_type_ticket_footer()
        else:
            self.view.error(
                'PROBLEMAS AL MOSTRAR TODOS LOS TIPOS DE BOLETOS. REVISA.')
        return

    def update_type_ticket(self):
        self.view.ask('Tipo de boleto a actualizar: ')
        tt_name = input()
        name = self.model.read_type_ticket(tt_name)
        if type(name) == tuple:
            self.view.show_type_ticket_header('Datos del tipo ' + tt_name +
                                              ' ')
            self.view.show_type_ticket(name)
            self.view.show_type_ticket_midder()
            self.view.show_type_ticket_footer()
        else:
            if name == None:
                self.view.error('EL TIPO DE BOLETO NO EXISTE.')
            else:
                self.view.error(
                    'PROBLEMAS AL MOSTRAR EL TIPO DE BOLETO. REVISA.')
            return
        self.view.msg(
            'Ingresa los valores a modificar (vacio para dejarlo igual):')
        whole_vals = self.ask_type_ticket()
        fields, vals = self.update_list(['tt_name', 'tt_price'], whole_vals)
        vals.append(tt_name)
        vals = tuple(vals)
        out = self.model.update_type_ticket(fields, vals)
        if out == True:
            self.view.ok(tt_name, 'actualizo')
        else:
            self.view.error(
                'PROBLEMAS AL ACTUALIZAR EL TIPO DE BOLETO. REVISA.')
        return

    def delete_type_ticket(self):
        self.view.ask('Tipo de boleto a eliminar: ')
        tt_name = input()
        count = self.model.delete_type_ticket(tt_name)
        if count != 0:
            self.view.ok(tt_name, 'elimino')
        else:
            if count == 0:
                self.view.error('EL TIPO DE BOLETO NO EXISTE.')
            else:
                self.view.error(
                    'PROBLEMAS AL ELIMINAR EL TIPO DE BOLETO. REVISA.')
        return

    """
    **********************************
    * Controllers for admin. tickets *
    **********************************
    """

    def tickets_menu(self):
        o = '0'
        while o != '6':
            self.view.tickets_menu()
            self.view.option('6')
            o = input()
            if o == '1':
                self.read_ticket()
            elif o == '2':
                self.read_all_tickets()
            elif o == '3':
                self.read_tickets_date()
            elif o == '4':
                self.update_ticket()
            elif o == '5':
                self.delete_ticket()
            elif o == '6':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_ticket(self):
        self.view.ask('Fecha: ')
        t_date = input()
        self.view.ask('ID Pelicula: ')
        id_movie = input()
        self.view.ask('Sala: ')
        id_hall = input()
        self.view.ask('Usuario: ')
        id_user = input()
        self.view.ask('Tipo boleto: ')
        name = input()
        self.view.ask('Asiento: ')
        id_seat = input()
        return [t_date, id_movie, id_hall, id_user, name, id_seat]

    def read_ticket(self):
        self.view.ask('ID Ticket: ')
        id_ticket = input()
        ticket = self.model.read_ticket(id_ticket)
        if type(ticket) == tuple:
            self.view.show_ticket_header('Datos del ticket ' + id_ticket + ' ')
            self.view.show_ticket(ticket)
            self.view.show_ticket_midder()
            self.view.show_ticket_total(ticket)
            self.view.show_ticket_footer()
        else:
            if ticket == None:
                self.view.error('EL TICKET NO EXISTE')
            else:
                self.view.error(
                    'PROBLEMAS AL LEER EL TICKET. VUELVE MAS TARDE')
        return

    def read_all_tickets(self):
        tickets = self.model.read_all_tickets()
        if type(tickets) == list:
            self.view.show_ticket_header('Todos los tickets')
            for ticket in tickets:
                self.view.show_ticket(ticket)
                self.view.show_ticket_midder()
            self.view.show_ticket_footer()
            self.view.show_ticket_total(ticket)
        else:
            self.view.error('PROBLEMAS A MOSTRAR TODOS LOS TICKETS. REVISA.')
        return

    def read_tickets_date(self):
        self.view.ask('Fecha: ')
        date = input()
        dates = self.model.read_tickets_date(date)
        if type(dates) == list:
            self.view.show_ticket_header('Tickets del dia ' + date + ' ')
            for date in dates:
                self.view.show_ticket(date)
                self.view.show_ticket_midder()
            self.view.show_ticket_footer()
            self.view.show_ticket_total(date)
        else:
            self.view.error('PROBLEMAS AL MOSTRAR LOS TICKETS. REVISA.')
        return

    def update_ticket(self):
        self.view.ask('ID Ticket a actualizar: ')
        id_ticket = input()
        ticket = self.model.read_ticket(id_ticket)
        if type(ticket) == tuple:
            self.view.show_ticket_header('Datos del ticket ' + id_ticket + ' ')
            self.view.show_ticket(ticket)
            self.view.show_ticket_midder()
            self.view.show_ticket_total(ticket)
            self.view.show_ticket_footer()
        else:
            if ticket == None:
                self.view.error('EL TICKET NO EXISTE')
            else:
                self.view.error(
                    'PROBLEMAS AL LEER EL TICKET. VUELVE MAS TARDE')
            return
        self.view.msg(
            'Ingresa los valores a modificar (vacio para dejarlo igual):')
        whole_vals = self.ask_ticket()
        fields, vals = self.update_list(
            ['t_date', 'id_movie', 'id_hall', 'id_user', 'name', 'id_seat'],
            whole_vals)
        vals.append(id_ticket)
        vals = tuple(vals)
        out = self.model.update_ticket(fields, vals)
        if out == True:
            self.view.ok(id_ticket, 'actualizo')
        else:
            self.view.error('PROBLEMAS AL ACTUALIZAR EL TICKET. REVISA.')
        return

    def delete_ticket(self):
        self.view.ask('ID Ticket a eliminar: ')
        id_ticket = input()
        count = self.model.delete_ticket(id_ticket)
        if count != 0:
            self.view.ok(id_ticket, 'elimino')
        else:
            if count == 0:
                self.view.error('EL TICKET NO EXISTE.')
            else:
                self.view.error('PROBLEMAS AL ELIMINAR EL TICKET. REVISA.')
        return

    """
    **********************************
    * Controllers for administrators *
    **********************************
    """

    def admins_menu(self):
        o = '0'
        while o != '7':
            self.view.admins_menu()
            self.view.option('7')
            o = input()
            if o == '1':
                self.create_admin()
            elif o == '2':
                self.read_admin()
            elif o == '3':
                self.read_all_admins()
            elif o == '4':
                self.read_admins_name()
            elif o == '5':
                self.update_admin()
            elif o == '6':
                self.delete_admin()
            elif o == '7':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_admin(self):
        self.view.ask('Nombre: ')
        name = input()
        self.view.ask('Apellido paterno: ')
        sname1 = input()
        self.view.ask('Apellido materno: ')
        sname2 = input()
        self.view.ask('Telefono: ')
        phone = input()
        self.view.ask('Email: ')
        email = input()
        self.view.ask('Cargo: ')
        charge = input()
        return [name, sname1, sname2, phone, email, charge]

    def create_admin(self):
        name, sname1, sname2, phone, email, charge = self.ask_admin()
        out = self.model.create_admin(name, sname1, sname2, phone, email,
                                      charge)
        if out == True:
            self.view.ok(name + ' ' + sname1 + ' ' + sname2, 'agrego')
        else:
            self.view.error('PROBLEMAS AL AGREGAR EL ADMINISTRADOR. REVISA.')
        return

    def read_admin(self):
        self.view.ask('ID Admin: ')
        id_admin = input()
        admin = self.model.read_admin(id_admin)
        if type(admin) == tuple:
            self.view.show_admin_header('Datos del admin ' + id_admin + ' ')
            self.view.show_admin(admin)
            self.view.show_admin_midder()
            self.view.show_admin_footer()
        else:
            if admin == None:
                self.view.error('EL ADMINISTRADOR NO EXISTE')
            else:
                self.view.error(
                    'PROBLEMAS AL MOSTRAR EL ADMINISTRADOR. REVISA.')
        return

    def read_all_admins(self):
        admins = self.model.read_all_admins()
        if type(admins) == list:
            self.view.show_admin_header('Todos los administradores')
            for admin in admins:
                self.view.show_admin(admin)
                self.view.show_admin_midder()
            self.view.show_admin_footer()
        else:
            self.view.error(
                'PROBLEMAS AL MOSTRAR TODOS LOS ADMINISTRADORES. REVISA.')
        return

    def read_admins_name(self):
        self.view.ask('Nombre: ')
        name = input()
        names = self.model.read_admins_name(name)
        if type(names) == list:
            self.view.show_admin_header('Administradores con nombre ' + name +
                                        ' ')
            for name in names:
                self.view.show_admin(name)
                self.view.show_admin_midder()
            self.view.show_admin_footer()
        else:
            self.view.error(
                'PROBLEMAS AL MOSTRAR LOS ADMINISTRADORES. REVISA.')
        return

    def update_admin(self):
        self.view.ask('ID Admin a actualizar: ')
        id_admin = input()
        admin = self.model.read_admin(id_admin)
        if type(admin) == tuple:
            self.view.show_admin_header('Datos del admin ' + id_admin + ' ')
            self.view.show_admin(admin)
            self.view.show_admin_midder()
            self.view.show_admin_footer()
        else:
            if admin == None:
                self.view.error('EL ADMINISTRADOR NO EXISTE')
            else:
                self.view.error(
                    'PROBLEMAS AL MOSTRAR EL ADMINISTRADOR. REVISA.')
            return
        self.view.msg(
            'Ingresa los valores a modificar (vacio para dejarlo igual):')
        whole_vals = self.ask_admin()
        fields, vals = self.update_list([
            'a_name', 'a_sname1', 'a_sname2', 'a_phone', 'a_email', 'a_charge'
        ], whole_vals)
        vals.append(id_admin)
        vals = tuple(vals)
        out = self.model.update_admin(fields, vals)
        if out == True:
            self.view.ok(id_admin, 'actualizo')
        else:
            self.view.error(
                'PROBLEMAS AL ACTUALIZAR EL ADMINISTRADOR. REVISA.')
        return

    def delete_admin(self):
        self.view.ask('ID Admin a eliminar: ')
        id_admin = input()
        count = self.model.delete_admin(id_admin)
        if count != 0:
            self.view.ok(id_admin, 'elimino')
        else:
            if count == 0:
                self.view.error('EL ADMINISTRADOR NO EXISTE.')
            else:
                self.view.error(
                    'PROBLEMAS AL ELIMINAR EL ADMINISTRADOR. REVISA.')
        return
示例#21
0
class Controller():
    """The Controller class is part of the model-view-controller architecture.

    Links views and Model and controls interaction between them."
    """

    # %%
    def __init__(self):
        """Initialize the object.

        First part of two-part initialization.
        The initialization done here should be low risk - we need the GUI to
        be built before we can show error messages.
        """
        self.model = Model()

        # Create the panels by instantiating each of the tabs. Note the order
        # in the list is the tab order in the GUI.
        self.about = About(self)
        self.managedata = ManageData(self)
        self.runforecast = RunForecast(self)
        self.forecastbytime = ForecastByTime(self)
        self.forecastdistribution = ForecastDistribution(self)
        self.forecastbygeography = ForecastByGeography(self)
        self.forecastbystate = ForecastByState(self)
        self.pollviewer = PollViewer(self)

        self.panels = [
            self.about, self.managedata, self.runforecast, self.forecastbytime,
            self.forecastdistribution, self.forecastbygeography,
            self.forecastbystate, self.pollviewer
        ]

        # Create tabs, note the order here is the display order.
        self.tabs = Tabs(tabs=[p.panel for p in self.panels])

    # %%
    def setup(self):
        """Set up object. Second part of two-part initialization."""
        for panel in self.panels:
            panel.setup()

    # %%
    def update(self):
        """Update the object."""
        self.model.read_rawdata()
        years = self.model.get_years()
        self.managedata.update(years)
        self.runforecast.update(years)

    # %%
    def cross_check(self):
        """Cross checks the model data."""
        return self.model.cross_check()

    # %%
    def calculate_forecast(self, year):
        """Calculate the forecast for the election year."""
        self.model.calculate_forecast(year)
        if ~self.model.error_status:
            return "Forecast completed without error."
        else:
            return self.model.error_string

    # %%
    def load_forecast(self, year):
        """Load forecast data into model."""
        self.model.load_forecast(year)
        if ~self.model.error_status:
            # Update the plots with the newly loaded data
            self.forecastbytime.update(self.model.electoral_maximum)
            self.forecastdistribution.update(self.model.electoral_distribution)
            self.forecastbygeography.update(self.model.state)
            self.forecastbystate.update(self.model.state, self.model.polls)
            self.pollviewer.update(self.model.polls)
            return "Year forecast loaded without error."
        else:
            return self.model.error_string

    # %%
    def display(self):
        """Display the visualization.

        Calls the Bokeh methods to make the
        application start. Note the server actually renders the GUI in the
        browser.

        Returns
        -------
        None
        """
        curdoc().add_root(self.tabs)
        curdoc().title = 'silkworm'
class MainWindow(QMainWindow, Ui_MainWindow):
    set_cross_bar_signal = pyqtSignal('int', 'int', 'int')
    set_brush_stats_signal = pyqtSignal('int', 'int')

    class OpMode(Enum):
        CURSOR = 1
        BRUSH = 2

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.parent = parent
        self.setupUi(self)
        self.setWindowState(Qt.WindowMaximized)
        self.model = Model()

        self._focus_point = [0, 0, 0]  # w, h, d or x, y, z
        self._hu_window = [0, 400]
        self._label_opacity = 50  # 0-100
        self._operation_mode = self.OpMode.CURSOR

        self.clear_views()

    def update_scenes(self, scenes='asc', raw=True, anno=True):
        if not self.model.is_valid():
            return
        if 'a' in scenes:
            if raw:
                self.aGraphicsView.raw_img_item.setPixmap(
                    QPixmap.fromImage(
                        QImage(
                            self.model.get_2D_map_in_window(
                                'a', self.focus_point[2], 'raw',
                                self.window_bottom, self.window_top),
                            self.model.get_size()[1],
                            self.model.get_size()[0],
                            self.model.get_size()[1] *
                            1,  # bytesperline = width*channel
                            QImage.Format_Grayscale8)))  # x, y
            if anno:
                self.aGraphicsView.anno_img_item.setPixmap(
                    QPixmap.fromImage(
                        QImage(
                            self.model.get_2D_map_in_window(
                                'a',
                                self.focus_point[2],
                                'anno',
                                colored_anno=True,
                                alpha=self.label_opacity / 100),
                            self.model.get_size()[1],
                            self.model.get_size()[0],
                            self.model.get_size()[1] *
                            4,  # bytesperline = width*channel
                            QImage.Format_RGBA8888)))  # x, y

        if 's' in scenes:
            if raw:
                self.sGraphicsView.raw_img_item.setPixmap(
                    QPixmap.fromImage(
                        QImage(
                            self.model.get_2D_map_in_window(
                                's', self.focus_point[0], 'raw',
                                self.window_bottom, self.window_top),
                            self.model.get_size()[2],
                            self.model.get_size()[1],
                            self.model.get_size()[2] *
                            1,  # bytesperline = width*channel
                            QImage.Format_Grayscale8)))
            if anno:
                self.sGraphicsView.anno_img_item.setPixmap(
                    QPixmap.fromImage(
                        QImage(
                            self.model.get_2D_map_in_window(
                                's',
                                self.focus_point[0],
                                'anno',
                                colored_anno=True,
                                alpha=self.label_opacity / 100),
                            self.model.get_size()[2],
                            self.model.get_size()[1],
                            self.model.get_size()[2] *
                            4,  # bytesperline = width*channel
                            QImage.Format_RGBA8888)))

        if 'c' in scenes:
            if raw:
                self.cGraphicsView.raw_img_item.setPixmap(
                    QPixmap.fromImage(
                        QImage(
                            self.model.get_2D_map_in_window(
                                'c', self.focus_point[1], 'raw',
                                self.window_bottom, self.window_top),
                            self.model.get_size()[2],
                            self.model.get_size()[0],
                            self.model.get_size()[2] *
                            1,  # bytesperline = width*channel
                            QImage.Format_Grayscale8)))
            if anno:
                self.cGraphicsView.anno_img_item.setPixmap(
                    QPixmap.fromImage(
                        QImage(
                            self.model.get_2D_map_in_window(
                                'c',
                                self.focus_point[1],
                                'anno',
                                colored_anno=True,
                                alpha=self.label_opacity / 100),
                            self.model.get_size()[2],
                            self.model.get_size()[0],
                            self.model.get_size()[2] *
                            4,  # bytesperline = width*channel
                            QImage.Format_RGBA8888)))

    def update_anno_targets_list(self):
        self.model.compute_img_stats('anno')
        self.targetList.clear()
        num_labels = self.model.get_anno_num_labels()
        for i_label in range(1, num_labels + 1):
            # create icon
            pixmap = QPixmap(100, 100)
            pixmap.fill(self.model.label_colors[i_label - 1])
            icon = QIcon(pixmap)
            # items
            target_centers = self.model.get_anno_target_centers_for_label(
                i_label)  # [n, (d, h, w)]
            target_ids = self.model.get_anno_target_ids()
            for i_centers in range(len(target_centers)):
                item = QListWidgetItem('[Label_%d] #%d' %
                                       (i_label, i_centers + 1))
                item.setIcon(icon)
                item.target_id = target_ids[i_centers]
                item.target_label = i_label
                self.targetList.addItem(item)

    def init_views(self):
        """after new file loaded"""
        self.update_scenes('asc')
        self.aGraphicsView.init_view(self.model.get_size())
        self.sGraphicsView.init_view(self.model.get_size())
        self.cGraphicsView.init_view(self.model.get_size())
        self.xSpinBox.setMaximum(self.model.get_size()[0])
        self.ySpinBox.setMaximum(self.model.get_size()[1])
        self.zSpinBox.setMaximum(self.model.get_size()[2])
        self.lineEditImageName.setText(self.model.get_img_filepath('raw'))
        self.lineEditAnnotationName.setText(
            self.model.get_img_filepath('anno'))
        self.lineEditImageSize.setText(
            '(%d, %d, %d)' %
            (self.model.get_size()[0], self.model.get_size()[1],
             self.model.get_size()[2]))
        self.valueUnderCursorList.addItem(QListWidgetItem())
        self.valueUnderCursorList.addItem(QListWidgetItem())
        self.update_anno_targets_list()
        self.operation_mode = self.OpMode.CURSOR
        self.opModeTab.setCurrentIndex(0)

    def clear_views(self):
        """welcome page and after clear images"""
        self._focus_point = [0, 0, 0]
        self.aGraphicsView.clear()
        self.sGraphicsView.clear()
        self.cGraphicsView.clear()
        self.xSpinBox.setMaximum(1)
        self.ySpinBox.setMaximum(1)
        self.zSpinBox.setMaximum(1)
        self.lineEditImageName.setText('Null')
        self.lineEditAnnotationName.setText('Null')
        self.lineEditImageSize.setText('(0, 0, 0)')
        for i in range(self.valueUnderCursorList.count()):
            self.valueUnderCursorList.item(0).setText('')
        self.targetList.clear()
        self.operation_mode = self.OpMode.CURSOR
        self.opModeTab.setCurrentIndex(0)
        self.brushSizeSpinBox.setValue(5)

    @property
    def operation_mode(self):
        return self._operation_mode

    @operation_mode.setter
    def operation_mode(self, mode):
        if not isinstance(mode, self.OpMode):
            return
        if mode == self.OpMode.CURSOR:
            self.opModeTab.setCurrentIndex(0)
        if mode == self.OpMode.BRUSH:
            self.opModeTab.setCurrentIndex(1)

        if self._operation_mode != mode:
            if mode == self.OpMode.CURSOR:
                self.set_brush_stats_signal.emit(BRUSH_TYPE_NO_BRUSH, 5)
            if mode == self.OpMode.BRUSH:
                if self.circleRadioButton.isChecked():
                    self.set_brush_stats_signal.emit(
                        BRUSH_TYPE_CIRCLE_BRUSH, self.brushSizeSlider.value())
                elif self.rectRadioButton.isChecked():
                    self.set_brush_stats_signal.emit(
                        BRUSH_TYPE_RECT_BRUSH, self.brushSizeSlider.value())
            self._operation_mode = mode

    @property
    def focus_point(self):
        return self._focus_point.copy()

    @focus_point.setter
    def focus_point(self, new_focus_point):
        if all([
                new_c == c
                for new_c, c in zip(new_focus_point, self._focus_point)
        ]):
            return
        scenes = ''
        # check boundary
        if self.model.get_size() is None:
            self._focus_point = [0, 0, 0]
            return
        for i in range(3):
            if new_focus_point[i] < 0:
                new_focus_point[i] = 0
            if new_focus_point[i] >= self.model.get_size()[i]:
                new_focus_point[i] = self.model.get_size()[i] - 1

        if new_focus_point[2] != self._focus_point[2]:
            scenes += 'a'
        if new_focus_point[0] != self._focus_point[0]:
            scenes += 's'
        if new_focus_point[1] != self._focus_point[1]:
            scenes += 'c'
        self._focus_point = new_focus_point

        # ui
        for i, spin_box in enumerate(
            [self.xSpinBox, self.ySpinBox, self.zSpinBox]):
            spin_box.setValue(new_focus_point[i] + 1)
        self.valueUnderCursorList.item(0).setText(
            'image:\t\t%d' %
            self.model.get_voxel_value_at_point(self.focus_point, 'raw'))
        self.valueUnderCursorList.item(1).setText(
            'annotation:\t%d' %
            self.model.get_voxel_value_at_point(self.focus_point, 'anno'))
        self.set_cross_bar_signal.emit(new_focus_point[0], new_focus_point[1],
                                       new_focus_point[2])
        self.update_scenes(scenes)

    @property
    def label_opacity(self):
        return self._label_opacity

    @label_opacity.setter
    def label_opacity(self, lo):
        if lo < 0:
            lo = 0
        if lo > 100:
            lo == 100
        self._label_opacity = lo
        self.findChild(QSpinBox, 'labelOpacitySpinBox').setValue(lo)
        self.update_scenes('asc', raw=False)

    @property
    def window_bottom(self):
        return self._hu_window[0]

    @property
    def window_top(self):
        return self._hu_window[1]

    @property
    def window_level(self):
        return (self._hu_window[0] + self._hu_window[1]) // 2

    @property
    def window_width(self):
        return self._hu_window[1] - self._hu_window[0]

    def set_hu_window_ui(self):
        self.windowLevelSpinBox.setValue(self.window_level)
        self.windowWidthSpinBox.setValue(self.window_width)
        self.windowBottomSpinBox.setValue(self.window_bottom)
        self.windowTopspinBox.setValue(self.window_top)

    @window_bottom.setter
    def window_bottom(self, bottom):
        if bottom < self.window_top:
            self._hu_window[0] = bottom
        self.set_hu_window_ui()
        self.update_scenes('asc', anno=False)

    @window_top.setter
    def window_top(self, top):
        if top > self.window_bottom:
            self._hu_window[1] = top
        self.set_hu_window_ui()
        self.update_scenes('asc', anno=False)

    @window_level.setter
    def window_level(self, level):
        old_level = self.window_level
        self._hu_window[0] += level - old_level
        self._hu_window[1] += level - old_level
        self.set_hu_window_ui()
        self.update_scenes('asc', anno=False)

    @window_width.setter
    def window_width(self, width):
        level = self.window_level
        self._hu_window[0] = level - width // 2
        self._hu_window[1] = self._hu_window[0] + width
        self.set_hu_window_ui()
        self.update_scenes('asc', anno=False)

    @pyqtSlot('float', 'float')
    def scale_all_scenes(self, scale_x, scale_y):
        self.aGraphicsView.scale(scale_x, scale_y)
        self.sGraphicsView.scale(scale_x, scale_y)
        self.cGraphicsView.scale(scale_x, scale_y)

    @pyqtSlot('int')
    def on_label_opacity_spin_box_changed(self, value):
        self.label_opacity = value

    @pyqtSlot('int', 'int', 'int')
    def move_focus_point(self, delta_x, delta_y, delta_z):
        self.focus_point = [
            self.focus_point[0] + delta_x, self.focus_point[1] + delta_y,
            self.focus_point[2] + delta_z
        ]

    @pyqtSlot('int', 'int', 'int')
    def set_focus_point(self, x, y, z):
        new_focus_point = self.focus_point
        for i, item in enumerate([x, y, z]):
            if item < 100000:  # bigger than this value means no change
                new_focus_point[i] = item
        self.focus_point = new_focus_point

    @pyqtSlot('float', 'float', 'float')
    def set_focus_point_by_ratio(self, xr, yr, zr):
        new_focus_point = self.focus_point
        for i, item in enumerate([xr, yr, zr]):
            if item >= 0:  # -1 means no change
                new_focus_point[i] = round(item * self.model.get_size()[i])
        self.focus_point = new_focus_point

    @pyqtSlot()
    def menu_open_triggered(self):
        filename, _ = QFileDialog.getOpenFileName(self,
                                                  'select file to open',
                                                  self.model.last_read_dir,
                                                  filter='*.nii.gz')
        if not filename:
            return

        if self.model.is_valid():
            message_box = QMessageBox(self)
            message_box.setWindowTitle('Image type selection')
            message_box.setText('Which type is the selected image?')
            message_box.setIcon(QMessageBox.Question)
            raw_img_button = QPushButton('raw image', message_box)
            anno_img_button = QPushButton('annotation image', message_box)
            message_box.addButton(raw_img_button, QMessageBox.AcceptRole)
            message_box.addButton(anno_img_button, QMessageBox.AcceptRole)
            message_box.setStandardButtons(QMessageBox.Cancel)
            message_box.exec()

            if message_box.clickedButton() == raw_img_button:
                img_type = 'raw'
            elif message_box.clickedButton() == anno_img_button:
                img_type = 'anno'
            else:
                return
        else:
            img_type = 'raw'

        try:
            if img_type == 'raw':
                self.clear_views()
                self.model.read_img(filename, img_type)
                self.init_views()
                self.focus_point = [
                    item // 2 for item in self.model.get_size()
                ]
            if img_type == 'anno':
                self.model.read_img(filename, img_type)
                self.init_views()
        except ImageTypeError as e:
            QMessageBox.warning(self, 'Wrong image type!', e.__str__())
            self.clear_views()

    @pyqtSlot()
    def menu_save_triggered(self):
        if not self.model.is_valid():
            return
        # if os.path.exists(self.model.get_img_filepath('anno')):
        #     default_filename = self.model.get_img_filepath('anno')
        # else:
        default_filename = os.path.join(
            self.model.last_save_dir,
            os.path.basename(self.model.get_img_filepath('raw')))

        filename, _ = QFileDialog.getSaveFileName(
            self,
            'select where to save the annotation file',
            default_filename,
            filter='*.nii.gz')
        self.model.save_anno(filename)

    @pyqtSlot()
    def menu_close_triggered(self):
        self.model.clear()
        self.clear_views()

    @pyqtSlot('int')
    def on_x_spin_box_value_changed(self, x):
        for i, spin_box in enumerate(
            [self.xSpinBox, self.ySpinBox, self.zSpinBox]):
            spin_box.blockSignals(True)
        self.set_focus_point(x - 1, 999999, 999999)
        for i, spin_box in enumerate(
            [self.xSpinBox, self.ySpinBox, self.zSpinBox]):
            spin_box.blockSignals(False)

    @pyqtSlot('int')
    def on_y_spin_box_value_changed(self, y):
        for i, spin_box in enumerate(
            [self.xSpinBox, self.ySpinBox, self.zSpinBox]):
            spin_box.blockSignals(True)
        self.set_focus_point(999999, y - 1, 999999)
        for i, spin_box in enumerate(
            [self.xSpinBox, self.ySpinBox, self.zSpinBox]):
            spin_box.blockSignals(False)

    @pyqtSlot('int')
    def on_z_spin_box_value_changed(self, z):
        for spin_box in [self.xSpinBox, self.ySpinBox, self.zSpinBox]:
            spin_box.blockSignals(True)
        self.set_focus_point(999999, 999999, z - 1)
        for spin_box in [self.xSpinBox, self.ySpinBox, self.zSpinBox]:
            spin_box.blockSignals(False)

    @pyqtSlot('int')
    def on_window_level_spin_box_value_changed(self, level):
        for spin_box in [
                self.windowLevelSpinBox, self.windowWidthSpinBox,
                self.windowBottomSpinBox, self.windowTopspinBox
        ]:
            spin_box.blockSignals(True)
        self.window_level = level
        for spin_box in [
                self.windowLevelSpinBox, self.windowWidthSpinBox,
                self.windowBottomSpinBox, self.windowTopspinBox
        ]:
            spin_box.blockSignals(False)

    @pyqtSlot('int')
    def on_window_width_spin_box_value_changed(self, width):
        for spin_box in [
                self.windowLevelSpinBox, self.windowWidthSpinBox,
                self.windowBottomSpinBox, self.windowTopspinBox
        ]:
            spin_box.blockSignals(True)
        self.window_width = width
        for spin_box in [
                self.windowLevelSpinBox, self.windowWidthSpinBox,
                self.windowBottomSpinBox, self.windowTopspinBox
        ]:
            spin_box.blockSignals(False)

    @pyqtSlot('int')
    def on_window_bottom_spin_box_value_changed(self, bottom):
        for spin_box in [
                self.windowLevelSpinBox, self.windowWidthSpinBox,
                self.windowBottomSpinBox, self.windowTopspinBox
        ]:
            spin_box.blockSignals(True)
        self.window_bottom = bottom
        for spin_box in [
                self.windowLevelSpinBox, self.windowWidthSpinBox,
                self.windowBottomSpinBox, self.windowTopspinBox
        ]:
            spin_box.blockSignals(False)

    @pyqtSlot('int')
    def on_window_top_spin_box_value_changed(self, top):
        for spin_box in [
                self.windowLevelSpinBox, self.windowWidthSpinBox,
                self.windowBottomSpinBox, self.windowTopspinBox
        ]:
            spin_box.blockSignals(True)
        self.window_top = top
        for spin_box in [
                self.windowLevelSpinBox, self.windowWidthSpinBox,
                self.windowBottomSpinBox, self.windowTopspinBox
        ]:
            spin_box.blockSignals(False)

    @pyqtSlot('QListWidgetItem*')
    def on_target_list_item_clicked(self, item):
        target_centers = self.model.get_anno_target_centers_for_label(
            item.target_label)
        d, h, w = target_centers[item.target_id - 1]
        self.set_focus_point(w, h, d)

    @pyqtSlot('int')
    def on_current_op_mode_tab_changed(self, current_index):
        if current_index == 0:
            self.operation_mode = self.OpMode.CURSOR
        if current_index == 1:
            self.operation_mode = self.OpMode.BRUSH

    @pyqtSlot('int')
    def on_brush_size_changed(self, size):
        if self.operation_mode == self.OpMode.CURSOR:
            return
        if self.circleRadioButton.isChecked():
            self.set_brush_stats_signal.emit(BRUSH_TYPE_CIRCLE_BRUSH, size)
        elif self.rectRadioButton.isChecked():
            self.set_brush_stats_signal.emit(BRUSH_TYPE_RECT_BRUSH, size)

    @pyqtSlot()
    def on_brush_type_clicked(self):
        if self.operation_mode == self.OpMode.CURSOR:
            return
        size = self.brushSizeSlider.value()
        if self.circleRadioButton.isChecked():
            self.set_brush_stats_signal.emit(BRUSH_TYPE_CIRCLE_BRUSH, size)
        elif self.rectRadioButton.isChecked():
            self.set_brush_stats_signal.emit(BRUSH_TYPE_RECT_BRUSH, size)

    @pyqtSlot('int', 'int', 'int', 'int', 'int', 'bool', 'bool')
    def on_paint_on_point(self, x, y, z, brush_type, brush_size, erase,
                          new_step):
        if x > 100000:  # bigger than this value means painting axis
            axis = 'x'
            x = self.focus_point[0]
        if y > 100000:
            axis = 'xy'
            y = self.focus_point[1]
        if z > 100000:
            axis = 'z'
            z = self.focus_point[2]
        label = 1
        self.model.anno_paint(x, y, z, axis, label, brush_type, brush_size,
                              erase, new_step)
        self.update_scenes('asc', raw=False)

    @pyqtSlot()
    def on_refresh_list_button_clicked(self):
        self.update_anno_targets_list()

    @pyqtSlot()
    def on_delete_target_button_clicked(self):
        selected_target = self.targetList.currentItem()
        row = self.targetList.currentRow()
        if selected_target is None:
            return
        target_id = selected_target.target_id
        try:
            self.model.delete_target(target_id)
            self.update_scenes('asc', raw=False)
            self.targetList.takeItem(row)
        except ChangeNotSavedError as e:
            QMessageBox.warning(self, 'Refresh before Delete!', e.__str__())
        pass

    @pyqtSlot()
    def menu_undo_paint_triggered(self):
        if self.model.undo_paint():
            self.update_scenes(raw=False)

    @pyqtSlot()
    def menu_redo_paint_triggered(self):
        if self.model.redo_paint():
            self.update_scenes(raw=False)

    @pyqtSlot()
    def menu_toggle_label_visibility(self):
        if self.label_opacity > 0:
            self.label_opacity = 0
        else:
            self.label_opacity = 50
示例#23
0
class Controller(object):
    
    def __init__(self):
        self.layout = Layout(Const.WORLD)
        Display.initGraphics(self.layout)
        self.model = Model(self.layout)
        self.carChanges = {}
        self.errorCounter = Counter()
        self.consecutiveLate = 0
        
        
    def learn(self, learner):
        self.isLearning = True
        self.learner = learner
        return self.run()
        
    def drive(self):
        self.isLearning = False
        return self.run()
        
    def run(self):
        self.render()
        self.userThread = UserThread(self.model.junior, self.model)
        self.userThread.start()
        self.iteration = 0
        while not self.isGameOver():
            self.resetTimes()
            startTime = time.time()
            self.printStats()
            
            self.otherCarUpdate()
            self.calculateError()
                        
            duration = time.time() - startTime
            timeToSleep = Const.SECONDS_PER_HEARTBEAT - duration
            # self.checkLate(timeToSleep)
            timeToSleep = max(0.01, timeToSleep)
            Display.graphicsSleep(timeToSleep)
            self.iteration += 1
        if not self.userThread.quit and not self.isLearning:
            self.outputGameResult()
        self.userThread.stop()
        Display.graphicsSleep(0.1)
        self.userThread.join()
        return self.userThread.quit
        
    def freezeFrame(self):
        while True:
            keys = Display.getKeys()
            if 'q' in keys: return
            Display.graphicsSleep(0.1)
        
    def outputGameResult(self):
        collided = self.userThread.hasCollided()
        for car in self.model.getCars():
            Display.drawCar(car)
        print '*********************************'
        print '* GAME OVER                     *'
        if collided:
            print '* CAR CRASH!!!!!'
        else:
            print '* You Win!'
        print '*********************************'    
        
            
    def isGameOver(self):
        if self.isLearning:
            keys = Display.getKeys()
            if 'q' in keys: 
                self.userThread.quit = True
                return True
            return self.iteration > Const.TRAIN_ITERATIONS
        if self.userThread.quit:
            return True
        if self.userThread.victory:
            return True
        return self.userThread.hasCollided()

    def round(self, num):
        return round(num * 1000) / 1000.0

    def checkLate(self, timeToSleep):
        secsLate = self.round(-timeToSleep)
        if secsLate > 0:
            self.consecutiveLate += 1
            if self.consecutiveLate < 3: return
            print '*****************************'
            print 'WARNING: Late to update (' + str(secsLate) + 's)'
            
            print 'Infer time: ' + str(self.round(self.inferTime))
            print 'Action time: ' + str(self.round(self.actionTime))
            print 'Update time: ' + str(self.round(self.updateTime))
            print 'Draw time: ' + str(self.round(self.drawTime))
            print '*****************************'
        else:
            self.consecutiveLate = 0

    def resetTimes(self):
        self.actionTime = 0
        self.inferTime = 0
        self.drawTime = 0
        self.updateTime = 0

    def printStats(self):
        if self.isLearning: return
        if self.iteration == 0: return
        if self.iteration % Const.REPORT_ITER != 0: return
        print '-------------'
        print 'iteration ' + str(self.iteration)
        error = self.errorCounter.getMean() * Const.BELIEF_TILE_SIZE
        print 'error: ' + str(error)
        print'--------------'
        print ''
        

    def juniorUpdate(self):
        junior = self.model.junior
        junior.action()
        self.move([junior])

    def otherCarUpdate(self):
        if True or Const.INFERENCE != 'none':
            self.infer()
        self.act()
        self.move(self.model.getOtherCars())
        
    def observe(self):
        if self.isLearning: return
        juniorX = self.model.junior.pos.x
        juniorY = self.model.junior.pos.y
        for car in self.model.getOtherCars():
            observation = car.getObservation(self.model.junior)
            obsDist = observation.getDist()
            inference = car.getInference()
            inference.observe(juniorX, juniorY, obsDist)
        
    def elapseTime(self):
        if self.isLearning: return
        if Const.CARS_PARKED: return
        for car in self.model.getOtherCars():
            inference = car.getInference()
            inference.elapseTime()
            
    def updateBeliefs(self):
        if self.isLearning: return
        beliefs = []
        for car in self.model.getOtherCars():
            belief = car.getInference().getBelief()
            color = car.getColor()
            Display.updateBelief(color, belief)
            beliefs.append(belief)
        self.model.setProbCar(beliefs)
        
    def infer(self):
        start = time.time()

        try:
            self.elapseTime()
            self.observe()
        except  Exception, e:
            print 'caught'
            traceback.print_exc()
            Display.raiseEndGraphics()
            Display.graphicsSleep(0.01)
            self.userThread.quit = True
           
            
        inferEnd = time.time()
        self.inferTime += inferEnd - start
        self.updateBeliefs()
        self.drawTime += time.time() - inferEnd
class Controller:

    def __init__(self):
        self.view = View()
        self.model = Model()
        self.cliente_iniciado = None
        
    def start(self):
        self.view.start()  
        self.menu_principal_login()

    def menu_principal_login(self): 
        option = None
        
        while option != '0':
            self.view.menu_principal_login()
            self.view.select_opcion()

            option = input()

            if option == '1':
                self.menu_registrarse()
            elif option == '2':
                self.menu_iniciar_sesion()             
            elif option == '0':
                self.view.end()
            else:
                self.view.opcion_invalid()
    """
    controlador 
    """    
    def menu_registrarse(self):
        self.view.ask('Nombre: ')
        nombre = input()
        self.view.ask('Apellido Paterno: ')
        apellido_p = input()
        self.view.ask('Apellido Materno: ')
        apellido_m = input()
        self.view.ask('Edad: ')
        edad = input()
        self.view.ask('Correo: ')
        correo = input()
        self.view.ask('Teléfono: ')
        tel = input()
        self.view.ask('Usuario: ')
        usuario = input()
        self.view.ask('Contraseña: ')
        contrasena = input()
        admin = 0

        registro = self.model.create_cliente(nombre,apellido_p,apellido_m,edad, correo,tel,usuario,contrasena,admin)

        if registro == True:

            self.view.success()
        else:
            self.view.error()

        
    def menu_iniciar_sesion(self):    
        self.view.ask('Nombre de usuario: ')
        usuario = input()
        self.view.ask('Contraseña: ')
        contrasena = input()

        cliente = self.model.read_login(usuario, contrasena)

        if type(cliente) == tuple:
            self.cliente_iniciado = cliente
            self.menu_principal_clientes()
        elif cliente ==  None:
            self.view.datos_incorrectos()
        else:
            self.view.error()


    """
    Controlador menu principal admin
    """

    def menu_principal(self): 
        option = None
        
        while option != '0':
            self.view.menu_principal()
            self.view.select_opcion()

            option = input()

            if option == '1':
                self.menu_cliente()
            elif option == '2':
                self.pelicula_menu()
            elif option == '3':
                self.funciones_menu()
            elif option == '4':
                self.salas_menu()
            elif option == '5':
                self.asientos_menu() 
            elif option == '6':
                self.boletos_menu()          
            elif option == '0':
                self.view.end()
            else:
                self.view.opcion_invalid() 
    """
    controlador clientes
    """
    def menu_cliente(self): 
        option = None
        
        while option != '0':
            self.view.menu_cliente()
            self.view.select_opcion()

            option = input()

            if option == '1':
                self.agregar_cliente()
            elif option == '2':
                self.read_cliente()
            elif option == '3':
                self.read_all_clientes()
            elif option == '4':
                self.update_cliente()     
            elif option == '5':
                self.delete_cliente()          
            elif option == '0':
                self.view.end()
            else:
                self.view.opcion_invalid() 

    def agregar_cliente(self):
        self.view.ask('Nombre:')
        nombre = input()
        self.view.ask('Apellido Paterno: ') 
        apellido_p = input()
        self.view.ask(' Apellido Materno: ')
        apellido_m = input()
        self.view.ask('Edad: ')
        edad = input()
        self.view.ask('Correo: ')
        correo = input()
        self.view.ask('Teléfono: ')
        tel = input()
        self.view.ask('Usuario: ')
        usuario = input()
        self.view.ask('Contraseña: ')
        contrasena = input()
        self.view.ask('Admin: ')
        admin = input()
        

        crear = self.model.create_cliente(nombre, apellido_p,apellido_m, edad,correo,tel,usuario,contrasena,admin)  
        if crear == True:

            self.view.success()
        else:
            self.view.error()

    def read_cliente(self):
        self.view.ask("ID Cliente: ")
        idcliente = input()

        cliente =  self.model.read_cliente(idcliente)

        if type(cliente) == tuple:
            self.view.mostrar_cliente(cliente)
        elif cliente ==  None:
            self.view.id_invalido()
        else:
            self.view.error()

    def read_all_clientes(self):
        clientes = self.model.read_all_clientes()

        if type(clientes) == list:
            self.view.mostrar_clientes(clientes)
        else:
            self.view.error()        

    def read_correo_cliente(self):
        self.view.ask("Correo: ")
        correo = input()

        cliente = self.model.leer_correo_clientes(correo)
        if type(cliente) == tuple:
            
            self.view.mostrar_clientes(cliente)
        elif cliente ==  None:
            self.view.id_invalido()        

        else:
            self.view.error()

    def update_cliente(self):
      
        self.view.mostrar_update()
        self.view.ask('ID:')
        idcliente = input()    
        self.view.ask('Nombre:')
        nombre = input()
        self.view.ask('Apellido Paterno: ') 
        apellido_p = input()
        self.view.ask(' Apellido Materno: ')
        apellido_m = input()
        self.view.ask('Edad: ')
        edad = input()
        self.view.ask('Correo: ')
        correo = input()
        self.view.ask('Teléfono: ')
        tel = input()
        self.view.ask('Usuario: ')
        usuario = input()
        self.view.ask('Contraseña: ')
        contrasena = input()
        self.view.ask('Admin: ')
        admin = input()
        

        result = self.model.update_cliente(idcliente, nombre,apellido_p, apellido_m,edad,correo,tel, usuario,contrasena,admin)
        
        if result == True:
            self.view.success()
        elif result == False: 
            self.view.id_invalido()   
        else:
            self.view.error() 

    def delete_cliente(self):
        self.view.ask("ID: ")
        idcliente = input()

        result = self.model.delete_cliente(idcliente)

        if result == True:
            self.view.success()
        elif  result == False:
            self.view.id_invalido()
        else:    
            self.view.error()
    """
    controlador peliculas
    """        

    def pelicula_menu(self): 
        option = None
        
        while option != '0':
            self.view.pelicula_menu()
            self.view.select_opcion()
            option = input()
            if option == '1':
                self.agregar_pelicula()
            elif option == '2':
                self.read_pelicula()
            elif option == '3':
                self.read_all_peliculas()
            elif option == '4':
                self.update_pelicula()
            elif option == '5':
                self.delete_peliculas()                  
            elif option == '0':
                self.view.end()
            else:
                self.view.opcion_invalid() 

    def agregar_pelicula(self):
        self.view.ask('Nombre:')
        nombre = input()
        self.view.ask('Duración: ') 
        duracion = input()
        self.view.ask('Sinopsis: ')
        sinopsis = input()
        self.view.ask('Clasificación: ')
        clasificacion= input()
        self.view.ask('Genero: ')
        generos_idgenero = input()
        
        crear = self.model.create_pelicula(nombre, duracion,sinopsis,clasificacion,generos_idgenero)  
        if crear == True:

            self.view.success()
        else:
            self.view.error()

    def read_pelicula(self):
        self.view.ask("ID pelicula: ")
        idpelicula = input()

        pelicula =  self.model.read_pelicula(idpelicula)

        if type(pelicula) == tuple:
            self.view.mostrar_pelicula(pelicula)
        elif pelicula ==  None:
            self.view.id_invalido()

    def read_all_peliculas(self):
        pelicula = self.model.read_all_peliculas()

        if type(pelicula) == list:
            self.view.mostrar_peliculas(pelicula)
        else:
            self.view.error()

    def update_pelicula(self):
      
        self.view.mostrar_update()
        self.view.ask('ID:')
        idpelicula = input()    
        self.view.ask('Nombre:')
        nombre = input()
        self.view.ask('Duración: ') 
        duracion = input()
        self.view.ask('sinopsis: ')
        sinopsis = input()
        self.view.ask('Clasificación: ')
        clasificacion= input()
        self.view.ask('Genero: ')
        generos_idgenero = input()
        
        result = self.model.update_pelicula(idpelicula, nombre,duracion, sinopsis,clasificacion,generos_idgenero)
        
        if result == True:
            self.view.success()
        elif result == False: 
            self.view.id_invalido()   
        else:
            self.view.error()

    def delete_peliculas(self):
        self.view.ask("ID: ")
        idpelicula = input()

        result = self.model.delete_pelicula(idpelicula)

        if result == True:
            self.view.success()
        elif  result == False:
            self.view.id_invalido()
        else:    
            self.view.error() 
    """
    controlador salas
    """        
    def salas_menu(self): 
        option = None
        
        while option != '0':
            self.view.salas_menu()
            self.view.select_opcion()
            option = input()
            if option == '1':
                self.agregar_sala()
            elif option == '2':
                self.read_sala()
            elif option == '3':
                self.read_all_salas()
            elif option == '4':
                self.update_sala()
            elif option == '5':
                self.delete_sala()                  
            elif option == '0':
                self.view.end()
            else:
                self.view.opcion_invalid()

    def agregar_sala(self):
        self.view.ask('Número de asientos:')
        num_asientos = input()
        self.view.ask('Número de sala: ') 
        numero_sala = input()
        self.view.ask('Tipo de sala: ')
        tipo_sala = input()
        
        crear = self.model.create_sala(num_asientos,numero_sala,tipo_sala)  
        if crear == True:

            self.view.success()
        else:
            self.view.error()

    def read_sala(self):
        self.view.ask("ID Sala: ")
        idsala = input()

        sala =  self.model.read_sala(idsala)

        if type(sala) == tuple:
            self.view.mostrar_sala(sala)
        elif sala ==  None:
            self.view.id_invalido()

    def read_all_salas(self):
        sala = self.model.read_all_salas()

        if type(sala) == list:
            self.view.mostrar_salas(sala)
        else:
            self.view.error() 

    def update_sala(self):
      
        self.view.mostrar_update()
        self.view.ask('ID:')
        idsala = input()    
        self.view.ask('Número de asientos :')
        num_asientos = input()
        self.view.ask('Número de sala: ') 
        numero_sala = input()
        self.view.ask('Tipo de sala: ')
        tipo_sala = input()
        
        result = self.model.update_sala(idsala,num_asientos,numero_sala,tipo_sala)
        
        if result == True:
            self.view.success()
        elif result == False: 
            self.view.id_invalido()   
        else:
            self.view.error() 

    def delete_sala(self):
        self.view.ask("ID: ")
        idsala = input()

        result = self.model.delete_sala(idsala)

        if result == True:
            self.view.success()
        elif  result == False:
            self.view.id_invalido()
        else:    
            self.view.error() 
    """
    controlador asientos
    """                                                 
    def asientos_menu(self): 
        option = None
        
        while option != '0':
            self.view.asientos_menu()
            self.view.select_opcion()
            option = input()
            if option == '1':
                self.agregar_asiento()
            elif option == '2':
                self.read_asiento()
            elif option == '3':
                self.read_all_asientos()
            elif option == '4':
                self.update_asiento()
            elif option == '5':
                self.delete_asiento()                  
            elif option == '0':
                self.view.end()
            else:
                self.view.opcion_invalid()

    def agregar_asiento(self):
        self.view.ask('Ingrese asiento: ')
        asiento = input()
        self.view.ask('Ingrese fila: ') 
        fila = input()
        self.view.ask('ID Sala: ')
        salas_idsala = input()
        
        crear = self.model.create_asiento(asiento,fila,salas_idsala)  
        if crear == True:

            self.view.success()
        else:
            self.view.error() 

    def read_asiento(self):
        self.view.ask("ID Asiento: ")
        idasiento = input()

        asiento =  self.model.read_asiento(idasiento)

        if type(asiento) == tuple:
            self.view.mostrar_asiento(asiento)
        elif asiento ==  None:
            self.view.id_invalido()

    def read_all_asientos(self):
        asiento = self.model.read_all_asientos()

        if type(asiento) == list:
            self.view.mostrar_asientos(asiento)
        else:
            self.view.error()

    def update_asiento(self):
      
        self.view.mostrar_update()
        self.view.ask('ID:')
        idasiento = input()    
        self.view.ask('Nombre asiento :')
        asiento = input()
        self.view.ask('Número fila: ') 
        fila = input()
        self.view.ask('ID Sala: ')
        salas_idsala = input()
        
        result = self.model.update_asientos(idasiento,asiento,fila,salas_idsala)
        
        if result == True:
            self.view.success()
        elif result == False: 
            self.view.id_invalido()   
        else:
            self.view.error()

    def delete_asiento(self):
        self.view.ask("ID: ")
        idasiento = input()

        result = self.model.delete_asiento(idasiento)

        if result == True:
            self.view.success()
        elif  result == False:
            self.view.id_invalido()
        else:    
            self.view.error() 
    """
    controlador funciones
    """                                                 
    def funciones_menu(self): 
        option = None
        
        while option != '0':
            self.view.funciones_menu()
            self.view.select_opcion()
            option = input()
            if option == '1':
                self.agregar_funcion()
            elif option == '2':
                self.read_funcion()
            elif option == '3':
                self.read_all_funciones()
            elif option == '4':
                self.update_funcion()
            elif option == '5':
                self.delete_fucion()                  
            elif option == '0':
                self.view.end()
            else:
                self.view.opcion_invalid()

    def agregar_funcion(self):
        self.view.ask('ID Pelicula: ')
        idpelicula = input()
        self.view.ask('Fecha: ') 
        fecha = input()
        self.view.ask('Hora: ')
        hora = input()
        self.view.ask('ID Sala: ')
        salas_idsala = input()
        self.view.ask('Precio: ')
        precio = input()
        
        crear = self.model.create_funcion(idpelicula,fecha,hora,salas_idsala,precio)  
        if crear == True:

            self.view.success()
        else:
            self.view.error() 

    def read_funcion(self):
        self.view.ask("ID Función: ")
        idfuncion = input()

        funcion =  self.model.read_funcion(idfuncion)

        if type(funcion) == tuple:
            self.view.mostrar_funcion(funcion)
        elif funcion ==  None:
            self.view.id_invalido()
        else:
            self.view.error()

    def read_all_funciones(self):
        funcion = self.model.read_all_funciones()

        if type(funcion) == list:
            self.view.mostrar_funciones(funcion)
        else:
            self.view.error()

    def update_funcion(self):
      
        self.view.ask('ID Función:')
        id_funciones = input()
        self.view.mostrar_update()
        self.view.ask('ID Pelicula:')
        idpelicula = input()    
        self.view.ask('Fecha :')
        fecha = input()
        self.view.ask('Hora: ') 
        hora = input()
        self.view.ask('ID Sala: ')
        salas_idsala = input()
        self.view.ask('Precio: ')
        precio = input()
        
        result = self.model.update_funcion(id_funciones,idpelicula,fecha,hora,salas_idsala,precio)

        print(result)
        
        if result == True:
            self.view.success()
        elif result == False: 
            self.view.id_invalido()   
        else:
            self.view.error()

    def delete_fucion(self):
        self.view.ask("ID: ")
        idfuncion = input()

        result = self.model.delete_funcion(idfuncion)

        if result == True:
            self.view.success()
        elif  result == False:
            self.view.id_invalido()
        else:    
            self.view.error()

    """
    controlador boletos admin
    """  
    def boletos_menu(self): 
        option = None
        
        while option != '0':
            self.view.boletos_menu()
            self.view.select_opcion()

            option = input()

            if option == '1':
                self.read_boleto()
            elif option == '2':
                self.read_all_boletos()
            elif option == '3':
                self.delete_boleto()              
            elif option == '0':
                self.view.end()
            else:
                self.view.opcion_invalid()   

    def read_boleto(self):
        self.view.ask("ID Boleto: ")
        idboleto = input()

        boleto =  self.model.read_boleto(idboleto)

        if type(boleto) == tuple:
            self.view.mostrar_boleto(boleto)
        elif boleto ==  None:
            self.view.id_invalido()
        else:
            self.view.error()

    def read_all_boletos(self):
        boleto = self.model.read_all_boletos()

        if type(boleto) == list:
            self.view.mostrar_boletos(boleto)
        else:
            self.view.error()

    def delete_boleto(self):
        self.view.ask("ID Boleto: ")
        boleto = input()

        result = self.model.delete_boleto(boleto)

        if result == True:
            self.view.success()
        elif  result == False:
            self.view.id_invalido()
        else:    
            self.view.error()        

    """
    Controlador clientes
    """         
    def menu_principal_clientes(self): 
        option = None
        
        while option != '0':
            self.view.menu_principal_clientes()
            self.view.select_opcion()

            option = input()

            if option == '1':
                self.read_all_peliculas()
            elif option == '2':
                self.read_all_funciones()
            elif option == '3':
                self.comprar_boletos()
            elif option == '4':
                self.comprar_boletos_por_pelicula()
            elif option == '5':
                self.ver_mis_boletos() 
            elif option == '6':
                self.menu_administrador()             
            elif option == '0':
                self.view.end()
            else:
                self.view.opcion_invalid() 

    def menu_administrador(self): 
        es_admin = self.cliente_iniciado[9]

        if es_admin:
            self.menu_principal()
        else:
            self.view.no_admin()

    def comprar_boletos(self):
        self.view.ask('Fecha (AAAA/MM/DD): ')
        fecha = input()

        if fecha == '':
            fecha = date.today().isoformat()

        funciones = self.model.read_all_funciones_por_fecha(fecha)

        self.view.mostrar_funciones(funciones)

        self.view.ask('ID Funciones: ')
        id_funciones = input()

        funcion = self.model.read_funcion(id_funciones)

        id_salas_asientos = funcion[4]
        clientes_idcliente = self.cliente_iniciado[0]

        asientos = self.model.read_all_asientos_por_sala(id_salas_asientos)
        asientos_ocupados_id = self.model.obtener_asientos_ocupados(id_funciones)

        asientos_disponibles = []

        for a in asientos:
            if a[0] not in asientos_ocupados_id:
                asientos_disponibles.append(a)

        self.view.mostrar_asientos(asientos_disponibles)
        
        self.view.ask('ID Asiento: ')
        asientos_idasiento = input()

        if int(asientos_idasiento) in asientos_ocupados_id:
            self.view.imprimir_asiento_ocupado()
            return
        
        crear = self.model.create_boleto(id_funciones,id_salas_asientos,clientes_idcliente,asientos_idasiento)  
        if crear == True:

            self.view.success()
        else:
            self.view.error() 
    
    def comprar_boletos_por_pelicula(self):
        self.read_all_peliculas()

        self.view.ask('ID pelicula: ')
        idpelicula = input()

        funciones = self.model.read_all_funciones_por_pelicula(idpelicula)

        self.view.mostrar_funciones(funciones)

        self.view.ask('ID Funciones: ')
        id_funciones = input()

        funcion = self.model.read_funcion(id_funciones)

        id_salas_asientos = funcion[4]
        clientes_idcliente = self.cliente_iniciado[0]

        asientos = self.model.read_all_asientos_por_sala(id_salas_asientos)
        asientos_ocupados_id = self.model.obtener_asientos_ocupados(id_funciones)

        asientos_disponibles = []

        for a in asientos:
            if a[0] not in asientos_ocupados_id:
                asientos_disponibles.append(a)

        self.view.mostrar_asientos(asientos_disponibles)
        
        self.view.ask('ID Asiento: ')
        asientos_idasiento = input()

        if int(asientos_idasiento) in asientos_ocupados_id:
            self.view.imprimir_asiento_ocupado()
            return
        
        crear = self.model.create_boleto(id_funciones,id_salas_asientos,clientes_idcliente,asientos_idasiento)  
        if crear == True:

            self.view.success()
        else:
            self.view.error() 

    def ver_mis_boletos(self):
        boletos = self.model.read_all_boletos()

        if type(boletos) == list:
            self.view.mostrar_boletos(boletos)
        else:
            self.view.error() 
示例#25
0
class Controller:
    #Contrusctor
    def __init__(self):
        self.model = Model()
        self.view = View()

    #Contacto controllers
    def agregar_contacto(self, id_contacto, nombre, tel, correo, dir):
        e, c = self.model.agregar_contacto(id_contacto, nombre, tel, correo,
                                           dir)
        if e:
            self.view.agregar_contacto(c)
        else:
            self.view.contacto_ya_existe(c)

    def leer_contacto(self, id_contacto):
        e, c = self.model.leer_contacto(id_contacto)
        if e:
            self.view.mostrar_contacto(c)
        else:
            self.view.contacto_no_existe(id_contacto)

    def leer_todos_contactos(self):
        c = self.model.leer_todos_contactos()
        self.view.mostrar_contactos(c)

    def actualizar_contacto(self,
                            id_contacto,
                            n_nombre='',
                            n_tel='',
                            n_correo='',
                            n_dir=''):
        e = self.model.actualizar_contacto(id_contacto, n_nombre, n_tel,
                                           n_correo, n_dir)
        if e:
            self.view.actualizar_contacto(id_contacto)
        else:
            self.view.contacto_no_existe(id_contacto)

    def borrar_contacto(self, id_contacto):
        e, c = self.model.borrar_contacto(id_contacto)
        if e:
            self.view.borrar_contacto(c)
        else:
            self.view.contacto_no_existe(id_contacto)

    def leer_contactos_letra(self, letra):
        c = self.model.contactos_letra(letra)
        self.view.mostrar_contactos(c)

    def agregar_cita(self, id_cita, id_contacto, lugar, fecha, hora, asunto):
        e, c = self.model.agregar_cita(id_cita, id_contacto, lugar, fecha,
                                       hora, asunto)
        if e:
            self.view.agregar_cita(c)
        else:
            self.view.cita_ya_existe(c)

    def leer_todas_citas(self):
        c = self.model.leer_todas_citas()
        self.view.mostrar_citas(c)

    def insertar_contactos(self):
        self.agregar_contacto(1, 'Juan Perez', '4641661118',
                              '*****@*****.**', 'Av siempre viva 113')
        self.agregar_contacto(2, 'Carlos Martinez', '6473350',
                              '*****@*****.**', 'Cerro Azul 201')
        self.agregar_contacto(3, 'Armando Navarro', '6473350',
                              '*****@*****.**',
                              'Piedras negras 234')
        self.agregar_contacto(4, 'Adriana Prieto', '64891111',
                              '*****@*****.**', 'Jalisto 032')

    def insertar_citas(self):
        self.agregar_cita(1, 1, 'Cerveceria Chapultepec', '26/01/2020',
                          '14:30', 'Tomar')
        self.agregar_cita(2, 1, 'MCarty´s', '10/09/2020', '14:30', 'Platicar')
        self.agregar_cita(3, 2, 'Casa de Levi', '26/05/20', '14:30',
                          'Tomar mas !')

    def leer_cita(self, id_cita):
        e, c = self.model.leer_cita(id_cita)
        if e:
            self.view.mostrar_cita(c)
        else:
            self.view.cita_no_existe(id_cita)

    def borrar_cita(self, id_cita):
        e, c = self.model.borrar_cita(id_cita)
        if e:
            self.view.borrar_cita(c)
        else:
            self.view.cita_no_existe(id_cita)

    def actualizar_cita(self,
                        id_cita,
                        n_id_contacto='',
                        n_lugar='',
                        n_fecha='',
                        n_hora='',
                        n_asunto=''):
        e = self.model.actualizar_cita(id_cita, n_id_contacto, n_lugar,
                                       n_fecha, n_hora, n_asunto)
        if e:
            self.view.actualizar_cita(id_cita)
        else:
            self.view.cita_no_existe(id_cita)

    def leer_citas_fecha(self, fecha):
        c = self.model.cita_fecha(fecha)
        self.view.mostrar_citas(c)

    def start(self):
        #Display a welcome mesagge
        self.view.start()
        #insert data in model
        self.insertar_contactos()
        self.insertar_citas()
        #show all contacts in DB
        self.leer_todos_contactos()
        self.leer_contactos_letra('a')
        self.leer_todas_citas()

    def menu(self):
        #Display menu
        self.view.menu()
        while True:
            o = input('Seleccion una opcion (1-13):  ')

            if o == '1':
                id_contacto = int(input('ID del contacto:'))
                nombre = input('Nombre: ')
                tel = input('Telefono: ')
                correo = input('Correo: ')
                dir = input('Direccion ')
                self.agregar_contacto(id_contacto, nombre, tel, correo, dir)
            if o == '2':
                self.leer_todos_contactos()
            if o == '3':
                id_contacto = int(input('ID del contacto:'))
                self.leer_contacto(id_contacto)
            if o == '4':
                id_contacto = int(input('ID del contacto:'))
                nombre = input('Nombre: ')
                tel = input('Telefono: ')
                correo = input('Correo: ')
                dir = input('Direccion ')
                self.actualizar_contacto(id_contacto, nombre, tel, correo, dir)
            if o == '5':
                g = input('Ingrese id de contacto:  ')
                self.borrar_contacto(g)
            if o == '6':
                g = input('Ingrese una letra:  ')
                print(g)
                self.leer_contactos_letra(g)
            if o == '7':
                id_cita = int(input('ID de la cita:'))
                id_contacto = int(input('ID del contacto:'))
                lugar = input('Lugar: ')
                fecha = input('Fecha: ')
                hora = input('Hora: ')
                asunto = input('Asunto ')
                self.agregar_cita(id_cita, id_contacto, lugar, fecha, hora,
                                  asunto)
            if o == '8':
                self.leer_todas_citas()
            if o == '9':
                g = input('Ingrese una letra:  ')
                self.leer_cita(g)
            if o == '10':
                id_cita = int(input('ID de la cita:'))
                id_contacto = int(input('ID del contacto:'))
                lugar = input('Lugar: ')
                fecha = input('Fecha: ')
                hora = input('Hora: ')
                asunto = input('Asunto ')
                self.actualizar_cita(id_cita, id_contacto, lugar, fecha, hora,
                                     asunto)
            if o == '11':
                self.borrar_cita(1)
            if o == '12':
                fecha = input('Ingrese la fecha (dd-mm-aaaa): ')
                self.leer_citas_fecha(fecha)
            elif o == '13':
                self.view.end()
                break
 def __init__(self):
     self.view = View()
     self.model = Model()
     self.cliente_iniciado = None
示例#27
0
            loss = loss_fn(predictions, targets, scaled_anchors)

        losses.append(loss.item())
        optimizer.zero_grad()
        scaler.scale(loss).backward()
        scaler.step(optimizer)
        scaler.update()

        # update progress bar
        mean_loss = sum(losses) / len(losses)
        loop.set_postfix(loss=mean_loss)


if __name__ == "__main__":
    model = Model(model_dict=load_yaml(config.MODEL_DICT),
                  in_channels=count_channles(config.LAYERS),
                  num_classes=config.NUM_CLASSES).to(config.DEVICE)
    optimizer = optim.Adam(model.parameters(),
                           lr=config.LEARNING_RATE,
                           weight_decay=config.WEIGHT_DECAY)
    loss_fn = LossFunction()
    scaler = torch.cuda.amp.GradScaler()

    dataset, loader = create_dataloader(config.IMG_DIR + "/train",
                                        config.LABEL_DIR + "/train",
                                        image_size=config.IMAGE_SIZE,
                                        batch_size=config.BATCH_SIZE,
                                        S=config.S,
                                        anchors=config.ANCHORS,
                                        transform=None,
                                        used_layers=config.LAYERS)
示例#28
0
def cloneModel(model):
    clone = Model(False, False, model.getParameters(), False)
    clone.resetLimit = model.resetLimit
    for bot in model.getBots():
        clone.createBot(bot.getType(), bot.getLearningAlg(), bot.parameters)
    return clone
示例#29
0
                        multi_scale=False,
                        use_flip=False)
test_data = VideoDataset(dataset_path=dataset_path,
                         split_data=split_data,
                         split='test',
                         multi_scale=False,
                         use_flip=False)

train_loader = DataLoader(train_data,
                          batch_size=16,
                          shuffle=True,
                          num_workers=4)
val_loader = DataLoader(val_data, batch_size=16, shuffle=True, num_workers=4)
test_loader = DataLoader(test_data, batch_size=16, shuffle=True, num_workers=4)

model = Model(7)
model = model.to(device)

n_epoch = 1000
lr = 0.0001
interval = 50

criterion = nn.CrossEntropyLoss(reduction='sum')
optimizer = optim.SGD(model.parameters(),
                      lr=lr,
                      momentum=0.9,
                      weight_decay=0.0005)
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer,
                                                 mode='min',
                                                 factor=0.2,
                                                 patience=2)
示例#30
0
def runTests(model, parameters):
    np.random.seed()

    print("Testing...")
    # Set Parameters:
    resetPellet = 15000
    resetGreedy = 30000
    resetVirus = 15000
    n_test_runs = 10
    trainedBot = model.getNNBot()
    trainedAlg = trainedBot.getLearningAlg()
    evaluations = []
    # Pellet testing:
    params = Params(0, False, parameters.EXPORT_POINT_AVERAGING)

    pelletModel = Model(False, False, params, False)
    pelletModel.createBot("NN", trainedAlg, parameters)
    pelletEvaluation = testModel(pelletModel, n_test_runs, resetPellet, model.getPath(), "pellet_collection")
    evaluations.append(pelletEvaluation)
    # Greedy Testing:
    if len(model.getBots()) > 1:
        greedyModel = Model(False, False, params, False)
        greedyModel.createBot("NN", trainedAlg, parameters)
        greedyModel.createBot("Greedy", None, parameters)
        greedyEvaluation = testModel(greedyModel, n_test_runs, resetGreedy, model.getPath(), "vs_1_greedy")
        evaluations.append(greedyEvaluation)
    # Virus Testing:
    if model.getVirusEnabled():
        params = Params(0, True, parameters.EXPORT_POINT_AVERAGING)
        virusModel = Model(False, False, params, False)
        virusModel.createBot("NN", trainedAlg, parameters)
        virusEvaluation = testModel(virusModel, n_test_runs, resetVirus, model.getPath(), "virus")
        evaluations.append(virusEvaluation)

    # TODO: add more test scenarios for multiple greedy bots and full model check
    print("Testing completed.")

    name_of_file = model.getPath() + "/final_results.txt"
    with open(name_of_file, "w") as file:
        data = "Avg run time(s): " + str(round(numpy.mean(model.timings), 6)) + "\n"
        data += "Number of runs per testing: " + str(n_test_runs) + "\n"
        for evaluation in evaluations:
            name = evaluation[0]
            maxScore = str(round(evaluation[1], 1))
            meanScore = str(round(evaluation[2], 1))
            stdMean = str(round(evaluation[3], 1))
            meanMaxScore = str(round(evaluation[4], 1))
            stdMax = str(round(evaluation[5], 1))
            data += name + " Highscore: " + maxScore + " Mean: " + meanScore + " StdMean: " + stdMean \
                    + " Mean_Max_Score: " + meanMaxScore + " Std_Max_Score: " + stdMax + "\n"
        file.write(data)
示例#31
0
# from phd import gmcphd
import gmcphd

# 仿真参数
N = 40  # 采样次数
M_number = 1  # 仿真次数
T_prun = 1e-5  # 合并阈值
U_merge = 5
J_max = 100  # 分量数
# ospa 参数
c_ospa = 100
p_ospa = 2

N_max = 20  # 存在目标最大数    cphd 的

model = Model()

# 生成真实数据
# target = target_form(F, N, G, q_noise)
target = target_data.target_form_nonoise(model.F, N, model.G, model.sigma_v)

# print(target[1][])

# 生成噪声数据
measuresdatas, nummeasures, numtruetargets = target_data.measures(
    model.H, model.sigma_r, target, N, model.P_D, model.lambda_c)

g = gmcphd.Gmcphd(model, N_max)
g.gmm.append(
    GmphdComponent(1, np.array([0, 2.6, 0, -1.2]), np.diag([1, 2, 1, 2])))
 def __init__(self, cfg):
     # Init superclass
     super().__init__()
     self.cfg = cfg
     self.hparams = cfg.training.hparams
     self.model = Model(**cfg.model.hparams)
示例#33
0
class Controller:
    """
    *******************************
    * A controller for a store DB *
    *******************************
    """
    def __init__(self):
        self.model = Model()
        self.view = View()

    def start(self):
        self.view.start()
        self.main_menu()

    """
    ***********************
    * General controllers *
    ***********************
    """

    def main_menu(self):
        o = '0'
        while o != '5':
            self.view.main_menu()
            self.view.option('5')
            o = input()
            if o == '1':
                self.zips_menu()
            elif o == '2':
                self.products_menu()
            elif o == '3':
                self.clients_menu()
            elif o == '4':
                self.orders_menu()
            elif o == '5':
                self.view.end()
            else:
                self.view.not_valid_option()
        return

    def update_lists(self, fs, vs):
        fields = []
        vals = []
        for f, v in zip(fs, vs):
            if v != '':
                fields.append(f + ' = %s')
                vals.append(v)
        return fields, vals

    """
    ********************
    * General for zips *
    ********************
    """

    def zips_menu(self):
        o = '0'
        while o != '7':
            self.view.zips_menu()
            self.view.option('7')
            o = input()
            if o == '1':
                self.create_zip()
            elif o == '2':
                self.read_a_zip()
            elif o == '3':
                self.read_all_zips()
            elif o == '4':
                self.read_zips_city()
            elif o == '5':
                self.update_zip()
            elif o == '6':
                self.delete_zip()
            elif o == '7':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_zip(self):
        self.view.ask('Ciudad: ')
        city = input()
        self.view.ask('Estado: ')
        state = input()
        return [city, state]

    def create_zip(self):
        self.view.ask('CP: ')
        i_zip = input()
        city, state = self.ask_zip()
        out = self.model.create_zip(i_zip, city, state)
        if out == True:
            self.view.ok(i_zip, 'agrego')
        else:
            if out.errno == 1062:
                self.view.error('El CP esta repetido')
            else:
                self.view.error('No se pudo agregar el CP')
        return

    def read_a_zip(self):
        self.view.ask('CP: ')
        i_zip = input()
        zip = self.model.read_a_zip(i_zip)
        if type(zip) == tuple:
            self.view.show_zip_header('Datos del CP  ' + i_zip + ' ')
            self.view.show_a_zip(zip)
            self.view.show_zip_midder()
            self.view.show_zip_footer()
        else:
            if zip == None:
                self.view.error('El CP no existe')
            else:
                self.view.error('Hay un problema al leer el CP')
        return

    def read_all_zips(self):
        zips = self.model.read_all_zips()
        if type(zips) == list:
            self.view.show_zip_header(' Todos los CPs ')
            for zip in zips:
                self.view.show_a_zip(zip)
            self.view.show_zip_midder()
            self.view.show_zip_footer()
        else:
            self.view.error('Hay un problema al leer los CPs ')

    def read_zips_city(self):
        self.view.ask('Ciudad: ')
        city = input()
        zips = self.model.read_zips_city(city)
        if type(zips) == list:
            self.view.show_zip_header('CP para la ciudad de  ' + city + ' ')
            for zip in zips:
                self.view.show_a_zip(zip)
            self.view.show_zip_midder()
            self.view.show_zip_footer()
        else:
            self.view.error('Hay un problema al leer los CPs ')
        return

    def update_zip(self):
        self.view.ask('CP a modificar: ')
        i_zip = input()
        zip = self.model.read_a_zip(i_zip)
        if type(zip) == tuple:
            self.view.show_zip_header(' Datos del CP ' + i_zip + ' ')
            self.view.show_a_zip(zip)
            self.view.show_zip_midder()
            self.view.show_zip_footer()
        else:
            if zip == None:
                self.view.error('El CP no existe')
            else:
                self.view.error('Hay un problema al leer el CP')
            return
        self.view.msg(
            ' Ingresa los valores a modificar (vacio para dejarlo igual): ')
        whole_vals = self.ask_zip()
        fields, vals = self.update_lists(['z_city', 'z_state'], whole_vals)
        vals.append(i_zip)
        vals = tuple(vals)
        out = self.model.update_zip(fields, vals)
        if out == True:
            self.view.ok(i_zip, 'actualizo')
        else:
            self.view.error('No se pudo actualizar el CP')
        return

    def delete_zip(self):
        self.view.ask('CP a borrar: ')
        i_zip = input()
        count = self.model.delete_zip(i_zip)
        if count != 0:
            self.view.ok(i_zip, 'borro')
        else:
            if count == 0:
                self.view.error('El CP no exite')
            else:
                self.view.error('Problema al borrar el CP')
        return

    """ 
    ***************************
    * Controllers for products*
    ***************************
    """

    def products_menu(self):
        o = '0'
        while o != '8':
            self.view.products_menu()
            self.view.option('8')
            o = input()
            if o == '1':
                self.create_product()
            elif o == '2':
                self.read_a_product()
            elif o == '3':
                self.read_all_products()
            elif o == '4':
                self.read_products_brand()
            elif o == '5':
                self.read_products_price_range()
            elif o == '6':
                self.update_product()
            elif o == '7':
                self.delete_product()
            elif o == '8':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_poduct(self):
        self.view.ask('Nombre: ')
        name = input()
        self.view.ask('Marca: ')
        brand = input()
        self.view.ask('Descripcion: ')
        descrip = input()
        self.view.ask('Precio: ')
        price = input()
        return [name, brand, descrip, price]

    def create_product(self):
        name, brand, descrip, price = self.ask_poduct()
        out = self.model.create_product(name, brand, descrip, price)
        if out == True:
            self.view.ok(name + ' ' + brand, 'agrego')
        else:
            self.view.error('No se pudo agregar el producto')
        return

    def read_a_product(self):
        self.view.ask('ID producto: ')
        id_producto = input()
        product = self.model.read_a_product(id_producto)
        if type(product) == tuple:
            self.view.show_product_header('Datos del producto  ' +
                                          id_producto + ' ')
            self.view.show_a_product(product)
            self.view.show_product_midder()
            self.view.show_product_footer()
        else:
            if product == None:
                self.view.error('El producto no existe')
            else:
                self.view.error('Hay un problema al leer el producto')
        return

    def read_all_products(self):
        products = self.model.read_all_products()
        if type(products) == list:
            self.view.show_product_header(' Todos los productos ')
            for product in products:
                self.view.show_a_product(product)
                self.view.show_product_midder()
            self.view.show_product_footer()
        else:
            self.view.error('Hay un problema al leer los productos ')

    def read_products_brand(self):
        self.view.ask('Marca: ')
        brand = input()
        products = self.model.read_products_brand(brand)
        if type(products) == list:
            self.view.show_product_header(' Productos de la marca ' + brand +
                                          ' ')
            for product in products:
                self.view.show_a_product(product)
                self.view.show_product_midder()
            self.view.show_product_footer()
        else:
            self.view.error('Problema al leer los prodcutos')
        return

    def read_products_price_range(self):
        self.view.ask('Precio inferior: ')
        price_ini = input()
        self.view.ask('Precio superior: ')
        price_end = input()
        products = self.model.read_products_price_range(
            float(price_ini), float(price_end))
        if type(products) == list:
            self.view.show_product_header(' Productos entre ' + price_ini +
                                          ' y ' + price_end + ' ')
            for product in products:
                self.view.show_a_product(product)
                self.view.show_product_midder()
            self.view.show_product_footer
        else:
            self.view.error('Problema al leer los productos')
        return

    def update_product(self):
        self.view.ask(' ID de producto a modificar: ')
        id_product = input()
        product = self.model.read_a_product(id_product)
        if type(product) == tuple:
            self.view.show_product_header(' Datos del produtco ' + id_product +
                                          ' ')
            self.view.show_a_product(product)
            self.view.show_product_midder
            self.view.show_product_footer()
        else:
            if product == None:
                self.view.error('El producto no existe')
            else:
                self.view.error('Problema al leer el producto')
            return
        self.view.msg(
            'Ingresa los valores a modificar ( vacio para dejarlo igual ):')
        whole_vals = self.ask_poduct()
        fields, vals = self.update_lists(
            ['p_name', 'p_brand', 'p_descrip', 'p_price'], whole_vals)
        vals.append(id_product)
        vals = tuple(vals)
        out = self.model.update_product(fields, vals)
        if out == True:
            self.view.ok(id_product, 'atualizo')
        else:
            self.view.error('No se pudo actualizar')
        return

    def delete_product(self):
        self.view.ask('ID de producto a borrar: ')
        id_product = input()
        count = self.model.delete_product(id_product)
        if count != 0:
            self.view.ok(id_product, 'Borro')
        else:
            if count == 0:
                self.view.error('El produco no exite')
            else:
                self.view.error('Prblema al borrar el producto')
        return

    """ 
    ***************************
    * Controllers for clients*
    ***************************
    """

    def clients_menu(self):
        o = '0'
        while o != '7':
            self.view.Clients_menu()
            self.view.option('7')
            o = input()
            if o == '1':
                self.create_client()
            elif o == '2':
                self.read_a_client()
            elif o == '3':
                self.read_all_clients()
            elif o == '4':
                self.read_client_zip()
            elif o == '5':
                self.update_client()
            elif o == '6':
                self.delete_client()
            elif o == '7':
                return
            else:
                self.view.not_valid_option()
        return

    def ask_client(self):
        self.view.ask('Nombre: ')
        name = input()
        self.view.ask('Apellido paterno: ')
        sname1 = input()
        self.view.ask('Apellido Materno: ')
        sname2 = input()
        self.view.ask('Calle: ')
        street = input()
        self.view.ask('No exterior: ')
        noext = input()
        self.view.ask('No interior: ')
        noint = input()
        self.view.ask('Colonia: ')
        col = input()
        self.view.ask('CP: ')
        zip = input()
        self.view.ask('Email: ')
        email = input()
        self.view.ask('telefono: ')
        phone = input()
        return (name, sname1, sname2, street, noext, noint, col, zip, email,
                phone)

    def create_client(self):
        name, sname1, sname2, street, noext, noint, col, zip, email, phone = self.ask_client(
        )
        out = self.model.create_client(name, sname1, sname2, street, noext,
                                       noint, col, zip, email, phone)
        if out == True:
            self.view.ok(name + ' ' + sname1 + ' ' + sname2, 'agrego')
        else:
            self.view.error('No se pudo agregar cliente')
        return

    def read_a_client(self):
        self.view.ask('ID cliente: ')
        id_client = input()
        client = self.model.read_a_client(id_client)
        if type(client) == tuple:
            self.view.show_client_header('Datos del cliente  ' + id_client +
                                         ' ')
            self.view.show_a_client(client)
            self.view.show_client_midder()
            self.view.show_client_footer()
        else:
            if client == None:
                self.view.error('El cliente no existe')
            else:
                self.view.error('Hay un problema al leer el cliente')
        return

    def read_all_clients(self):
        clients = self.model.read_all_clients()
        if type(clients) == list:
            self.view.show_client_header(' Todos los clientes ')
            for client in clients:
                self.view.show_a_client(client)
                self.view.show_zip_midder()
            self.view.show_zip_footer
        else:
            self.view.error('Problema al leer los clientes')
        return

    def read_client_zip(self):
        self.view.ask('CP: ')
        zip = input()
        clients = self.model.read_client_zip(zip)
        if type(clients) == list:
            self.view.show_client_header('Clientes con el cp ' + zip + ' ')
            for client in clients:
                self.view.show_a_client(client)
                self.view.show_client_midder()
            self.view.show_client_footer()
        else:
            self.view.error('Problema al leer los clientes')
        return

    def update_client(self):
        self.view.ask('ID de cliente a modificar: ')
        id_client = input()
        client = self.model.read_a_client(id_client)
        if type(client) == tuple:
            self.view.show_client_header(' Datos del cliente ' + id_client +
                                         ' ')
            self.view.show_a_client(client)
            self.view.show_client_midder()
            self.view.show_product_footer
        else:
            if client == None:
                self.view.error('El cliente no existe')
            else:
                self.view.error('Problema al leer el cliente')
        self.view.msg(
            'Ingresa los valores a modificar (vacio para dejarlo igual): ')
        whole_vals = self.ask_client()
        fields, vals = self.update_lists([
            'c_fname', 'c_sname1', 'c_sname2', 'c_noext', 'c_noint', 'c_col',
            'c_zip', 'c_email', 'c_phone'
        ], whole_vals)
        vals.append(id_client)
        vals = tuple(vals)
        out = self.model.update_client(fields, vals)
        if out == True:
            self.view.ok(id_client, 'actualizo')
        else:
            self.view.error('Error no se pudo actualizar el cliente')
        return

    def delete_client(self):
        self.view.ask('ID de cliente a borrar: ')
        id_client = input()
        count = self.model.delete_client(id_client)
        if count != 0:
            self.view.ok(id_client, 'Borro')
        else:
            if count == 0:
                self.view.error('El cliente no exite')
            else:
                self.view.error('Prblema al borrar el cliente')
        return

    """ 
    **************************
    * Controllers for orders *
    **************************
    """

    def orders_menu(self):
        o = '0'
        while o != '11':
            self.view.orders_menu()
            self.view.option('11')
            o = input()
            if o == '1':
                self.create_order()
            elif o == '2':
                self.read_a_order()
            elif o == '3':
                self.read_all_orders()
            elif o == '4':
                self.read_orders_date()
            elif o == '5':
                self.read_orders_client()
            elif o == '6':
                self.update_orders()
            elif o == '7':
                self.add_order_details()
            elif o == '8':
                self.update_order_details()
            elif o == '9':
                self.delete_order_details()
            elif o == '10':
                self.delete_order()
            elif o == '11':
                return
            else:
                self.view.not_valid_option()
        return

    def create_order(self):
        self.view.ask('ID cliente: ')
        id_client = input()
        o_status = 'PROCESSING'
        today = date.today()
        o_date = today.strftime('%y-%m-%d')
        o_total = 0.0
        id_order = self.model.create_order(id_client, o_status, o_date,
                                           o_total)
        if type(id_order) == int:
            id_product = ' '
            while id_product != '':
                self.view.msg(
                    '--- Agrega productos a la orden (deja vacio el id del producto para salir ---'
                )
                id_product, od_total = self.create_order_details(id_order)
                o_total += od_total
            self.model.update_order(('o_total = %s', ), (o_total, id_order))
        else:
            self.view.error('No se pudo crear la orden')
        return

    def read_a_order(self):
        self.view.ask('ID order: ')
        id_order = input()
        order = self.model.read_a_order(id_order)
        if type(order) == tuple:
            order_details = self.model.read_a_order_details(id_order)

            if type(order_details) != list and order_details != None:
                self.view.error('Problema al leer la orden')
            else:
                self.view.show_order_header('Datos de la orden ' + id_order +
                                            ' ')

                self.view.show_order(order)

                self.view.show_order_details_header()

                for order_detail in order_details:
                    self.view.show_a_order_details(order_detail)
                self.view.show_order_details_footer()
                self.view.show_order_total(order)
                self.view.show_order_footer()
                return order
        else:
            if order == None:
                self.view.error('La orden no existe')
            else:
                self.view.error('Problema al leer la orden')
        return

    def read_all_orders(self):
        orders = self.model.read_all_orders()
        if type(orders) == list:
            self.view.show_order_header(' Todas las ordenes ')
            for order in orders:
                id_order = order[0]
                order_details = self.model.read_a_order_details(id_order)
                if type(order_details) != list and order_details != None:
                    self.view.error('Problema al leer la orden ' + id_order +
                                    '. REVISA .')
                else:
                    self.view.show_order(order)
                    self.view.show_order_details_header()
                    for order_detail in order_details:
                        self.view.show_a_order_details(order_detail)
                    self.view.show_order_details_footer()
                    self.view.show_order_total(order)
                    self.view.show_order_midder()
            self.view.show_order_footer
        else:
            self.view.error('Problema al leer las ordenes')
        return

    def read_orders_date(self):
        self.view.ask('Fecha: ')
        date = input()
        orders = self.model.read_orders_date(date)
        if type(orders) == list:
            self.view.show_order_header(' Ordenes para la fecha ' + date + ' ')
            for order in orders:
                id_order = order[0]
                order_details = self.model.read_a_order_details(id_order)
                if type(order_details) != list and order_details != None:
                    self.view.error('Problema al leer la orden' + id_order +
                                    ' .Revisa. ')
                else:
                    self.view.show_order(order)
                    self.view.show_order_details_header()
                    for order_detail in order_details:
                        self.view.show_a_order_details(order_detail)
                    self.view.show_order_details_footer()
                    self.view.show_order_total(order)
                    self.view.show_order_midder()
        else:
            self.view.error('Problemas a leer las ordenes')
        return

    def read_orders_client(self):
        self.view.ask('ID cliente: ')
        id_client = input()
        orders = self.model.read_orders_client(id_client)
        if type(orders) == list:
            self.view.show_order_header(' Ordnes para el cliente ' +
                                        id_client + ' ')
            for order in orders:
                id_order = order[0]
                order_details = self.model.read_a_order_details(id_order)
                if type(order_details) != list and order_details != None:
                    self.view.error('Problema al leer la orden ' + id_order +
                                    ' .Revisa ')
                else:
                    self.view.show_order(order)
                    self.view.show_order_details_header()
                    for order_detail in order_details:
                        self.view.show_a_order_details(order_detail)
                    self.view.show_order_details_footer()
                    self.view.show_order_total(order)
                    self.view.show_order_midder
            self.view.show_order_footer()
        else:
            self.view.error('Problema al leer las ordenes')
        return

    def update_orders(self):
        self.view.ask('ID orden a modificar')
        id_orden = input()
        order = self.model.read_a_order(id_orden)
        if type(order) == tuple:
            self.view.show_order_header('Datos de la orden' + id_orden + ' ')
            self.view.show_order(order)
            self.view.show_order_total(order)
            self.view.show_order_footer()
        else:
            if id_orden == None:
                self.view.error('La orden no exite')
            else:
                self.view.error('Problema al leer la orden')
            return
        self.view.msg(
            'Ingresa los valores a modificar (vacio para dejarlo igual): ')
        self.view.ask('ID cliente: ')
        id_client = input()
        self.view.ask('Estado (processing,acepted, sent recived): ')
        o_status = input()
        self.view.ask('Fecha (yyyy/mm/dd): ')
        o_date = input()
        whole_vals = [id_client, o_status, o_date]
        fields, vals = self.update_lists(['id_client', 'o_status', 'o_date'],
                                         whole_vals)
        vals.append(id_orden)
        vals = tuple(vals)
        out = self.model.update_order(fields, vals)
        if out == True:
            self.view.ok(id_orden, ' se actualizo')
        else:
            self.view.error('No se pudo actualizar la orden')
        return

    def delete_order(self):
        self.view.ask('ID de orden a borrar: ')
        id_order = input()
        count = self.model.delete_order(id_order)
        if count != 0:
            self.view.ok(id_order, 'Borro')
        else:
            if count == 0:
                self.view.error('La orden no exite')
            else:
                self.view.error('Problema al borrar la orden')
        return

    """ 
    **********************************
    * Controllers for orders details *
    **********************************
    """

    def create_order_details(self, id_order):
        od_total = 0.0
        self.view.ask('ID producto: ')
        id_product = input()
        if id_product != '':
            product = self.model.read_a_product(id_product)
            if type(product) == tuple:
                self.view.show_product_header(' Datos del producto ' +
                                              id_product + ' ')
                self.view.show_a_product(product)
                self.view.show_product_footer()
                self.view.ask('Cantidad: ')
                od_amount = int(input())

                od_total = od_amount * product[4]
                out = self.model.create_order_details(id_order, id_product,
                                                      od_amount, od_total)
                if out == True:
                    self.view.ok(product[1] + ' ' + product[2],
                                 'agrego a la orden')
                else:
                    if out.errno == 1062:
                        self.view.error(' El producto ya esta en la orden')
                    else:
                        self.view.error('No se pudo agregar el producto')
                    od_total = 0.0
            else:
                if product == None:
                    self.view.error('El produdcto no existe')
                else:
                    self.view.error('Problema al leer el producto')
        return id_product, od_total

    def add_order_details(self):
        order = self.read_a_order()
        if type(order) == tuple:
            id_order = order[0]
            o_total = order[4]
            id_product = ' '
            while id_product != '':
                self.view.msg(
                    '--- Agrega productos a la orden (deja vacio el id del producto para salir) ---'
                )
                id_product, od_total = self.create_order_details(id_order)
                o_total += od_total
            self.model.update_order(('o_total = %s', ), (o_total, id_order))
        return

    def update_order_details(self):
        order = self.read_a_order()
        if type(order) == tuple:
            id_order = order[0]
            o_total = order[4]
            id_product = ' '
            while id_product != '':
                self.view.msg(
                    '--- Modifica productos de la orden (deja vacio el id del producto para salir) ---'
                )
                self.view.ask('ID producto: ')
                id_product = input()
                if id_product != '':
                    order_detail = self.model.read_a_order_detail(
                        id_order, id_product)
                    print(order_detail)
                    if type(order_detail) == tuple:
                        od_total_old = order_detail[5]
                        o_total -= od_total_old
                        product = self.model.read_a_product(id_product)
                        price = product[4]
                        self.view.ask('Cantidad: ')
                        od_amount = int(input())
                        od_total = price * od_amount
                        o_total += od_total
                        fields, whole_vals = self.update_lists(
                            ['od_amount', 'od_total'], [od_amount, od_total])
                        whole_vals.append(id_order)
                        whole_vals.append(id_product)
                        self.model.update_order_details(fields, whole_vals)
                        self.view.ok(id_product, 'actrualizo la orden')
                    else:
                        if order_detail == None:
                            self.view.error('El producto no existe')
                        else:
                            self.view.error(
                                'Problema al actualizar el producto :(')
            self.model.update_order(('o_total = %s', ), (o_total, id_order))
        return

    def delete_order_details(self):
        order = self.read_a_order()
        if type(order) == tuple:
            id_order = order[0]
            o_total = order[4]
            id_product = ' '
            while id_product != '':
                self.view.msg(
                    '--- Borrar productos de la orden (deja vacio el id del producto para salir) ---'
                )
                self.view.ask('ID producto: ')
                id_product = input()
                if id_product != '':
                    order_detail = self.model.read_a_order_detail(
                        id_order, id_product)
                    count = self.model.delete_order_detail(
                        id_order, id_product)
                    if type(order_detail) == tuple and count != 0:
                        od_total = order_detail[5]
                        o_total -= od_total
                        self.view.ok(id_product, 'borro la orden ')
                    else:
                        if order_detail == None:
                            self.view.error(
                                'El producto no existe en la orden')
                        else:
                            self.view.error('Problema al borrar el producto')
            self.model.update_order(('o_total = %s', ), (o_total, id_order))
        return
示例#34
0
	def on_message(self, request):
		personId = self.get_secure_cookie('sid')

		model = Model(request, personId)
		response = model.execute()
		clients.send(response)
示例#35
0
class TestModel(unittest.TestCase):
    def setUpClass():
        logging.basicConfig(level=logging.DEBUG)

    def setUp(self):
        self.logger = logging.getLogger()

        self.testFiles = []

        self.itemFile = Datafile('test.model.items.xml', self.id())
        self.itemFileAuctionOnly = Datafile('test.model.items.auction_only.xml', self.id())
        self.sessionFile = Datafile('test.model.session.xml', self.id())
        self.currencyFile = Datafile('test.model.currency.xml', self.id())
        self.importFileCsv = Datafile('test.model.import.csv', self.id())
        self.importFileTxt = Datafile('test.model.import.txt', self.id())

        self.dataset = Dataset(
                self.logger, './',
                self.sessionFile.getFilename(),
                self.itemFile.getFilename(),
                self.currencyFile.getFilename())
        self.dataset.restore()

        self.currency = Currency(
                self.logger,
                self.dataset,
                currencyCodes=['czk', 'eur'])
        self.model = Model(
                self.logger,
                self.dataset,
                self.currency)

    def tearDown(self):
        self.itemFile.clear()
        self.sessionFile.clear()
        self.currencyFile.clear()
        self.importFileCsv.clear()
        self.importFileTxt.clear()
        for file in self.testFiles:
            file.clear()

        del self.model
        del self.currency
        del self.dataset

    def restoreTestFile(self, filename):
        testFile = Datafile(filename, self.id())
        self.testFiles.append(testFile)
        return testFile
        
    def test_getItem(self):
        item = self.model.getItem('A2')
        self.assertDictContainsSubset({ItemField.CODE: 'A2'}, item)
        self.assertListEqual([Decimal('250'), Decimal('9.21')], [currency[CurrencyField.AMOUNT] for currency in item[ItemField.INITIAL_AMOUNT_IN_CURRENCY]])
        self.assertListEqual([Decimal('300'), Decimal('11.06')], [currency[CurrencyField.AMOUNT] for currency in item[ItemField.AMOUNT_IN_CURRENCY]])
        self.assertListEqual([], [currency[CurrencyField.AMOUNT] for currency in item[ItemField.AMOUNT_IN_AUCTION_IN_CURRENCY]])
    
    def test_addNewItem(self):
        sessionID = 11111

        # add (on show)
        self.assertEqual(
                self.model.addNewItem(sessionID, 23, 'Mysteria', 'Wolf', 'Pastel', None, None, None),
                Result.SUCCESS)
        addedItem = self.dataset.getItems('Owner=="23" and Title=="Mysteria" and Author=="Wolf"')[0]
        self.assertDictContainsSubset({
                        ItemField.STATE: ItemState.ON_SHOW,
                        ItemField.MEDIUM: 'Pastel',
                        ItemField.NOTE: None},
                addedItem);

        # duplicate add
        self.assertEqual(
                self.model.addNewItem(sessionID, 23, 'Mysteria', 'Wolf', None, None, None, None),
                Result.DUPLICATE_ITEM)

        # add (on sale) (amount/charity is converted but search expression assumes strings)
        self.assertEqual(
                self.model.addNewItem(sessionID, 35, 'Mysteria', 'Tiger', '', 123.5, 10, 'Good Stuff'),
                Result.SUCCESS)
        addedItem = self.dataset.getItems('Owner=="35" and Title=="Mysteria" and Author=="Tiger" and Charity=="10" and InitialAmount=="123.5"')[0]
        self.assertDictContainsSubset({
                        ItemField.INITIAL_AMOUNT: 123.5,
                        ItemField.CHARITY: 10,
                        ItemField.STATE: ItemState.ON_SALE,
                        ItemField.MEDIUM: None,
                        ItemField.NOTE: 'Good Stuff'},
                addedItem);

        # add (quotes)
        self.assertEqual(
                self.model.addNewItem(sessionID, 98, 'Quotted"Title', 'Qu"es', 'Photo', None, None, 'Do not touch.'),
                Result.SUCCESS)

        # add (empty parameters)
        self.assertEqual(
                self.model.addNewItem(sessionID, 99, 'Strong', 'Lemur', None, None, None, ''),
                Result.SUCCESS)
        addedItem = self.dataset.getItems('Owner=="99" and Title=="Strong" and Author=="Lemur"')[0]
        self.assertDictContainsSubset({
                        ItemField.MEDIUM: None,
                        ItemField.NOTE: None},
                addedItem);

        # add item from an import
        importNumber = 100
        self.assertEqual(
                self.model.addNewItem(sessionID, 99, 'Shy', 'Lemur', None, None, None, '', importNumber),
                Result.SUCCESS)
        addedItem = self.dataset.getItems('Owner=="99" and Title=="Shy" and Author=="Lemur"')[0]
        self.assertDictContainsSubset({
                        ItemField.CODE: str(importNumber),
                        ItemField.IMPORT_NUMBER: importNumber},
                addedItem);

        # add updated item (differs in amount/charity)
        self.assertEqual(
                self.model.addNewItem(sessionID, 99, 'Shy', 'Lemur', None, '12.5', 100, 'Some note', importNumber),
                Result.DUPLICATE_IMPORT_NUMBER)

        # add updated item (differs in name)
        self.assertEqual(
                self.model.addNewItem(sessionID, 99, 'Smiling', 'Lemur', None, None, None, 'Some note', importNumber),
                Result.DUPLICATE_IMPORT_NUMBER)

        # add item from an import with a and import number that matches an existing code
        importNumber = 3
        self.assertEqual(len(self.dataset.getItems('Code=="{0}"'.format(importNumber))), 0)
        self.assertEqual(
                self.model.addNewItem(sessionID, 99, 'Funny', 'Cat', None, None, None, '', importNumber),
                Result.SUCCESS_BUT_IMPORT_RENUMBERED)
        addedItem = self.dataset.getItems('Owner=="99" and Title=="Funny" and Author=="Cat"')[0]
        self.assertDictContainsSubset({
                        ItemField.IMPORT_NUMBER: importNumber},
                addedItem);

        # added list
        addedItemCodes = self.model.getAdded(sessionID)
        self.assertEqual(len(addedItemCodes), 6);


    def test_getAddedItems(self):
        sessionID = 11111

        # add items
        self.assertEqual(self.model.addNewItem(sessionID, 23, 'Mysteria', 'Wolf', 'Oil', None, None, None), Result.SUCCESS)
        self.assertEqual(self.model.addNewItem(sessionID, 35, 'Mysteria', 'Tiger', 'Pencil', '123', '10', None), Result.SUCCESS)

        # get added items
        addedItems = self.model.getAddedItems(sessionID)

        self.assertEqual(len(addedItems), 2);
        item = [item for item in addedItems if item[ItemField.OWNER] == 23][0]
        self.assertListEqual([], [currencyAmount[CurrencyField.AMOUNT] for currencyAmount in item[ItemField.INITIAL_AMOUNT_IN_CURRENCY]])
        item = [item for item in addedItems if item[ItemField.OWNER] == 35][0]
        self.assertListEqual(
                [Decimal('123'), Decimal('4.53')],
                [currencyAmount[CurrencyField.AMOUNT] for currencyAmount in item[ItemField.INITIAL_AMOUNT_IN_CURRENCY]])


    def test_updateItem(self):
        # update item
        self.assertEqual(
                self.model.updateItem(56,
                    owner=1, title='Wolf', author='Greenwolf', medium='Color Pencils', state=ItemState.ON_SALE, 
                    initialAmount='105', charity='50', amount=None, buyer=None, note=None),
                Result.SUCCESS)
        updatedItem = self.dataset.getItems('Owner=="1" and Title=="Wolf" and Author=="Greenwolf" and Medium=="Color Pencils"')[0]
        self.assertDictContainsSubset({
                        ItemField.STATE: ItemState.ON_SALE,
                        ItemField.INITIAL_AMOUNT: 105,
                        ItemField.CHARITY: 50,
                        ItemField.AMOUNT: None,
                        ItemField.NOTE: None},
                updatedItem);        
        self.assertIsNone(updatedItem[ItemField.AMOUNT]);
        self.assertIsNone(updatedItem[ItemField.BUYER]);

        # update item (range error of charity)
        self.assertEqual(
                self.model.updateItem(56,
                    owner=1, title='Wolf', author='Greenwolf', medium='Color Pencils', state=ItemState.FINISHED,
                    initialAmount='105', charity='150', amount='200', buyer='20', note=None),
                Result.INVALID_VALUE)

        # update item (consistency error)
        self.assertEqual(
                self.model.updateItem(56,
                    owner=1, title='Wolf', author='Greenwolf', medium='Color Pencils', state=ItemState.FINISHED,
                    initialAmount='105', charity='10', amount=None, buyer=None, note=None),
                Result.AMOUNT_NOT_DEFINED)

    def test_deleteItems(self):
        # 1. Delete item
        self.assertEqual(self.model.deleteItems(['A11', 'A2', 'A999']), 2)
        self.assertIsNone(self.model.getItem('A11'));
        self.assertIsNone(self.model.getItem('A2'));
        self.assertIsNone(self.model.getItem('A999'));

    def test_getItemNetAmount(self):
        item = self.model.getItem('A2')
        amountNet, amountCharity = self.model.getItemNetAmount(item)
        self.assertEqual(amountNet, Decimal('270'))
        self.assertEqual(amountCharity, Decimal('30'))
        
    def test_getPotentialCharityAmount(self):
        charityAmount = self.model.getPotentialCharityAmount()
        self.assertEqual(charityAmount, Decimal('299'))

    def test_getBadgeReconciliationSummary(self):
        # Owner that has no delivered item
        self.logger.info('Badge 1')
        summary = self.model.getBadgeReconciliationSummary(1)
        self.assertEqual(summary[SummaryField.GROSS_SALE_AMOUNT], Decimal('0'))
        self.assertEqual(summary[SummaryField.CHARITY_DEDUCTION], Decimal('0'))
        self.assertEqual(summary[SummaryField.BOUGHT_ITEMS_AMOUNT], Decimal('350'))
        self.assertEqual(summary[SummaryField.TOTAL_DUE_AMOUNT], Decimal('350'))
        self.assertEqual(len(summary[SummaryField.AVAILABLE_UNSOLD_ITEMS]), 2)
        self.assertEqual(len(summary[SummaryField.AVAILABLE_BOUGHT_ITEMS]), 2)
        self.assertEqual(len(summary[SummaryField.PENDING_SOLD_ITEMS]), 2)
        self.assertEqual(len(summary[SummaryField.DELIVERED_SOLD_ITEMS]), 0)

        # Owner that has just delivered items
        self.logger.info('Badge 2')
        summary = self.model.getBadgeReconciliationSummary(2)
        self.assertEqual(summary[SummaryField.GROSS_SALE_AMOUNT], Decimal('447'))
        self.assertEqual(summary[SummaryField.CHARITY_DEDUCTION], Decimal('49'))
        self.assertEqual(summary[SummaryField.BOUGHT_ITEMS_AMOUNT], Decimal('0'))
        self.assertEqual(summary[SummaryField.TOTAL_DUE_AMOUNT], Decimal('-398'))
        self.assertEqual(len(summary[SummaryField.AVAILABLE_UNSOLD_ITEMS]), 0)
        self.assertEqual(len(summary[SummaryField.AVAILABLE_BOUGHT_ITEMS]), 0)
        self.assertEqual(len(summary[SummaryField.PENDING_SOLD_ITEMS]), 3)
        self.assertEqual(len(summary[SummaryField.DELIVERED_SOLD_ITEMS]), 2)

        # Owner that has delivered items and bought items
        self.logger.info('Badge 4')
        summary = self.model.getBadgeReconciliationSummary(4)
        self.assertEqual(summary[SummaryField.GROSS_SALE_AMOUNT], Decimal('235'))
        self.assertEqual(summary[SummaryField.CHARITY_DEDUCTION], Decimal('36'))
        self.assertEqual(summary[SummaryField.BOUGHT_ITEMS_AMOUNT], Decimal('57'))
        self.assertEqual(summary[SummaryField.TOTAL_DUE_AMOUNT], Decimal('-142'))
        self.assertEqual(len(summary[SummaryField.AVAILABLE_UNSOLD_ITEMS]), 0)
        self.assertEqual(len(summary[SummaryField.AVAILABLE_BOUGHT_ITEMS]), 1)
        self.assertEqual(len(summary[SummaryField.PENDING_SOLD_ITEMS]), 0)
        self.assertEqual(len(summary[SummaryField.DELIVERED_SOLD_ITEMS]), 2)

        # Owner that has items either finished, not delivered, or unsold
        self.logger.info('Badge 6')
        summary = self.model.getBadgeReconciliationSummary(6)
        self.assertEqual(summary[SummaryField.GROSS_SALE_AMOUNT], Decimal('0'))
        self.assertEqual(summary[SummaryField.CHARITY_DEDUCTION], Decimal('0'))
        self.assertEqual(summary[SummaryField.BOUGHT_ITEMS_AMOUNT], Decimal('0'))
        self.assertEqual(summary[SummaryField.TOTAL_DUE_AMOUNT], Decimal('0'))
        self.assertEqual(len(summary[SummaryField.AVAILABLE_UNSOLD_ITEMS]), 1)
        self.assertEqual(len(summary[SummaryField.AVAILABLE_BOUGHT_ITEMS]), 0)
        self.assertEqual(len(summary[SummaryField.PENDING_SOLD_ITEMS]), 0)
        self.assertEqual(len(summary[SummaryField.DELIVERED_SOLD_ITEMS]), 0)

        # Buyer that has just bought items and some of the bought items are finished
        self.logger.info('Badge 11')
        summary = self.model.getBadgeReconciliationSummary(11)
        self.assertEqual(summary[SummaryField.GROSS_SALE_AMOUNT], Decimal('0'))
        self.assertEqual(summary[SummaryField.CHARITY_DEDUCTION], Decimal('0'))
        self.assertEqual(summary[SummaryField.BOUGHT_ITEMS_AMOUNT], Decimal('429'))
        self.assertEqual(summary[SummaryField.TOTAL_DUE_AMOUNT], Decimal('429'))
        self.assertEqual(len(summary[SummaryField.AVAILABLE_UNSOLD_ITEMS]), 0)
        self.assertEqual(len(summary[SummaryField.AVAILABLE_BOUGHT_ITEMS]), 3)
        self.assertEqual(len(summary[SummaryField.PENDING_SOLD_ITEMS]), 0)
        self.assertEqual(len(summary[SummaryField.DELIVERED_SOLD_ITEMS]), 0)

        # Buyer that has items either in auction or finished
        self.logger.info('Badge 12')
        summary = self.model.getBadgeReconciliationSummary(12)
        self.assertEqual(summary[SummaryField.GROSS_SALE_AMOUNT], Decimal('0'))
        self.assertEqual(summary[SummaryField.CHARITY_DEDUCTION], Decimal('0'))
        self.assertEqual(summary[SummaryField.BOUGHT_ITEMS_AMOUNT], Decimal('0'))
        self.assertEqual(summary[SummaryField.TOTAL_DUE_AMOUNT], Decimal('0'))
        self.assertEqual(len(summary[SummaryField.AVAILABLE_UNSOLD_ITEMS]), 0)
        self.assertEqual(len(summary[SummaryField.AVAILABLE_BOUGHT_ITEMS]), 0)
        self.assertEqual(len(summary[SummaryField.PENDING_SOLD_ITEMS]), 0)
        self.assertEqual(len(summary[SummaryField.DELIVERED_SOLD_ITEMS]), 0)

    def test_reconciliateBadge(self):
        # Badge 1 contains:
        # * sold item which has not been paid for (code: A2)
        # * self-sale of an item (code: 56)
        summaryBefore = self.model.getBadgeReconciliationSummary(1)
        self.assertTrue(self.model.reconciliateBadge(1))
        summaryAfter = self.model.getBadgeReconciliationSummary(1)
        self.assertEqual(summaryAfter[SummaryField.GROSS_SALE_AMOUNT], Decimal('200'))
        self.assertEqual(summaryAfter[SummaryField.CHARITY_DEDUCTION], Decimal('20'))
        self.assertEqual(summaryAfter[SummaryField.BOUGHT_ITEMS_AMOUNT], Decimal('0'))
        self.assertEqual(summaryAfter[SummaryField.TOTAL_DUE_AMOUNT], Decimal('-180'))
        self.assertListEqual(
            [],
            summaryAfter[SummaryField.AVAILABLE_UNSOLD_ITEMS])
        self.assertListEqual(
            [],
            summaryAfter[SummaryField.AVAILABLE_BOUGHT_ITEMS])
        self.assertListEqual(
            ['A2'],
            [item[ItemField.CODE] for item in summaryAfter[SummaryField.PENDING_SOLD_ITEMS]])
        self.assertListEqual(
            ['56'],
            [item[ItemField.CODE] for item in summaryAfter[SummaryField.DELIVERED_SOLD_ITEMS]])
    
        for itemUnsoldBefore in summaryBefore[SummaryField.AVAILABLE_UNSOLD_ITEMS]:
            self.assertEqual(
                    self.model.getItem(itemUnsoldBefore[ItemField.CODE])[ItemField.STATE],
                    ItemState.FINISHED,
                    'Item {0}'.format(itemUnsoldBefore[ItemField.CODE]))

        for itemBoughtBefore in summaryBefore[SummaryField.AVAILABLE_BOUGHT_ITEMS]:
            self.assertEqual(
                    self.model.getItem(itemBoughtBefore[ItemField.CODE])[ItemField.STATE],
                    ItemState.DELIVERED,
                    'Item {0}'.format(itemBoughtBefore[ItemField.CODE]))

        for itemDeliveredBefore in summaryBefore[SummaryField.DELIVERED_SOLD_ITEMS]:
            self.assertEqual(
                    self.model.getItem(itemDeliveredBefore[ItemField.CODE])[ItemField.STATE],
                    ItemState.FINISHED,
                    'Item {0}'.format(itemDeliveredBefore[ItemField.CODE]))


    def test_summaryChecksum(self):
        summaryA = self.model.getBadgeReconciliationSummary(1)
        summaryB = self.model.getBadgeReconciliationSummary(11)
        self.assertNotEqual(Summary.calculateChecksum(summaryA), Summary.calculateChecksum(summaryB))

    def test_getCashDrawerSummary(self):
        summary = self.model.getCashDrawerSummary()
        self.assertIsNotNone(summary)
        self.assertEqual(summary[DrawerSummaryField.TOTAL_GROSS_CASH_DRAWER_AMOUNT], Decimal('709'))
        self.assertEqual(summary[DrawerSummaryField.TOTAL_NET_CHARITY_AMOUNT], Decimal('112'))
        self.assertEqual(summary[DrawerSummaryField.TOTAL_NET_AVAILABLE_AMOUNT], Decimal('597'))
        self.assertListEqual(
                sorted([actorSummary.Badge for actorSummary in summary[DrawerSummaryField.BUYERS_TO_BE_CLEARED]]),
                [1, 3, 4, 11, 13])
        self.assertListEqual(
                sorted([actorSummary.Badge for actorSummary in summary[DrawerSummaryField.OWNERS_TO_BE_CLEARED]]),
                [1, 2, 3, 4, 6, 7])
        self.assertEqual(len(summary[DrawerSummaryField.PENDING_ITEMS]), 3)


    def test_importItemsFromCsv(self):
        # 1. Import
        sessionID = 11111
        binaryStream = io.open(self.importFileCsv.getFilename(), mode='rb')
        importedItems, importedChecksum = self.model.importCSVFile(sessionID, binaryStream)
        binaryStream.close()

        # 2. Verify
        self.assertEqual(len(importedItems), 13)
        self.assertEqual(importedItems[0][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[1][ImportedItemField.IMPORT_RESULT], Result.DUPLICATE_ITEM)
        self.assertEqual(importedItems[2][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[3][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[4][ImportedItemField.IMPORT_RESULT], Result.INVALID_CHARITY)
        self.assertEqual(importedItems[5][ImportedItemField.IMPORT_RESULT], Result.INCOMPLETE_SALE_INFO)
        self.assertEqual(importedItems[6][ImportedItemField.IMPORT_RESULT], Result.INVALID_AMOUNT)
        self.assertEqual(importedItems[7][ImportedItemField.IMPORT_RESULT], Result.INVALID_AUTHOR)
        self.assertEqual(importedItems[8][ImportedItemField.IMPORT_RESULT], Result.INVALID_TITLE)
        self.assertEqual(importedItems[9][ImportedItemField.IMPORT_RESULT], Result.DUPLICATE_ITEM)
        self.assertEqual(importedItems[10][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[11][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[12][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)

        # 3. Apply
        defaultOwner = 2
        result, skippedItems, renumberedItems = self.model.applyImport(sessionID, importedChecksum, defaultOwner)
        self.assertEqual(result, Result.SUCCESS)
        self.assertEqual(len(self.model.getAdded(sessionID)), 6)
        self.assertEqual(len(self.dataset.getItems(
                'Owner=="{0}" and Title=="Smooth \\\"Frog\\\"" and Author=="Greentiger" and State=="{1}" and InitialAmount=="120" and Charity=="47"'.format(
                        defaultOwner, ItemState.ON_SALE))), 1)
        self.assertEqual(len(self.dataset.getItems(
                'Owner=="{0}" and Title=="Draft Horse" and Author=="Greentiger" and State=="{1}" and InitialAmount=="500" and Charity=="0"'.format(
                        defaultOwner, ItemState.ON_SALE))), 1)
        self.assertEqual(len(self.dataset.getItems(
                'Owner=="{0}" and Title=="Žluťoučký kůň" and Author=="Greentiger" and State=="{1}"'.format(
                        defaultOwner, ItemState.ON_SHOW))), 1)
        self.assertEqual(len(self.dataset.getItems(
                'Owner=="{0}" and Title=="Eastern Dragon" and Author=="Redwolf" and State=="{1}"'.format(
                        defaultOwner, ItemState.SOLD))), 1)
        self.assertEqual(len(self.dataset.getItems(
                'Owner=="7" and Title=="More Wolves" and Author=="Greenfox" and State=="{0}" and InitialAmount=="280" and Charity=="50"'.format(
                        ItemState.ON_SALE))), 1)

        # 4. Re-apply
        result, skippedItems, renumberedItems = self.model.applyImport(sessionID, importedChecksum, defaultOwner)
        self.assertEqual(result, Result.NO_IMPORT)

        # 5. Re-apply with invalid checksum
        binaryStream = io.open(self.importFileCsv.getFilename(), mode='rb')
        importedItems, importedChecksum = self.model.importCSVFile(sessionID, binaryStream)
        binaryStream.close()
        result, skippedItems, renumberedItems = self.model.applyImport(sessionID, importedChecksum + 50, defaultOwner)
        self.assertEqual(result, Result.INVALID_CHECKSUM)

    def test_importItemsFromCsv_ImportNumberReuse(self):
        # Verify next code. This is crucial for the last test.
        NEXT_AVAILABLE_CODE = 57

        # 1. Import
        importFile = self.restoreTestFile('test.model.import_number.csv');
        sessionID = 11111
        binaryStream = io.open(importFile.getFilename(), mode='rb')
        importedItems, importedChecksum = self.model.importCSVFile(sessionID, binaryStream)
        binaryStream.close()

        # 2. Verify
        self.assertEqual(len(importedItems), 11)
        self.assertEqual(importedItems[0][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[1][ImportedItemField.IMPORT_RESULT], Result.DUPLICATE_ITEM)
        self.assertEqual(importedItems[2][ImportedItemField.IMPORT_RESULT], Result.DUPLICATE_ITEM)
        self.assertEqual(importedItems[3][ImportedItemField.IMPORT_RESULT], Result.DUPLICATE_ITEM)
        self.assertEqual(importedItems[4][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[5][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[6][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[7][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[8][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[9][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[10][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)

        # 3. Apply
        defaultOwner = 2
        result, skippedItems, renumberedItems = self.model.applyImport(sessionID, importedChecksum, defaultOwner)
        self.assertEqual(Result.SUCCESS, result)
        self.assertEqual(7, len(self.model.getAdded(sessionID)))

        # 3a. Check that if Import Number is missing, it will be left empty.
        self.assertDictContainsSubset(
                { ItemField.IMPORT_NUMBER: None },
                self.dataset.getItems('Owner=="7" and Author=="Redpanda" and Title=="Moon cycles"')[0])

        # 3b. Check that a duplicate Import Number in the import was not imported.
        self.assertEqual(
                0,
                len(self.dataset.getItems('Owner=="7" and Author=="Redpanda" and Title=="Fullmoon"')))
        self.assertEqual(
                0,
                len(self.dataset.getItems('Owner=="7" and Author=="Redpanda" and Title=="No moon"')))

        # 3c. Check that an existing item with a matching Import Number has not been updated
        # in case there were changes.
        self.assertEqual(
                1,
                len(self.dataset.getItems('Owner=="7" and Author=="Redpanda" and Title=="Half moon"')))
        updatedItem = self.dataset.getItems('Owner=="7" and Author=="Redpanda" and Title=="Half moon"')[0]
        self.assertIn(updatedItem[ItemField.CODE], self.model.getAdded(sessionID))

        # 3d. Check that an existing item with a matching Import Number has not been updated.
        nonupdatedItem = self.dataset.getItems('Owner=="7" and Author=="Greenfox" and Title=="White Snow"')[0]
        self.assertNotIn(nonupdatedItem[ItemField.CODE], self.model.getAdded(sessionID))

        # 3e. Check that item which import number might have been used earlier is renumbered.
        renumberedItem = self.dataset.getItems('Owner=="7" and Author=="Redpanda" and Title=="Day phases"')[0]
        self.assertNotEqual('45', renumberedItem[ItemField.CODE]);
        self.assertEqual(45, renumberedItem[ItemField.IMPORT_NUMBER]);

        # 3f. Check that Import Number is used case Code if the Code might not have been used previously.
        self.assertDictContainsSubset(
                { ItemField.CODE: '80', ItemField.IMPORT_NUMBER: 80 },
                self.dataset.getItems('Owner=="7" and Author=="Redpanda" and Title=="Morning"')[0])

        self.assertDictContainsSubset(
                { ItemField.CODE: '90', ItemField.IMPORT_NUMBER: 90 },
                self.dataset.getItems('Owner=="7" and Author=="Redpanda" and Title=="Afternoon"')[0])

        # 3g. Check that order of occurance in the import has no impact on ability to use Import Number as Code
        self.assertDictContainsSubset(
                { ItemField.CODE: '85', ItemField.IMPORT_NUMBER: 85 },
                self.dataset.getItems('Owner=="7" and Author=="Redpanda" and Title=="Noon"')[0])

        # 3f. Check that if Import Number might be used as Code at the start of the import, it will be used as Code.
        # No unnumbered or re-numbered item will prevent that.
        self.assertDictContainsSubset(
                { ItemField.CODE: str(NEXT_AVAILABLE_CODE), ItemField.IMPORT_NUMBER: NEXT_AVAILABLE_CODE },
                self.dataset.getItems('Owner=="7" and Author=="Redpanda" and Title=="Day"')[0])


    def test_importItemsFromText(self):
        textStream = io.open(self.importFileTxt.getFilename(), mode='rt', encoding='utf-8')
        text = '\n'.join(textStream.readlines())
        textStream.close()

        # 1. Import
        sessionID = 11111
        importedItems, importedChecksum = self.model.importText(sessionID, text)

        # 2. Verify
        self.assertEqual(len(importedItems), 10)
        self.assertEqual(importedItems[0][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[1][ImportedItemField.IMPORT_RESULT], Result.SUCCESS)
        self.assertEqual(importedItems[2][ImportedItemField.IMPORT_RESULT], Result.INVALID_CHARITY)
        self.assertEqual(importedItems[3][ImportedItemField.IMPORT_RESULT], Result.INCOMPLETE_SALE_INFO)
        self.assertEqual(importedItems[4][ImportedItemField.IMPORT_RESULT], Result.INVALID_AMOUNT)
        self.assertEqual(importedItems[5][ImportedItemField.IMPORT_RESULT], Result.INVALID_AUTHOR)
        self.assertEqual(importedItems[6][ImportedItemField.IMPORT_RESULT], Result.INVALID_TITLE)
        self.assertEqual(importedItems[7][ImportedItemField.IMPORT_RESULT], Result.DUPLICATE_ITEM)
        self.assertEqual(importedItems[8][ImportedItemField.IMPORT_RESULT], Result.DUPLICATE_ITEM)
        self.assertEqual(importedItems[9][ImportedItemField.IMPORT_RESULT], Result.DUPLICATE_ITEM)

        # 3. Apply
        owner = 2
        result, skippedItems, renumberedItems = self.model.applyImport(sessionID, importedChecksum, owner)
        self.assertEqual(result, Result.SUCCESS)
        self.assertEqual(len(self.model.getAdded(sessionID)), 2)
        self.assertEqual(len(self.dataset.getItems(
                'Owner=="{0}" and Title=="Smooth Frog" and Author=="Greentiger" and State=="{1}" and InitialAmount=="120" and Charity=="47"'.format(
                        owner, ItemState.ON_SALE))), 1)
        self.assertEqual(len(self.dataset.getItems(
                'Owner=="{0}" and Title=="Žluťoučký kůň" and Author=="Greentiger" and State=="{1}"'.format(
                        owner, ItemState.ON_SHOW))), 1)
        self.assertEqual(len(self.dataset.getItems(
                'Owner=="{0}" and Title=="Eastern Dragon" and Author=="Redwolf" and State=="{1}"'.format(
                        owner, ItemState.SOLD))), 1)

    def test_getNetAmount(self):
        # Regular amount
        grossAmount = 253
        saleAmount, charityAmount = self.model.getNetAmount(Decimal(grossAmount), 47)
        self.assertEqual((saleAmount, charityAmount), (134, 119))
        self.assertEqual(saleAmount + charityAmount, grossAmount)

        # Excessive amount
        self.assertEqual(self.model.getNetAmount(Decimal('1E+34'), 14), (0, 0))

        # Invalid amount
        self.assertEqual(self.model.getNetAmount(None, 23), (0, 0))

    def test_getSendItemToAuction(self):
        # Item of acceptable state (AUCT)
        item = self.model.sendItemToAuction('A10')
        self.assertIsNotNone(item)
        self.assertDictContainsSubset(
                {
                        ItemField.CODE:'A10',
                        ItemField.AMOUNT_IN_AUCTION:item[ItemField.AMOUNT]},
                self.model.getItemInAuction())
        self.model.clearAuction()
        self.assertIsNone(self.model.getItemInAuction())

        # Item of invalid state (SOLD)
        self.assertIsNone(self.model.sendItemToAuction('A13'))
        self.assertIsNone(self.model.getItemInAuction())

    def test_closeItemAsNotSold(self):
        # Close item
        self.assertEqual(Result.SUCCESS, self.model.closeItemAsNotSold('55'))
        item = self.model.getItem('55')
        self.assertDictContainsSubset(
                {
                        ItemField.STATE: ItemState.NOT_SOLD,
                        ItemField.BUYER: None,
                        ItemField.AMOUNT: None},
                item)

        # Close item which is not closable
        self.assertEqual(Result.ITEM_NOT_CLOSABLE, self.model.closeItemAsNotSold('A13'))

    def test_closeItemAsSold(self):
        # Close item
        self.assertEqual(Result.SUCCESS, self.model.closeItemAsSold('55', Decimal(1000), 9999))
        item = self.dataset.getItems('Buyer=="{0}"'.format(9999))[0]
        self.assertDictContainsSubset(
                {
                        ItemField.STATE: ItemState.SOLD,
                        ItemField.BUYER: 9999,
                        ItemField.AMOUNT: Decimal(1000)},
                item)

        # Close item which is not closable
        self.assertEqual(Result.ITEM_NOT_CLOSABLE, self.model.closeItemAsSold('A13', Decimal(1000), 9999))

    def test_closeItemIntoAuction(self):
        # Close item
        self.assertEqual(Result.SUCCESS, self.model.closeItemIntoAuction('55', Decimal(1000), 9999, None))
        item = self.dataset.getItems('Buyer=="{0}"'.format(9999))[0]
        self.assertDictContainsSubset(
                {
                        ItemField.STATE: ItemState.IN_AUCTION,
                        ItemField.BUYER: 9999,
                        ItemField.AMOUNT: Decimal(1000)},
                item)

        # Close item which is not closable
        self.assertEqual(Result.ITEM_NOT_CLOSABLE, self.model.closeItemIntoAuction('A13', Decimal(1000), 9999, None))

    def test_getAllItemsInAuction(self):
        auctionItems = self.model.getAllItemsInAuction()
        self.assertListEqual(
                ['A9', 'A10'],
                [item[ItemField.CODE] for item in auctionItems]);

    def test_getAllItemsInAuction_Ordering(self):
        datasetAuction = Dataset(
                self.logger, './',
                self.sessionFile.getFilename(),
                self.itemFileAuctionOnly.getFilename(),
                self.currencyFile.getFilename())
        datasetAuction.restore()
        modelAuction = Model(
                self.logger,
                datasetAuction,
                self.currency)

        auctionItems = modelAuction.getAllItemsInAuction()
        auctionItems.sort(key=lambda item: item[ItemField.AUCTION_SORT_CODE])

        for item in auctionItems:
            print('{0} - {1}'.format(item[ItemField.AUTHOR], item[ItemField.AMOUNT]))

        # Check that there is no block authors larger than two
        largestBlockSize = 0
        largestBlockAuthor = None
        blockAuthor = None
        blockSize = 0
        for item in auctionItems:
            if blockAuthor is not None and item[ItemField.AUTHOR] == blockAuthor:
                blockSize = blockSize + 1
            else:
                if blockSize > largestBlockSize:
                    largestBlockSize = blockSize
                    largestBlockAuthor = blockAuthor
                blockAuthor = item[ItemField.AUTHOR]
                blockSize = 1
        self.assertGreaterEqual(2, largestBlockSize, 'Author: ' + str(largestBlockAuthor))


    def test_generateDeviceCode(self):
        adminSessionID = self.model.startNewSession(UserGroups.ADMIN, '127.0.0.1')

        sessionID = self.model.startNewSession(UserGroups.UNKNOWN, '192.168.0.1')

        # If multiple numbers are generated per session, only the last one is valid
        deviceCode1 = self.model.generateDeviceCode(sessionID)
        self.assertIsNotNone(deviceCode1)
        deviceCode2 = self.model.generateDeviceCode(sessionID)
        self.assertIsNotNone(deviceCode2)
        self.assertEqual(Result.DISABLED_DEVICE_CODE, self.model.approveDeviceCode(adminSessionID, deviceCode1, UserGroups.SCAN_DEVICE))
        self.assertEqual(Result.SUCCESS, self.model.approveDeviceCode(adminSessionID, deviceCode2, UserGroups.SCAN_DEVICE))


    def test_getSessionUserGroup(self):
        adminSessionID = self.model.startNewSession(UserGroups.ADMIN, '127.0.0.1')

        sessionID = self.model.startNewSession(UserGroups.UNKNOWN, '192.168.0.1')
        self.assertIsNotNone(sessionID)

        # User group is defined in session
        self.assertEqual(UserGroups.ADMIN, self.model.getSessionUserGroup(adminSessionID))
        self.assertEqual(UserGroups.UNKNOWN, self.model.getSessionUserGroup(sessionID))

        # If a device code is approved, associated user group is used.
        deviceCode = self.model.generateDeviceCode(sessionID)
        self.assertEqual(Result.SUCCESS, self.model.approveDeviceCode(adminSessionID, deviceCode, UserGroups.SCAN_DEVICE))
        self.assertEqual(UserGroups.SCAN_DEVICE, self.model.getSessionUserGroup(sessionID))

        # If a device code is dropped, user group is UNKNOWN.
        self.model.dropDeviceCode(adminSessionID, deviceCode)
        self.assertEqual(UserGroups.UNKNOWN, self.model.getSessionUserGroup(sessionID))
示例#36
0
    opt.display_server = 'http://xxx.xx.xxx.xxx'  # IP
    opt.display_port = 1128
    opt.display_env = 'check'
    vis = Visualizer(server=opt.display_server,
                     port=opt.display_port,
                     env=opt.display_env)

    loss_meter = meter.AverageValueMeter()
    loss_file = os.path.join(experiment_dir, 'loss.txt')
    if os.path.exists(loss_file):
        os.remove(loss_file)
        print("Delete the obsolete loss files: %s!" % loss_file)

    data = loader_data(opt, TrainOrTest='train')
    model = Model(opt, DEVICE)
    model.initial()

    for epoch in range(opt.epoch):
        loss_meter.reset()
        for step, dataitem in enumerate(data):
            model.set_data(dataitem)
            model.optimize_parameters()

            return_dic = model.get_return()
            loss = return_dic['loss']

            # save and show loss
            loss_meter.add(loss.item())
            loss_str = 'mse_loss: %.3f' % loss.item()
            print_current_losses(txt_file=loss_file,
示例#37
0
 def setUp(self):
     self.volume = 1e-18
     self.model = Model()
     self.function_maker = FunctionMaker()
示例#38
0
文件: test.py 项目: Amiiirali/SC-CNN
class Test(object):
    def __init__(self, arg):

        # train on the GPU or on the CPU, if a GPU is not available
        self.device = torch.device(
            'cuda') if torch.cuda.is_available() else torch.device('cpu')
        self.logger = logging.getLogger('Testing')

        self.arg = arg
        self.root = os.path.dirname(os.path.realpath(__file__))
        self.d = arg.d
        self.version = arg.version
        self.num_workers = arg.num_workers
        self.batch_size = arg.batch_size
        self.heatmap_size = arg.heatmap_size
        self.patch_size = arg.patch_size
        self.test_dir = arg.test_dir

    def data_loader(self, file):

        self.logger.info(f'Loading Image <{file}> ...')
        dataset = TestDataset(self.root, self.arg, file)

        return dataset

    def detect_cell(self, file):

        dataset = self.data_loader(file)

        H, W = dataset.dimension()
        cell = np.zeros((H, W))
        count = np.zeros((H, W))

        [H_prime, W_prime] = self.heatmap_size

        for data in dataset:

            img, coords = data

            img = img.to(self.device)
            img = img.unsqueeze(0)

            point, h = self.SC_CNN.model(img)

            heat_map = utils.heat_map_tensor(point.view(-1, 2), h.view(-1, 1),
                                             self.device, self.d,
                                             self.heatmap_size)
            heatmap = heat_map.cpu().detach().numpy().reshape(
                (H_prime, W_prime))

            start_H, end_H, start_W, end_W = utils.find_out_center_coords(
                coords, self.patch_size, self.heatmap_size)

            cell[start_H:end_H, start_W:end_W] += heatmap

            idx = np.argwhere(heatmap != 0)
            count[idx[:, 0] + start_H, idx[:, 1] + start_W] += 1

        count[count == 0] = 1
        cell = np.divide(cell, count)

        return cell

    def load_model(self):

        self.SC_CNN = Model(self.arg, self.logger)
        self.SC_CNN.initialize()
        self.SC_CNN.load_()
        # Test mode
        self.SC_CNN.model.train(False)

    def run(self):

        self.load_model()

        utils.delete_file(self.test_dir, '.DS_Store')
        for file in os.listdir(self.test_dir):
            cell = self.detect_cell(file)
            cell = postprocess(cell, dist=8, thresh=0.3)
            self.logger.info(f'{len(cell)} cells are detected for <{file}>.')

            center_name = os.path.splitext(file)[0] + '.txt'
            path = f"{self.root}/{cfg.dataset_path}/Test/{cfg.center_path}/{center_name}"
            utils.save_cells(cell, path)
示例#39
0
from arch.Word2Vec import Word2Vec
from pipe.ConvertWordIds import convertWordIds
from pipe.DownSample import DownSample
from pipe.createInputTasks import createW2VInputTasks
from pipe.ContextWindows import contextWindow
from model.model import Model
from tools.word2vec import save
from tools.worddict import buildvocab

# set cbow=1 to use CBOW, Hierarchical Softmax is used by default if negative is not set (higher than 0)
if __name__ == "__main__":
    m = Model(alpha=0.05, vectorsize=100,
                 input="data/text8",
                 inputrange=None, # means all
                 build=[ buildvocab ],
                 pipeline=[ createW2VInputTasks, convertWordIds, DownSample, contextWindow, Word2Vec ],
                 mintf=5, cores=2, threads=3, windowsize=5, iterations=1, downsample=0.001,
                 cbow=1,
              )
    m.run()
    save("results/vectors.cbhs.bin", m, binary=True)

示例#40
0
class Controller:
    def __init__(self):
        #OxideData.set_default_oxides()   # Replace by function that sets data saved by user
        self.mod = Model()
        #self.cd = self.mod
        self.lprp = LpRecipeProblem("Glaze recipe", pulp.LpMaximize, self.mod)
        
        self.mw = MainWindow()
  
        for button, t in [(self.mw.unity_radio_button, 'umf_'), \
                          (self.mw.percent_wt_radio_button, 'mass_perc_'), \
                          (self.mw.percent_mol_radio_button, 'mole_perc_')]:
            button.config(command=partial(self.update_oxide_entry_type, t))

        self.mw.file_menu.add_command(label="Recipes", command=self.open_recipe_menu)
        self.mw.file_menu.add_command(label="Save", command=self.save_recipe)
        self.mw.file_menu.add_command(label="Save as new recipe", command=self.save_new_recipe)

        #self.mw.options_menu.add_command(label="Edit Oxides", command=None)
        self.mw.options_menu.add_command(label="Edit Ingredients", command=self.open_ingredient_editor)
        self.mw.options_menu.add_command(label="Edit Other Restrictions", command=self.open_other_restriction_editor)
        #self.mw.options_menu.add_command(label="Restriction Settings", command=self.open_ingredient_editor)
        
        self.mw.calc_button.config(command=self.calc_restr)
        
        # Create and grid ingredient selection buttons:
        for r, i in enumerate(self.mod.order["ingredients"]):
            self.mw.ingredient_select_button[i] = ttk.Button(self.mw.ingredient_vsf.interior, text=self.mod.ingredient_dict[i].name, \
                                                             width=20, command=partial(self.toggle_ingredient, i))
            self.mw.ingredient_select_button[i].grid(row=r)

        # Create and grid other selection buttons:
        for r, j in enumerate(self.mod.order["other"]):
            self.mw.other_select_button[j] = ttk.Button(self.mw.other_vsf.interior, text=prettify(self.mod.other_dict[j].name), \
                                                        width=20, command=partial(self.toggle_other, j))
            self.mw.other_select_button[j].grid(row=r+1)

        # Create DisplayRestriction dictionary
        self.display_restr_dict = {}      
        for key in self.mod.restr_keys():
            self.display_restr_dict[key] = DisplayRestriction(self.mw.restriction_sf.interior, self.mw.x_lab, self.mw.y_lab, \
                                                              key, self.mod.restr_dict[key].name, self.mod.restr_dict[key].default_low, self.mod.restr_dict[key].default_upp)

        # Open default recipe.
        self.open_recipe('0')

    def calc_restr(self):
        t0 = time.process_time()
        self.get_bounds()
        calculated_bounds = self.lprp.calc_restrictions(self.mod.current_recipe, self.mod.restr_dict)
        for key in self.mod.current_recipe.restriction_keys:
            res = self.display_restr_dict[key]
            dp =  self.mod.restr_dict[key].dec_pt
            for eps in ['lower', 'upper']:               # display calculated lower and upper bounds.
                res.calc_bounds[eps].config(text=('%.'+str(dp)+'f') % no_neg_zero(calculated_bounds[eps][key]))

        self.mw.proj_canvas.delete("all")
        var = self.mod.current_recipe.variables
        if len(var) == 2:
            vertices = self.lprp.calc_2d_projection(self.mod.current_recipe, self.mod.restr_dict)
            if self.mod.restr_dict[var['x']].normalization == self.mod.restr_dict[var['y']].normalization:
                scaling = 1
            else:
                x_pts = [p[0] for p in vertices]
                y_pts = [p[1] for p in vertices]
                delta_x = max(x_pts) - min(x_pts)
                delta_y = max(y_pts) - min(y_pts)
                if delta_y == 0 or delta_x == 0:
                    scaling = 1
                else:
                    scaling = delta_x / delta_y

            # Display 2-d projection of feasible region onto 'x'-'y' axes           
            self.mw.proj_canvas.create_polygon_plot(vertices, scaling)
        else:
            pass
        self.mw.root.lift()    # Doesn't work, and I don't know why
        #self.mw.root.attributes('-topmost', 1)
        #self.mw.root.attributes('-topmost', 0)
        try:
            self.ing_editor.toplevel.lower()
        except:
            pass
        t1 = time.process_time()
        #print(t1 - t0)

    def get_bounds(self):
        for key in self.mod.current_recipe.restriction_keys:
            self.mod.current_recipe.lower_bounds[key] = self.display_restr_dict[key].low.get()
            self.mod.current_recipe.upper_bounds[key] = self.display_restr_dict[key].upp.get()

    def open_recipe_menu(self):
        """Opens a pop-up window that lets users select which recipes bounds to display, or delete existing recipe bounds (except the default)"""
        try:
            self.mw.recipe_menu.recipe_selector.lift()
        except:
            self.mw.recipe_menu = RecipeMenu()
            for i in self.mod.recipe_dict:
                self.display_recipe(i) 
            self.mw.recipe_menu.r_s_scrollframe.interior.focus_force()

    def display_recipe(self, index):
        """Displays recipe name and delete button in recipe menu"""
        recipe = self.mod.recipe_dict[index]
        self.mw.recipe_menu.name_buttons[index] =  ttk.Button(master=self.mw.recipe_menu.r_s_scrollframe.interior, text=recipe.name, width=30,
                                 command=partial(self.open_recipe, index))
        self.mw.recipe_menu.name_buttons[index].grid(row=recipe.pos+1, column=0)
        if index != '0': 
            # Only allow deletion of user recipes.  Index '0' denotes the default recipe bounds
            self.mw.recipe_menu.delete_buttons[index] = ttk.Button(master=self.mw.recipe_menu.r_s_scrollframe.interior, text="X", width=5,
                                      command=partial(self.delete_recipe, index))
            self.mw.recipe_menu.delete_buttons[index].grid(row=recipe.pos+1, column=1)

    def open_recipe(self, index):   # To be used when opening a recipe, (or when ingredients have been updated?). Be careful.

        for t, res in self.mod.current_recipe.variables.items():
            self.display_restr_dict[res].deselect(t)            # Remove stars from old variables
            
        for res in self.display_restr_dict.values():
            res.remove(self.mod.current_recipe.variables)    # Clear the entries from previous recipes, if opening a new recipe

        self.mod.set_current_recipe(index)
                
        self.mw.recipe_name.set(self.mod.current_recipe.name)      # update the displayed recipe name

        r_k = self.mod.current_recipe.restriction_keys
        for i in r_k:
            try:
                self.display_restr_dict[i].low.set(self.mod.current_recipe.lower_bounds[i])
                self.display_restr_dict[i].upp.set(self.mod.current_recipe.upper_bounds[i])
            except:
                self.display_restr_dict[i].low.set(self.mod.restr_dict[i].default_low)    # this is just for the case where the oxides have changed
                self.display_restr_dict[i].upp.set(self.mod.restr_dict[i].default_upp)    # ditto

        for t, res in self.mod.current_recipe.variables.items():
            self.display_restr_dict[res].select(t)               # add stars to new variables
        
        et = self.mod.current_recipe.entry_type
        self.mw.entry_type.set(et)

        oxide_order = self.mod.order["oxides"]
        for ox in oxide_order:
            if ox in self.mod.current_recipe.oxides:
                self.display_restr_dict[et+ox].display(1 + oxide_order.index(ox))

        ingredient_order = self.mod.order["ingredients"]
        for i in ingredient_order:
            if i in self.mod.current_recipe.ingredients:
                self.mw.ingredient_select_button[i].state(['pressed'])
                self.display_restr_dict['ingredient_'+i].display(101 + ingredient_order.index(i))
            else:
                self.mw.ingredient_select_button[i].state(['!pressed'])

        other_order = self.mod.order["other"]
        for ot in other_order:
            if ot in self.mod.current_recipe.other:
                self.mw.other_select_button[ot].state(['pressed'])
                self.display_restr_dict['other_'+ot].display(1001 + other_order.index(ot))
            else:
                self.mw.other_select_button[ot].state(['!pressed'])
        
        # Set the command for x and y variable selection boxes
        for key, restr in self.display_restr_dict.items():
            restr.left_label.bind("<Button-1>", partial(self.update_var, key, 'x'))
            restr.right_label.bind("<Button-1>", partial(self.update_var, key, 'y'))

        try:
            self.mw.recipe_menu.recipe_selector.destroy()
        except:   # The recipe selector won't be open when the controller opens the default recipe on start-up
            pass  

    def save_recipe(self):
        """Save a recipe to the Model's recipe_dict, then update the JSON data file"""
        self.mod.current_recipe.name = self.mw.recipe_name.get()
        self.mod.current_recipe.entry_type = self.mw.entry_type.get()
        self.get_bounds()
        self.mod.current_recipe.update_bounds(self.mod.restr_dict)   # Do we need this?        
        self.mod.save_current_recipe()

    def save_new_recipe(self):
        """Save a new recipe with new ID to the self.mod.recipe_dict, then update the JSON data file"""
        self.get_bounds()
        self.mod.current_recipe.update_bounds(self.mod.restr_dict)   # Do we need this?
        self.mod.current_recipe.entry_type = self.mw.entry_type.get()
        self.mod.save_new_recipe()
        self.mw.recipe_name.set(self.mod.current_recipe.name)  # Sets the name to Recipe Bounds n, for a natural number n

    def delete_recipe(self, i):
        """Delete the recipe from the recipe_dict, then write out the updated recipe_dict to JSON file."""
        self.mod.delete_recipe(i)
        if i == self.mod.recipe_index:
            # We have deleted the current recipe.  Go to default recipe
            self.open_recipe('0')
        self.mw.recipe_menu.delete_recipe(i)

    def open_ingredient_editor(self):
        """Opens a window that lets users edit ingredients"""
        try:
            self.ing_editor.toplevel.lift() # lift the recipe selector, if it already exists
        except:
            print(self.mod.order['oxides'])
            self.ing_editor = IngredientEditor(self.mod, self.mod.order, self.reorder_ingredients)
            self.ing_editor.new_ingr_button.config(command=self.new_ingredient)
            self.ing_editor.update_button.config(command=self.update_ingredient_dict)
            for i in self.mod.order['ingredients']:
                self.ing_editor.display_ingredients[i].delete_button.config(command=partial(self.pre_delete_ingredient, i))

    def reorder_ingredients(self, y0, yr):
        """To be run when reordering the ingredients using dragmanager. This moves the ingredient in line y0
           to line yr, and shifts the ingredients between by one line up or down, as needed"""
        temp_list = self.mod.order["ingredients"]
        temp_list.insert(yr, temp_list.pop(y0))
        self.mod.json_write_order()

        #Regrid ingredients in ingredient editor, selection window and those that have been selected.
        for i, j in enumerate(temp_list):
            self.ing_editor.display_ingredients[j].display(i, self.mod.order)
            self.mw.ingredient_select_button[j].grid(row=i)
            if j in self.mod.current_recipe.ingredients:
                self.display_restr_dict['ingredient_'+j].display(101 + i)
            else:
                pass
            
    def new_ingredient(self):
        i, ing = self.mod.new_ingredient()    # i = index of new ingredient ing

        self.ing_editor.new_ingredient(i, self.mod, self.mod.order)
        # Moved next section to IngredientEditor
##        self.ing_editor.display_ingredients[i] = DisplayIngredient(i, self.mod, self.ing_editor.i_e_scrollframe.interior) 
##        self.ing_editor.display_ingredients[i].display(int(i), self.mod, self.mod.order)
##        self.ing_editor.ing_dnd.add_dragable(self.ing_editor.display_ingredients[i].name_entry)    # This lets you drag the row corresponding to an ingredient by right-clicking on its name   
        self.ing_editor.display_ingredients[i].delete_button.config(command=partial(self.pre_delete_ingredient, i))
        
        self.display_restr_dict['ingredient_'+i] = DisplayRestriction(self.mw.restriction_sf.interior, self.mw.x_lab, self.mw.y_lab,
                                                                          'ingredient_'+i, ing.name, 0, 100)
        # Set the command for x and y variable selection boxes
        display_restr = self.display_restr_dict['ingredient_'+i]
        display_restr.left_label.bind("<Button-1>", partial(self.update_var, 'ingredient_'+i, 'x'))
        display_restr.right_label.bind("<Button-1>", partial(self.update_var, 'ingredient_'+i, 'y'))

        self.mw.ingredient_select_button[i] = ttk.Button(self.mw.ingredient_vsf.interior, text=ing.name, width=20,
                                                     command=partial(self.toggle_ingredient, i))
        self.mw.ingredient_select_button[i].grid(row=int(i))

    ##    i_e_scrollframe.vscrollbar.set(100,0)  # Doesn't do anything
        self.ing_editor.i_e_scrollframe.canvas.yview_moveto(1)  # Supposed to move the scrollbar to the bottom, but misses the last row
   
        # TODO: Move next section to model
        self.lprp.lp_var['ingredient_'+i] = pulp.LpVariable('ingredient_'+i, 0, None, pulp.LpContinuous)
        self.lprp.constraints['ing_total'] = \
                                           self.lprp.lp_var['ingredient_total'] \
                                           == sum(self.lprp.lp_var['ingredient_'+j] for j in self.mod.ingredient_dict)
     
    def update_ingredient_dict(self):
        """"Run when updating ingredients (via ingredient editor)"""

        for i, ing in self.mod.ingredient_dict.items():
            # Maybe the restriction class should have an update_data method
            ing.name = self.ing_editor.display_ingredients[i].name_entry.get()                 # update ingredient name
            self.mw.ingredient_select_button[i].config(text=ing.name)
            self.display_restr_dict['ingredient_'+i].set_name(ing.name)
            self.mod.restr_dict['ingredient_'+i].name = ing.name
            for ox in self.mod.order['oxides']:
                try:
                    val = eval(self.ing_editor.display_ingredients[i].oxide_entry[ox].get()   )
                except:
                    val = 0
                if isinstance(val, Number) and val != 0:
                    ing.analysis[ox] = val
                else:
                    self.ing_editor.display_ingredients[i].oxide_entry[ox].delete(0, tk.END)
                    try:
                        del ing.analysis[ox]
                    except:
                        pass

            for j, attr in self.mod.other_attr_dict.items():
                try:
                    val = eval(self.ing_editor.display_ingredients[i].other_attr_entry[j].get())
                except:
                    val = 0
                if isinstance(val, Number) and val != 0:
                    ing.other_attributes[j] = val
                else:
                    self.ing_editor.display_ingredients[i].other_attr_entry[j].delete(0, tk.END)
                    try:
                        del ing.other_attributes[j]
                    except:
                        pass

            self.mod.ingredient_dict[i] = ing
            self.mod.ingredient_analyses[i] = ing.analysis
        self.mod.json_write_ingredients()
        self.mod.json_write_restrictions()
                
        self.lprp.update_ingredient_analyses() 
                
        old_oxides = copy.copy(self.mod.current_recipe.oxides)
        old_variables = copy.copy(self.mod.current_recipe.variables)
        # Reinsert stars next to ingredients that are variables:
        for t, res in old_variables.items():
            if res[0:10] == 'ingredient':
                self.display_restr_dict[res].select(t)

        self.mod.current_recipe.update_oxides(self.mod)   # Do this for all recipes?
        
        for ox in old_oxides - self.mod.current_recipe.oxides:
            for et in ['umf_', 'mass_perc_', 'mole_perc_']:
                self.display_restr_dict[et+ox].remove(old_variables)

        et = self.mw.entry_type.get()
        for ox in self.mod.current_recipe.oxides - old_oxides:
            self.display_restr_dict[et+ox].display(1 + self.mod.order['oxides'].index(ox))

    def pre_delete_ingredient(self, i):
        """Deletes ingredient if not in any recipes, otherwise opens dialogue window asking for confirmation."""
        recipe_dict = self.mod.recipe_dict
        ingredient_dict = self.mod.ingredient_dict
        recipes_affected = [j for j in recipe_dict if i in recipe_dict[j].ingredients]
        n = len(recipes_affected)
        if n > 0:
            self.confirmation_window = tk.Toplevel()
            question_frame = tk.Frame(self.confirmation_window)
            question_frame.grid()
            text1 = ingredient_dict[i].name+' occurs in '+recipe_dict[recipes_affected[0]].name
            text2 = 'Are you sure you want to delete '+ingredient_dict[i].name+'?'
            if n == 1:
                tk.Label(master=question_frame, text=text1+'.').grid(row=0)
                tk.Label(master=question_frame, text=text2).grid(row=1)
            elif n == 2:
                tk.Label(master=question_frame, text=text1+' and '+recipe_dict[recipes_affected[1]].name+'.').grid(row=0)
                tk.Label(master=question_frame, text=text2).grid(row=1)
            elif n == 3:
                tk.Label(master=question_frame, text=text1+', '+recipe_dict[recipes_affected[1]].name).grid(row=0)
                tk.Label(master=question_frame, text=' and 1 other recipe.').grid(row=1)
                tk.Label(master=question_frame, text=text2).grid(row=2)
            else:
                tk.Label(master=question_frame, text=text1+', '+recipe_dict[recipes_affected[1]].name).grid(row=0)
                tk.Label(master=question_frame, text=' and '+str(n-2)+' other recipes.').grid(row=1)
                tk.Label(master=question_frame, text=text2).grid(row=2)  
            answer_frame = tk.Frame(self.confirmation_window)
            answer_frame.grid()
            ttk.Button(answer_frame, text='Yes', width=10, command=partial(self.close_conf_window_and_delete_ing, i, recipes_affected)).grid(column=0, row=0)
            ttk.Button(answer_frame, text='No', width=10, command=lambda : self.confirmation_window.destroy()).grid(column=1, row=0)
        else:
            self.delete_ingredient(i, [])

    def close_conf_window_and_delete_ing(self, i, recipes_affected):
        self.delete_ingredient(i, recipes_affected)
        self.confirmation_window.destroy()

    def delete_ingredient(self, i, recipes_affected):

        #self.update_basic_constraints(ingredient_analyses, other_dict)   # I should probably update other_dict, no?

        if i in self.mod.current_recipe.ingredients:
            self.toggle_ingredient(i)   # gets rid of stars, if the ingredient is a variable

        self.mod.delete_ingredient(i, recipes_affected)

        self.lprp.remove_ingredient(i, self.mod)

        self.ing_editor.display_ingredients[i].delete()
        for k, j in enumerate(self.mod.order['ingredients']):
            self.ing_editor.display_ingredients[j].display(k, self.mod.order)    # We actually only need to do this for the rows that are below the one that was deleted

        # Remove the deleted ingredient from the list of ingredients to select from:
        self.mw.ingredient_select_button[i].destroy()
        del self.display_restr_dict['ingredient_'+i]

        
    def toggle_ingredient(self, i):
        """Adds/removes ingredient_dict[i] to/from the current recipe, depending on whether it isn't/is an ingredient already."""
        recipe = self.mod.current_recipe
        if i in recipe.ingredients:
            old_variables = copy.copy(recipe.variables)
            recipe.remove_ingredient(self.mod, i)
            self.mw.ingredient_select_button[i].state(['!pressed'])
            self.display_restr_dict['ingredient_'+i].remove(old_variables)
            # Remove the restrictions on the oxides no longer present:
            for ox in set(self.mod.ingredient_analyses[i]) - recipe.oxides:
                for et in ['umf_', 'mass_perc_', 'mole_perc_']:
                    self.display_restr_dict[et+ox].remove(old_variables)

        else:
            recipe.add_ingredient(self.mod, i)
            self.mw.ingredient_select_button[i].state(['pressed'])
            self.display_restr_dict['ingredient_'+i].display(101 + self.mod.order["ingredients"].index(i))
            et = self.mw.entry_type.get()
            for ox in recipe.oxides:
                self.display_restr_dict[et+ox].display(1 + self.mod.order['oxides'].index(ox))

    def open_other_restriction_editor(self):
        """Opens a window that lets users edit other restrictions"""
        try:
            self.other_restr_editor.toplevel.lift() # lift the recipe selector, if it already exists
        except:
            self.other_restr_editor = OtherRestrictionEditor(self.mod, self.mod.order, self.reorder_other_restrictions)
            self.other_restr_editor.new_other_restr_button.config(command=self.new_other_restriction)
            self.other_restr_editor.update_button.config(command=self.update_other_restriction_dict)
            for i in self.mod.order['other']:
                self.other_restr_editor.display_other_restrictions[i].delete_button.config(command=partial(self.pre_delete_other_restriction, i))

    def reorder_other_restrictions(self, y0, yr):
        """To be run when reordering the ingredients using dragmanager. This moves the ingredient in line y0
           to line yr, and shifts the ingredients between by one line up or down, as needed"""
        temp_list = self.mod.order["other"]
        temp_list.insert(yr, temp_list.pop(y0))
        self.mod.json_write_order()

        #Regrid restrictions in other restriction editor, selection window and those that have been selected.
        for i, j in enumerate(temp_list):
            self.other_restr_editor.display_other_restrictions[j].display(i, self.mod.order)
            self.mw.other_select_button[j].grid(row=i)
            if j in self.mod.current_recipe.other:
                self.display_restr_dict['other_'+j].display(1001 + i)
            else:
                pass
            
    def new_other_restriction(self):
        i, ot = self.mod.new_other_restriction()    # i = index of new restriction ot

        self.other_restr_editor.new_other_restriction(i, self.mod, self.mod.order)
        self.other_restr_editor.display_other_restrictions[i].delete_button.config(command=partial(self.pre_delete_other_restriction, i))
        
        self.display_restr_dict['other_'+i] = DisplayRestriction(self.mw.restriction_sf.interior, self.mw.x_lab, self.mw.y_lab,
                                                                          'other_'+i, ot.name, 0, 100)
        # Set the command for x and y variable selection boxes
        display_restr = self.display_restr_dict['other_'+i]
        display_restr.left_label.bind("<Button-1>", partial(self.update_var, 'other_'+i, 'x'))
        display_restr.right_label.bind("<Button-1>", partial(self.update_var, 'other_'+i, 'y'))

        self.mw.other_select_button[i] = ttk.Button(self.mw.other_vsf.interior, text=ot.name, width=20,
                                                     command=partial(self.toggle_other, i))
        self.mw.other_select_button[i].grid(row=int(i)+1)

    ##    i_e_scrollframe.vscrollbar.set(100,0)  # Doesn't do anything
        self.other_restr_editor.i_e_scrollframe.canvas.yview_moveto(1)  # Supposed to move the scrollbar to the bottom, but misses the last row
   
        # TODO: Move next section to model
        self.lprp.lp_var['other_'+i] = pulp.LpVariable('other_'+i, 0, None, pulp.LpContinuous)
        # TODO relate the other variable to the standard variables
     
    def update_other_restriction_dict(self):
        """"Run when updating other restrictions (via other restriction editor)"""
        for i in self.mod.other_dict:
            disp_other = self.other_restr_editor.display_other_restrictions[i]
            ot = Other(disp_other.name_entry.get(),
                       ast.literal_eval(disp_other.numerator_coefs_entry.get()),  # Converts the string into a dictionary
                       ast.literal_eval(disp_other.normalization_entry.get()),
                       disp_other.def_low_entry.get(),
                       disp_other.def_upp_entry.get(),
                       disp_other.dec_pt_entry.get())
            self.mod.other_dict[i] = ot
            self.mod.restr_dict['other_'+i].name = ot.name
            self.mod.restr_dict['other_'+i].normalization = ot.normalization
            self.mod.restr_dict['other_'+i].default_low = ot.def_low
            self.mod.restr_dict['other_'+i].default_upp = ot.def_upp
            self.mod.restr_dict['other_'+i].dec_pt = ot.dec_pt
            
            self.mw.other_select_button[i].config(text=prettify(ot.name))
            self.display_restr_dict['other_'+i].set_name(prettify(ot.name))
            self.display_restr_dict['other_'+i].set_default_low(ot.def_low)
            self.display_restr_dict['other_'+i].set_default_upp(ot.def_upp)
            
        old_variables = copy.copy(self.mod.current_recipe.variables)
        # Reinsert stars next to other restrictions that are variables:
        for t, res in old_variables.items():
            if res[0:5] == 'other':
                self.display_restr_dict[res].select(t)
            
        self.mod.json_write_other()
        self.mod.json_write_restrictions()
                
        self.lprp.update_other_restrictions()

    def pre_delete_other_restriction(self, i):
        """Deletes restriction if not in any recipes, otherwise opens dialogue window asking for confirmation."""
        recipe_dict = self.mod.recipe_dict
        other_dict = self.mod.other_dict
        recipes_affected = [j for j in recipe_dict if i in recipe_dict[j].other]
        n = len(recipes_affected)
        if n > 0:
            self.confirmation_window = tk.Toplevel()
            question_frame = tk.Frame(self.confirmation_window)
            question_frame.grid()
            text1 = other_dict[i].name+' occurs in '+recipe_dict[recipes_affected[0]].name
            text2 = 'Are you sure you want to delete '+other_dict[i].name+'?'
            if n == 1:
                tk.Label(master=question_frame, text=text1+'.').grid(row=0)
                tk.Label(master=question_frame, text=text2).grid(row=1)
            elif n == 2:
                tk.Label(master=question_frame, text=text1+' and '+recipe_dict[recipes_affected[1]].name+'.').grid(row=0)
                tk.Label(master=question_frame, text=text2).grid(row=1)
            elif n == 3:
                tk.Label(master=question_frame, text=text1+', '+recipe_dict[recipes_affected[1]].name).grid(row=0)
                tk.Label(master=question_frame, text=' and 1 other recipe.').grid(row=1)
                tk.Label(master=question_frame, text=text2).grid(row=2)
            else:
                tk.Label(master=question_frame, text=text1+', '+recipe_dict[recipes_affected[1]].name).grid(row=0)
                tk.Label(master=question_frame, text=' and '+str(n-2)+' other recipes.').grid(row=1)
                tk.Label(master=question_frame, text=text2).grid(row=2)  
            answer_frame = tk.Frame(self.confirmation_window)
            answer_frame.grid()
            ttk.Button(answer_frame, text='Yes', width=10, command=partial(self.close_conf_window_and_delete_other_restr, i, recipes_affected)).grid(column=0, row=0)
            ttk.Button(answer_frame, text='No', width=10, command=lambda : self.confirmation_window.destroy()).grid(column=1, row=0)
        else:
            self.delete_other_restriction(i, [])

    def close_conf_window_and_delete_other_restr(self, i, recipes_affected):
        self.delete_other_restriction(i, recipes_affected)
        self.confirmation_window.destroy()

    def delete_other_restriction(self, i, recipes_affected):
        """Incomplete"""
        if i in self.mod.current_recipe.other:
            self.toggle_other(i)   # gets rid of stars, if the ingredient is a variable

        self.mod.delete_other_restriction(i, recipes_affected)

        self.lprp.remove_other_restriction(i, self.mod)

        self.other_restr_editor.display_other_restrictions[i].delete()
        for k, j in enumerate(self.mod.order['other']):
            self.other_restr_editor.display_other_restrictions[j].display(k, self.mod.order)    # We actually only need to do this for the rows that are below the one that was deleted
            
        # Remove the deleted restriction from the list of other restrictions to select from:
        self.mw.other_select_button[i].destroy()
        del self.display_restr_dict['other_'+i]


    def toggle_other(self, i):
        """Adds/removes other_dict[index] to/from the current recipe, depending on whether it isn't/is an other restriction already."""
        recipe = self.mod.current_recipe
        if i in recipe.other:
            old_variables = copy.copy(recipe.variables)            
            recipe.remove_other_restriction(self.mod, i)
            self.mw.other_select_button[i].state(['!pressed'])
            self.display_restr_dict['other_'+i].remove(old_variables)
        else:
            recipe.add_other(self.mod, i)
            self.mw.other_select_button[i].state(['pressed'])         
            self.display_restr_dict['other_'+i].display(1001 + self.mod.order['other'].index(i))
            self.mw.restriction_sf.canvas.yview_moveto(1)

    def update_var(self, key, t, mystery_variable):     # t should be either 'x' or 'y'. Might be a better way of doing this
        restr = self.display_restr_dict[key]
        if t in self.mod.current_recipe.variables:
            v = self.mod.current_recipe.variables[t]
            if v == key:
                del self.mod.current_recipe.variables[t]
                self.display_restr_dict[key].deselect(t)
            else:
                self.mod.current_recipe.variables[t] = restr.index
                self.display_restr_dict[v].deselect(t)
                self.display_restr_dict[key].select(t)      
        else:
            self.mod.current_recipe.variables[t] = restr.index
            restr.select(t)

    def update_oxide_entry_type(self, entry_type):
        self.mod.current_recipe.set('entry_type', entry_type)
        for et in ['umf_', 'mass_perc_', 'mole_perc_']:
            if et == entry_type:
                for ox in self.mod.current_recipe.oxides:
                    self.display_restr_dict[et+ox].display(1 + self.mod.order['oxides'].index(ox))
            else:
                for ox in self.mod.current_recipe.oxides:
                    self.display_restr_dict[et+ox].hide()
示例#41
0
def run():
    # This is used in case we want to use a freezing program to create an .exe
    #if getattr(sys, 'frozen', False):
    #    os.chdir(sys._MEIPASS)

    guiEnabled = int(input("Enable GUI?: (1 == yes)\n"))
    guiEnabled = (guiEnabled == 1)
    viewEnabled = False
    if guiEnabled:
        viewEnabled = int(input("Display view?: (1 == yes)\n"))
        viewEnabled = (viewEnabled == 1)

    modelName = None
    modelPath = None
    loadedModelName = None
    algorithm = None
    packageName = None
    parameters = None
    model_in_subfolder = False
    loadModel = int(input("Do you want to load a model? (1 == yes)\n"))
    loadModel = (loadModel == 1)
    if loadModel:
        while packageName is None:
            packageName = None
            print("#########################################")
            print("Saved Models: \n")
            for folder in [i for i in os.listdir("savedModels/")]:
                print(folder)
            modelName = input("Enter the model name (name of directory in savedModels): (Empty string == break)\n")
            # If user presses enter, quit model loading
            if str(modelName) == "":
                loadModel = False
                modelName = None
                break
            # If user inputs wrong model name, ask for input again
            modelPath = "savedModels/" + modelName + "/"
            if not os.path.exists(modelPath):
                print("Invalid model name, no model found under ", modelPath)
                continue
            # CHECK FOR SUBFOLDERS
            if str(modelName)[0] != "$":
                while packageName is None:
                    print("------------------------------------")
                    print("Folder Submodels: \n")
                    for folder in [i for i in os.listdir(modelPath) if os.path.isdir(modelPath + "/" + i)]:
                        print(folder)
                    subModelName = input("Enter the submodel name: (Empty string == break)\n")
                    # If user presses enter, leave model
                    if str(subModelName) == "":
                        break
                    subPath = modelPath + subModelName + "/"
                    if not os.path.exists(subPath):
                        print("Invalid model name, no model found under ", subPath)
                        continue
                    packageName = "savedModels." + modelName + "." + subModelName
                    loadedModelName = subPath
                    # modelName = path
                    model_in_subfolder = True
                if packageName is None:
                    continue

            if packageName is None:
                packageName = "savedModels." + modelName
                loadedModelName = modelPath
                # ModelName = None will autogenereate a name
                modelName = None
        if packageName is not None:
            parameters = importlib.import_module('.networkParameters', package=packageName)
            algorithm = algorithmNameToNumber(parameters.ALGORITHM)
            # model.setPath(modelName)

    if not loadModel:
        parameters = importlib.import_module('.networkParameters', package="model")

        algorithm = int(input("What learning algorithm do you want to use?\n" + \
                              "'Q-Learning' == 0, 'Actor-Critic' == 2,\n"))
    tweaking = int(input("Do you want to tweak parameters? (1 == yes)\n"))
    tweakedTotal = []
    if tweaking == 1:
        while True:
            tweakedParameter = str(input("Enter name of parameter to be tweaked:\n"))
            paramLineNumber = checkValidParameter(tweakedParameter)
            if paramLineNumber is not None:
                paramValue = str(input("Enter parameter value:\n"))
                tweakedTotal.append([tweakedParameter, paramValue, paramLineNumber])
            if 1 != int(input("Tweak another parameter? (1 == yes)\n")):
                break
        modelPath = "savedModels/" + nameSavedModelFolder(tweakedTotal)
        model_in_subfolder = True

    if int(input("Give saveModel folder a custom name? (1 == yes)\n")) == 1:
        modelPath = "savedModels/" + str(input("Input folder name:\n"))


    model = Model(guiEnabled, viewEnabled, parameters, True)
    if parameters.JOB_TRAINING_STEPS != 0 and parameters.JOB_STEP_START > 0:
        model.loadModel(loadedModelName)
        print("Loaded into load path: " + model.getPath())

    else:
        model.initModelFolder(modelPath, loadedModelName, model_in_subfolder)
        print("Created new path: " + model.getPath())

    if tweakedTotal:
        modifyParameterValue(tweakedTotal, model)

    numberOfHumans = 0
    mouseEnabled = True
    humanTraining = False
    if guiEnabled and viewEnabled:
        numberOfHumans = int(input("Please enter the number of human players: (" + str(MAXHUMANPLAYERS) + " max)\n"))
        if fitsLimitations(numberOfHumans, MAXHUMANPLAYERS):
            createHumans(numberOfHumans, model)
            if 2 >= numberOfHumans > 0:
                humanTraining = int(input("Do you want to train the network using human input? (1 == yes)\n"))
                mouseEnabled = not humanTraining
            if numberOfHumans > 0 and not humanTraining:
                mouseEnabled = int(input("Do you want control Player1 using the mouse? (1 == yes)\n"))


    enableTrainMode = humanTraining if humanTraining is not None else False
    if not humanTraining:
        enableTrainMode = int(input("Do you want to train the network?: (1 == yes)\n"))
    model.setTrainingEnabled(enableTrainMode == 1)

    parameters = importlib.import_module('.networkParameters', package=model.getPath().replace("/", ".")[:-1])
    numberOfNNBots = parameters.NUM_NN_BOTS
    numberOfGreedyBots = parameters.NUM_GREEDY_BOTS
    numberOfBots = numberOfNNBots + numberOfGreedyBots

    Bot.init_exp_replayer(parameters, loadedModelName)

    setSeedAccordingToFolderNumber(model_in_subfolder, loadModel, modelPath, enableTrainMode)

    createBots(numberOfNNBots, model, "NN", parameters, algorithm, loadModel)
    createBots(numberOfGreedyBots, model, "Greedy", parameters)
    createBots(parameters.NUM_RANDOM_BOTS, model, "Random", parameters)
    model.addDataFilesToDictionary()

    if guiEnabled and viewEnabled and not model.hasHuman():
        spectate = int(input("Do want to spectate an individual bot's FoV? (1 = yes)\n"))
        if spectate == 1:
            model.addPlayerSpectator()

    if numberOfNNBots == 0:
        model.setTrainingEnabled(False)

    if numberOfBots == 0 and not viewEnabled:
        modelMustHavePlayers()

    model.initialize(loadModel)

    screenWidth, screenHeight = defineScreenSize(numberOfHumans)

    testResults = None
    if guiEnabled:
        view = View(model, screenWidth, screenHeight, parameters)
        controller = Controller(model, viewEnabled, view, mouseEnabled)
        view.draw()
        while controller.running:
            controller.process_input()
            model.update()
    else:
        maxSteps = parameters.MAX_SIMULATION_STEPS
        jobSteps = maxSteps if parameters.JOB_SIMULATION_STEPS == 0 else parameters.JOB_SIMULATION_STEPS
        jobStart = parameters.JOB_STEP_START
        smallPart = max(int(maxSteps / 100), 1) # constitutes one percent of total training time
        testPercentage = smallPart * 5
        if jobStart == 0:
            testResults = []
        else:
            print("max:", maxSteps, "start:", jobStart, "steps:", jobSteps)
            with open(model.getPath() + 'testResults.pkl', 'rb') as inputFile:
                testResults = pkl.load(inputFile)
        for step in range(jobStart, jobStart + jobSteps):
            model.update()
            if step % smallPart == 0 and step != 0:
                print("Trained: ", round(step / maxSteps * 100, 1), "%")
                # Test every 5% of training
            if parameters.ENABLE_TESTING:
                if step % testPercentage == 0:
                    testResults = updateTestResults(testResults, model, round(step / maxSteps * 100, 1), parameters)

        jobStart_line = checkValidParameter("JOB_STEP_START")
        epsilon_line = checkValidParameter("EPSILON")
        endParams = []
        endParams.append(["JOB_STEP_START", jobStart + jobSteps, jobStart_line])
        endParams.append(["EPSILON", model.getBots()[0].getLearningAlg().getNoise(), epsilon_line])
        modifyParameterValue(endParams, model)

        if parameters.ENABLE_TESTING and parameters.JOB_TRAINING_STEPS == 0 or \
                parameters.JOB_SIMULATION_STEPS + parameters.JOB_STEP_START >= parameters.MAX_SIMULATION_STEPS:
            testResults = updateTestResults(testResults, model, 100, parameters)
            meanMassesOfTestResults = [val[0] for val in testResults]
            exportTestResults(meanMassesOfTestResults, model.getPath() + "data/", "testMassOverTime")
            meanMassesOfPelletResults = [val[2] for val in testResults]
            exportTestResults(meanMassesOfPelletResults, model.getPath() + "data/", "Pellet_CollectionMassOverTime")
            plotTesting(testResults, model.getPath(), testPercentage, maxSteps, "Test", 0)
            plotTesting(testResults, model.getPath(), testPercentage, maxSteps, "Pellet_Collection", 2)
            
            if parameters.MULTIPLE_BOTS_PRESENT:
                meanMassesOfGreedyResults = [val[4] for val in testResults]
                exportTestResults(meanMassesOfGreedyResults, model.getPath() + "data/", "VS_1_GreedyMassOverTime")
                plotTesting(testResults, model.getPath(), testPercentage, maxSteps, "Vs_Greedy", 4)
            if parameters.VIRUS_SPAWN:
                meanMassesOfPelletVirusResults = [val[6] for val in testResults]
                exportTestResults(meanMassesOfPelletVirusResults, model.getPath() + "data/", "Pellet_Collection_Virus_MassOverTime")
                plotTesting(testResults, model.getPath(), testPercentage, maxSteps, "Pellet_Collection_with_Viruses", 6)
                if parameters.MULTIPLE_BOTS_PRESENT:
                    meanMassesOfGreedyVirusResults = [val[8] for val in testResults]
                    exportTestResults(meanMassesOfGreedyVirusResults, model.getPath() + "data/", "VS_1_Greedy_Virus_MassOverTime")
                    plotTesting(testResults, model.getPath(), testPercentage, maxSteps, "Vs_Greedy_with_Viruses", 8)


            print("Training done.")
            print("")

    if model.getTrainingEnabled():
        model.save(True)
        model.saveModels()
        if parameters.JOB_TRAINING_STEPS == 0 or \
                parameters.JOB_SIMULATION_STEPS + parameters.JOB_STEP_START >= parameters.MAX_SIMULATION_STEPS:

            runTests(model, parameters)
            if model_in_subfolder:
                print(os.path.join(modelPath))
                createCombinedModelGraphs(os.path.join(modelPath))

            print("Total average time per update: ", round(numpy.mean(model.timings), 5))

            bots = model.getBots()
            for bot_idx, bot in enumerate([bot for bot in model.getBots() if bot.getType() == "NN"]):
                player = bot.getPlayer()
                print("")
                print("Network parameters for ", player, ":")
                attributes = dir(parameters)
                for attribute in attributes:
                    if not attribute.startswith('__'):
                        print(attribute, " = ", getattr(parameters, attribute))
                print("")
                print("Mass Info for ", player, ":")
                massListPath = model.getPath() + "/data/" +  model.getDataFiles()["NN" + str(bot_idx) + "_mass"]
                with open(massListPath, 'r') as f:
                    massList = list(map(float, f))
                mean = numpy.mean(massList)
                median = numpy.median(massList)
                variance = numpy.std(massList)
                print("Median = ", median, " Mean = ", mean, " Std = ", variance)
                print("")
        elif testResults is not None:
            with open(model.getPath() + "replay_buffer.pkl", 'wb') as output:
                print(len(model.getBots()[0].getExpReplayer()), "buffLength")
                pkl.dump(model.getBots()[0].getExpReplayer(), output, pkl.HIGHEST_PROTOCOL)
            with open(model.getPath() + "testResults.pkl", 'wb') as output:
                pkl.dump(testResults, output, pkl.HIGHEST_PROTOCOL)

            submitNewJob(model.getPath())
示例#42
0
validationSize = 0.2


# Load training and validation images and labels

data = dataset.readTrainSets(
    trainPath, imgSize, classes, validationSize=validationSize)

print("Complete reading input data. Will Now print a snippet of it")
print("Number of files in Training-set:\t\t{}".format(len(data.train.labels)))
print("Number of files in Validation-set:\t{}".format(len(data.valid.labels)))

session = tf.Session()

# Get model graph
nn = Model()
x, layerFc2, yTrue, yTrueCls, yPred, yPredCls = nn.getGraph(len(classes))

session.run(tf.global_variables_initializer())

# Training functions
crossEntropy = tf.nn.softmax_cross_entropy_with_logits(
    logits=layerFc2, labels=yTrue)
cost = tf.reduce_mean(crossEntropy)
optimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(cost)
correct_prediction = tf.equal(yPredCls, yTrueCls)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

session.run(tf.global_variables_initializer())

示例#43
0
    def __init__(self):
        QMainWindow.__init__(self)

        self.resize(800, 470)
        self.setWindowTitle('Jerry - Chess')
        self.centerOnScreen()

        exit = QAction(QIcon('icons/exit.png'), 'Exit', self)
        exit.setShortcut('Ctrl+Q')
        exit.setStatusTip(self.trUtf8('Exit application'))
        self.connect(exit, SIGNAL('triggered()'), SLOT('close()'))

        self.engine_controller = Uci_controller()
        """
        self.engine_fn = os.path.dirname(os.path.realpath(sys.argv[0]))
        # get filename of engine depending on os
        if sys.platform == 'win32':
            self.engine_fn += "/engine/stockfish.exe"
        elif 'linux' in  sys.platform:
            self.engine_fn += "/engine/stockfish_linux"
        elif sys.platform == 'darwin':
            self.engine_fn += '/engine/stockfish_osx'
        self.engine_fn = '"'+self.engine_fn+'"'
        """

        self.model = Model.create_on_startup(self)

        self.chessboard_view = ChessboardView(self.model.gamestate,self.engine_controller)
        self.chessboard_view.on_statechanged()

        self.moves_edit_view = MovesEditView(self.model.gamestate)
        self.moves_edit_view.setReadOnly(True)
        self.moves_edit_view.on_statechanged()


        # setup the main window
        # consisting of:
        #
        # <-------menubar---------------------------->
        # <chess-     ->   <moves_edit_view---------->
        # <boardview  ->   <engine output (Textedit)->
        #
        spLeft = QSizePolicy();
        spLeft.setHorizontalStretch(1);
        mainWidget = QWidget()
        hbox = QHBoxLayout()
        hbox.addWidget(self.chessboard_view)
        spRight = QSizePolicy()
        spRight.setHorizontalStretch(2)
        vbox = QVBoxLayout()
        self.name = QLabel()
        self.name.setAlignment(Qt.AlignCenter)
        self.name.setBuddy(self.moves_edit_view)
        vbox.addWidget(self.name)
        vbox.addWidget(self.moves_edit_view)
        self.chessboard_view.movesEdit = self.moves_edit_view
        self.engineOutput = QTextEdit()
        self.engineOutput.setReadOnly(True)
        self.engineOutput.setFocusPolicy(Qt.NoFocus)
        vbox.addWidget(self.engineOutput)
        hbox.addLayout(vbox)
        mainWidget.setLayout(hbox)
        self.setCentralWidget(mainWidget)
        statusbar = self.statusBar()
        statusbar.showMessage('Jerry v2.0')

        # set labels of game (i.e. player etc.) above move editing panel
        self.setLabels()

        # create the main menu bar, and connect slots for actions
        self.menubar = self.menuBar()

        # the gamestate controller is the controller that
        # manages all functionality w.r.t. state changes
        #
        # other controllers get a reference of this
        # controller and make user of this functionality
        self.gamestateController = GamestateController(self)

        # FILE MENU
        self.fileMenuController = FileMenuController(self)
        m_file = self.menuBar().addMenu(self.trUtf8('File '))
        new_db = m_file.addAction(self.trUtf8("New..."))
        new_db.triggered.connect(self.fileMenuController.new_database)
        open_db = m_file.addAction(self.trUtf8("Open..."))
        open_db.setShortcut(QKeySequence.Open)
        open_db.triggered.connect(self.fileMenuController.open_database)
        browse_games = m_file.addAction(self.trUtf8("Browse Games..."))
        browse_games.setShortcut('L')
        browse_games.triggered.connect(self.fileMenuController.browse_games)
        m_file.addSeparator()
        save_diag = m_file.addAction(self.trUtf8("Save Position as Image"))
        save_diag.triggered.connect(self.fileMenuController.save_image)
        m_file.addSeparator()
        print_game = m_file.addAction(self.trUtf8("Print Game"))
        print_game.triggered.connect(self.fileMenuController.print_game)
        print_game.setShortcut(QKeySequence.Print)
        print_pos = m_file.addAction(self.trUtf8("Print Position"))
        print_pos.triggered.connect(self.fileMenuController.print_position)
        m_file.addSeparator()
        exit_item = m_file.addAction(self.trUtf8("Quit"))
        exit_item.setShortcut(QKeySequence.Quit)
        exit_item.triggered.connect(self.close)

        # EDIT MENU
        self.editMenuController = EditMenuController(self)
        m_edit = self.menuBar().addMenu(self.trUtf8('Edit '))
        copy_game = m_edit.addAction(self.trUtf8("Copy Game"))
        copy_game.triggered.connect(self.editMenuController.copy_game_to_clipboard)
        copy_game.setShortcut(QKeySequence.Copy)
        copy_pos = m_edit.addAction(self.trUtf8("Copy Position"))
        copy_pos.triggered.connect(self.editMenuController.copy_pos_to_clipboard)
        paste = m_edit.addAction(self.trUtf8("Paste"))
        paste.setShortcut(QKeySequence.Paste)
        paste.triggered.connect(self.editMenuController.paste_from_clipboard)
        m_edit.addSeparator()
        enter_pos = m_edit.addAction(self.trUtf8("&Enter Position"))
        enter_pos.setShortcut('e')
        enter_pos.triggered.connect(self.editMenuController.enter_position)
        reset_pos = m_edit.addAction(self.trUtf8("Reset to Initial"))
        reset_pos.triggered.connect(self.editMenuController.reset_to_initial)
        m_edit.addSeparator()
        flip = m_edit.addAction(self.trUtf8("&Flip Board"))
        flip.setShortcut('f')
        flip.triggered.connect(self.chessboard_view.flip_board)
        self.display_info = QAction(self.trUtf8("Show Search &Info"),m_edit,checkable=True)
        self.display_info.setShortcut('i')
        m_edit.addAction(self.display_info)
        self.display_info.setChecked(True)
        self.display_info.triggered.connect(self.set_display_info)
        m_edit.addSeparator()
        self.offer_draw = m_edit.addAction(self.trUtf8("Offer Draw"))
        self.offer_draw.triggered.connect(self.gamestateController.handle_offered_draw)
        self.offer_draw.setEnabled(False)
        self.give_up = m_edit.addAction(self.trUtf8("Resign"))
        self.give_up.triggered.connect(self.gamestateController.on_player_resigns)
        self.give_up.setEnabled(False)
        m_edit.addSeparator()

        # GAME MENU
        self.gameMenuController = GameMenuController(self)
        m_game = self.menuBar().addMenu(self.trUtf8('Game '))
        new_game = m_game.addAction(self.trUtf8('New Game'))
        new_game.setShortcut(QKeySequence.New)
        new_game.triggered.connect(self.gameMenuController.on_newgame)
        self.save = m_game.addAction(self.trUtf8("Save"))
        self.save.triggered.connect(self.gameMenuController.save)
        if(not self.model.gamestate.unsaved_changes):
            self.save.setEnabled(False)
        self.save_as = m_game.addAction(self.trUtf8("Save As New..."))
        self.save_as.triggered.connect(self.gameMenuController.save_as_new)
        export_game = m_game.addAction(self.trUtf8("Export..."))
        export_game.triggered.connect(self.gameMenuController.export_game)
        m_game.addSeparator()
        edit_game_data = m_game.addAction(self.trUtf8("Edit Game Data"))
        edit_game_data.triggered.connect(self.gameMenuController.editGameData)
        m_game.addSeparator()
        next_ = m_game.addAction(self.trUtf8("Next in Database"))
        next_.triggered.connect(self.gameMenuController.on_nextgame)
        prev_ = m_game.addAction(self.trUtf8("Previous in Database"))
        prev_.triggered.connect(self.gameMenuController.on_previous_game)


        # MODE MENU
        self.modeMenuController = ModeMenuController(self)
        m_mode = self.menuBar().addMenu(self.trUtf8("Mode"))
        ag = QActionGroup(self, exclusive=True)
        analysis = QAction(self.trUtf8("&Analysis Mode"),m_mode,checkable=True)
        m_mode.addAction(ag.addAction(analysis))
        analysis.setShortcut('a')
        analysis.triggered.connect(self.modeMenuController.on_analysis_mode)
        self.play_white = QAction(self.trUtf8("Play as &White"),m_mode,checkable=True)
        self.play_white.setShortcut('w')
        m_mode.addAction(ag.addAction(self.play_white))
        self.play_white.triggered.connect(self.modeMenuController.on_play_as_white)

        self.play_black = QAction(self.trUtf8("Play as &Black"),m_mode,checkable=True)
        self.play_black.setShortcut('b')
        m_mode.addAction(ag.addAction(self.play_black))
        self.play_black.triggered.connect(self.modeMenuController.on_play_as_black)

        self.enter_moves = QAction(self.trUtf8("Enter &Moves"),m_mode,checkable=True)
        self.enter_moves.setShortcuts([Qt.Key_M,Qt.Key_Escape])
        m_mode.addAction(ag.addAction(self.enter_moves))
        self.enter_moves.triggered.connect(self.modeMenuController.on_enter_moves_mode)
        self.enter_moves.setChecked(True)
        m_mode.addSeparator()

        self.analyze_game = QAction(self.trUtf8("Full Game Analysis"),m_mode,checkable=True)
        m_mode.addAction(ag.addAction(self.analyze_game))
        self.analyze_game.triggered.connect(self.modeMenuController.on_game_analysis_mode,)
        self.play_out_pos = QAction(self.trUtf8("Play out Position"),m_mode,checkable=True)
        m_mode.addAction(ag.addAction(self.play_out_pos))
        self.play_out_pos.triggered.connect(self.modeMenuController.on_playout_pos)
        m_mode.addSeparator()

        set_strength = m_mode.addAction(self.trUtf8("Strength Level"))
        set_strength.triggered.connect(self.modeMenuController.on_strength_level)

        set_engines = m_mode.addAction(self.trUtf8("Engines..."))
        set_engines.triggered.connect(self.modeMenuController.on_set_engines)

        # HELP MENU
        m_help = self.menuBar().addMenu((self.trUtf8("Help")))
        about = m_help.addAction(self.trUtf8("About"))
        about.setMenuRole(QAction.AboutRole)
        about.triggered.connect(self.show_about)
        homepage = m_help.addAction(self.trUtf8(("Jerry-Homepage")))
        homepage.triggered.connect(self.go_to_homepage)

        self.connect(self.engine_controller, SIGNAL("updateinfo(PyQt_PyObject)"),self.gamestateController.receive_engine_info)
        self.connect(self.moves_edit_view, SIGNAL("statechanged()"),self.chessboard_view.on_statechanged)
        self.connect(self.moves_edit_view, SIGNAL("statechanged()"),self.gamestateController.on_statechanged)
        self.connect(self.moves_edit_view, SIGNAL("unsaved_changes()"),self.gameMenuController.on_unsaved_changes)
        self.connect(self.chessboard_view, SIGNAL("unsaved_changes()"),self.gameMenuController.on_unsaved_changes)
        self.connect(self.chessboard_view, SIGNAL("statechanged()"),self.moves_edit_view.on_statechanged)
        self.connect(self.chessboard_view, SIGNAL("bestmove(QString)"),self.gamestateController.on_bestmove)
        self.connect(self.engine_controller, SIGNAL("bestmove(QString)"),self.gamestateController.on_bestmove)
        self.connect(self.chessboard_view,SIGNAL("drawn"),self.gamestateController.draw_game)
        self.connect(self.chessboard_view,SIGNAL("checkmate"),self.gamestateController.on_checkmate)
示例#44
0
train_data = VideoDataset(
    root_dir=root_dir,
    split_data=split_data,
    split='train',
    )
val_data = VideoDataset(
    root_dir=root_dir,
    split_data=split_data,
    split='val',
    )

train_loader = DataLoader(train_data, batch_size=16, shuffle=True, num_workers=4)
val_loader = DataLoader(val_data, batch_size=16, shuffle=True, num_workers=4)


model = Model(7)
model = model.to(device)

n_epoch = 1000
lr = 0.001
interval = 50

criterion = nn.CrossEntropyLoss()
# optimizer = optim.SGD([{'params':rgb_model.model.classifier.parameters()}, {'params':flow_model.model.classifier.parameters()}], lr=lr, momentum=0.9, weight_decay=0.0005 )
optimizer = optim.SGD(model.parameters(), lr=lr, momentum=0.9, weight_decay=0.0005 )
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, patience=5)
# scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.2, last_epoch=-1)
def train_model(model, n_epoch, optimizer, scheduler, train_loader, val_loader, model_dir):
    print('Start trianning')
    record = open('./{}.txt'.format(os.path.basename(__file__).split('.')[0]), 'w+')
    for epoch in range(n_epoch):
示例#45
0
文件: blog.py 项目: weasky/example
 def __init__(self, **kwd):
     Model.__init__(self, **kwd)
示例#46
0
def main():

    # 载入数据集
    trainset, validset, testset = [], [], []
    if args.inference:  # 测试时只载入测试集
        with open(args.testset_path, 'r', encoding='utf8') as fr:
            for line in fr:
                testset.append(json.loads(line))
        print('载入测试集%d条' % len(testset))
    else:  # 训练时载入训练集和验证集
        with open(args.trainset_path, 'r', encoding='utf8') as fr:
            for line in fr:
                trainset.append(json.loads(line))
        print('载入训练集%d条' % len(trainset))
        with open(args.validset_path, 'r', encoding='utf8') as fr:
            for line in fr:
                validset.append(json.loads(line))
        print('载入验证集%d条' % len(validset))

    # 载入词汇表,词向量
    vocab, embeds = [], []
    with open(args.embed_path, 'r', encoding='utf8') as fr:
        for line in fr:
            line = line.strip()
            word = line[:line.find(' ')]
            vec = line[line.find(' ') + 1:].split()
            embed = [float(v) for v in vec]
            assert len(embed) == config.embedding_size  # 检测词向量维度
            vocab.append(word)
            embeds.append(embed)
    print('载入词汇表: %d个' % len(vocab))
    print('词向量维度: %d' % config.embedding_size)

    # 载入vad字典
    vads = []
    with open(args.vad_path, 'r', encoding='utf8') as fr:
        for line in fr:
            line = line.strip()
            vad = line[line.find(' ') + 1:].split()
            vad = [float(item) for item in vad]
            assert len(vad) == config.affect_embedding_size
            vads.append(vad)
    print('载入vad字典: %d个' % len(vads))
    print('vad维度: %d' % config.affect_embedding_size)

    # 通过词汇表构建一个word2index和index2word的工具
    sentence_processor = SentenceProcessor(vocab, config.pad_id,
                                           config.start_id, config.end_id,
                                           config.unk_id)

    # 创建模型
    model = Model(config)
    epoch = 0  # 训练集迭代次数
    global_step = 0  # 参数更新次数

    # 载入模型
    if os.path.isfile(args.model_path):  # 如果载入模型的位置存在则载入模型
        epoch, global_step = model.load_model(args.model_path)
        model.affect_embedding.embedding.weight.requires_grad = False
        print('载入模型完成')
        # 记录模型的文件夹
        log_dir = os.path.split(args.model_path)[0]
    elif args.inference:  # 如果载入模型的位置不存在,但是又要测试,这是没有意义的
        print('请测试一个训练过的模型!')
        return
    else:  # 如果载入模型的位置不存在,重新开始训练,则载入预训练的词向量
        model.embedding.embedding.weight = torch.nn.Parameter(
            torch.FloatTensor(embeds))
        model.affect_embedding.embedding.weight = torch.nn.Parameter(
            torch.FloatTensor(vads))
        model.affect_embedding.embedding.weight.requires_grad = False
        print('初始化模型完成')
        # 记录模型的文件夹
        log_dir = os.path.join(args.log_path, 'run' + str(int(time.time())))
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)

    if args.gpu:
        model.to('cuda')  # 将模型参数转到gpu

    model.print_parameters()  # 输出模型参数个数

    # 定义优化器参数
    optim = Optim(config.method, config.lr, config.lr_decay,
                  config.weight_decay, config.max_grad_norm)
    optim.set_parameters(model.parameters())  # 给优化器设置参数
    optim.update_lr(epoch)  # 每个epoch更新学习率

    # 训练
    if not args.inference:

        summary_writer = SummaryWriter(os.path.join(
            log_dir, 'summary'))  # 创建tensorboard记录的文件夹

        dp_train = DataProcessor(trainset, config.batch_size,
                                 sentence_processor)  # 数据的迭代器
        dp_valid = DataProcessor(validset,
                                 config.batch_size,
                                 sentence_processor,
                                 shuffle=False)

        while epoch < args.max_epoch:  # 最大训练轮数

            model.train()  # 切换到训练模式

            for data in dp_train.get_batch_data():

                start_time = time.time()

                feed_data = prepare_feed_data(data)
                rl_loss, reward, loss, nll_loss, kld_loss, ppl, kld_weight = train(
                    model, feed_data, global_step)

                optim.optimizer.zero_grad()  # 清空梯度
                if args.reinforce:
                    rl_loss.mean().backward()
                else:
                    loss.mean().backward()  # 反向传播
                optim.step()  # 更新参数

                use_time = time.time() - start_time

                global_step += 1  # 参数更新次数+1

                # summary当前情况
                if global_step % args.print_per_step == 0:
                    print(
                        'epoch: %d, global_step: %d, lr: %g, rl_loss: %.2fs, reward: %.2f, nll_loss: %.2f,'
                        ' kld_loss: %.2f, kld_weight: %g, ppl: %.2f, time: %.2fs'
                        % (epoch, global_step, optim.lr, rl_loss.mean().item(),
                           reward.mean().item(), nll_loss.mean().item(),
                           kld_loss.mean().item(), kld_weight,
                           ppl.mean().exp().item(), use_time))
                    summary_writer.add_scalar('train_rl',
                                              rl_loss.mean().item(),
                                              global_step)
                    summary_writer.add_scalar('train_reward',
                                              reward.mean().item(),
                                              global_step)
                    summary_writer.add_scalar('train_nll',
                                              nll_loss.mean().item(),
                                              global_step)
                    summary_writer.add_scalar('train_kld',
                                              kld_loss.mean().item(),
                                              global_step)
                    summary_writer.add_scalar('train_weight', kld_weight,
                                              global_step)
                    summary_writer.add_scalar('train_ppl',
                                              ppl.mean().exp().item(),
                                              global_step)
                    summary_writer.flush()  # 将缓冲区写入文件

                if global_step % args.log_per_step == 0 or (
                        global_step % (2 * config.kl_step) -
                        config.kl_step) == config.kl_step // 2:

                    log_file = os.path.join(
                        log_dir, '%03d%012d.model' % (epoch, global_step))
                    model.save_model(epoch, global_step, log_file)

                    # 验证集上计算困惑度
                    model.eval()
                    rl_loss, reward, nll_loss, kld_loss, ppl = valid(
                        model, dp_valid, global_step - 1)
                    model.train()
                    print(
                        '在验证集上的rl损失为: %g, 奖励为: %g, nll损失为: %g, kld损失为: %g, 困惑度为: %g'
                        % (rl_loss, reward, nll_loss, kld_loss, np.exp(ppl)))
                    summary_writer.add_scalar('valid_rl', rl_loss, global_step)
                    summary_writer.add_scalar('valid_reward', reward,
                                              global_step)
                    summary_writer.add_scalar('valid_nll', nll_loss,
                                              global_step)
                    summary_writer.add_scalar('valid_kld', kld_loss,
                                              global_step)
                    summary_writer.add_scalar('valid_ppl', np.exp(ppl),
                                              global_step)
                    summary_writer.flush()  # 将缓冲区写入文件

            epoch += 1  # 数据集迭代次数+1
            optim.update_lr(epoch)  # 调整学习率

            # 保存模型
            log_file = os.path.join(log_dir,
                                    '%03d%012d.model' % (epoch, global_step))
            model.save_model(epoch, global_step, log_file)

            # 验证集上计算困惑度
            model.eval()
            rl_loss, reward, nll_loss, kld_loss, ppl = valid(
                model, dp_valid, global_step - 1)
            print(
                '在验证集上的rl损失为: %g, 奖励为: %g, nll损失为: %g, kld损失为: %g, 困惑度为: %g' %
                (rl_loss, reward, nll_loss, kld_loss, np.exp(ppl)))
            summary_writer.add_scalar('valid_rl', rl_loss, global_step)
            summary_writer.add_scalar('valid_reward', reward, global_step)
            summary_writer.add_scalar('valid_nll', nll_loss, global_step)
            summary_writer.add_scalar('valid_kld', kld_loss, global_step)
            summary_writer.add_scalar('valid_ppl', np.exp(ppl), global_step)
            summary_writer.flush()  # 将缓冲区写入文件

        summary_writer.close()

    else:  # 测试

        if not os.path.exists(args.result_path):  # 创建结果文件夹
            os.makedirs(args.result_path)

        result_file = os.path.join(args.result_path, '%03d%012d.txt' %
                                   (epoch, global_step))  # 命名结果文件
        fw = open(result_file, 'w', encoding='utf8')

        dp_test = DataProcessor(testset,
                                config.batch_size,
                                sentence_processor,
                                shuffle=False)

        model.eval()  # 切换到测试模式,会停用dropout等等

        rl_loss, reward, nll_loss, kld_loss, ppl = valid(
            model, dp_test, global_step - 1)
        print('在测试集上的rl损失为: %g, 奖励为: %g, nll损失为: %g, kld损失为: %g, 困惑度为: %g' %
              (rl_loss, reward, nll_loss, kld_loss, np.exp(ppl)))

        len_results = []  # 统计生成结果的总长度

        for data in dp_test.get_batch_data():

            posts = data['str_posts']
            responses = data['str_responses']

            feed_data = prepare_feed_data(data, inference=True)
            results = test(model, feed_data)  # 使用模型计算结果 [batch, len_decoder]

            for idx, result in enumerate(results):
                new_data = {}
                new_data['post'] = posts[idx]
                new_data['response'] = responses[idx]
                new_data['result'] = sentence_processor.index2word(
                    result)  # 将输出的句子转回单词的形式
                len_results.append(len(new_data['result']))
                fw.write(json.dumps(new_data) + '\n')

        fw.close()
        print('生成句子平均长度: %d' % (1.0 * sum(len_results) / len(len_results)))