def evaluate(model='ram', width=60, n_distractors=4, N=10):
    """Tests performance of trained model on larger/noisier mnist images."""

    # data
    mnist = input_data.read_data_sets('MNIST_data', one_hot=False)

    # set parameters
    #config.loc_std          = 1e-10
    config.num_glimpses = FLAGS.num_glimpses
    config.n_patches = FLAGS.n_patches
    config.use_context = FLAGS.use_context
    config.convnet = FLAGS.convnet
    config.sensor_size = config.glimpse_size**2 * config.n_patches * config.num_channels
    config.N = mnist.train.num_examples  # number of training examples

    config.new_size = width
    config.n_distractors = n_distractors

    # init model
    print('\n-- Model: {} --'.format(model))
    print('Setting samplding SD to {:.4e}'.format(config.loc_std))
    if model == 'ram':
        net = RAM(config)
    elif model == 'dram':
        net = DRAM(config)
    elif model == 'dram_loc':
        net = DRAMl(config)
    else:
        print('Unknown model {}'.format(model))
        exit()

    net.load(FLAGS.load)  # restore
    net.count_params()

    #params = net.return_params(['context_network/conv0/w:0'])
    #net.plot_filters(params[0], fname=FLAGS.plot_dir + '.pdf')
    #exit()

    if FLAGS.visualize:

        # create plot for current parameters
        plot_dir = os.path.join(FLAGS.load, FLAGS.plot_dir)
        if not os.path.exists(plot_dir):
            os.mkdir(plot_dir)

        task = {
            'variant': FLAGS.task,
            'width': width,
            'n_distractors': n_distractors
        }
        net.visualize(data=mnist,
                      task=task,
                      config=config,
                      N=N,
                      plot_dir=plot_dir)

    # evaluate
    #test, val = net.evaluate(data=mnist, task=FLAGS.task)

    return test, val
Beispiel #2
0
	def WRITE(self, BYTE):
		# Check if there is a value at the current address
		if RAM().ADDRESS[ADDR().PEEK()]:
			RAM().ADDRESS[ADDR().PEEK()] = BYTE # Write to Address
			DEBUG().MSG('BUS', 'DATA', 'WRITE', DATA)
		else:
			DEBUG().MSG('BUS', 'DATA', 'WRITE', 'NO ADDRESS')
Beispiel #3
0
	def READ(self): # Read Function
		# Check if there is a value at the current address
		if RAM().ADDRESS[ADDR().PEEK()]:
			DATA = RAM().ADDRESS[ADDR().PEEK()] # Assign the value from address
		else:
			DATA = 0 # If no value assign 0
		DEBUG().MSG('BUS', 'DATA', 'READ', DATA)
		return DATA # Return the value
def main():
    tabla = RAM()
    visual = Rom()
    registros = Rom()
    reloj = Rom()
    operacion = Rom()
    r1= Register()
    delay1=delay()
    delay1.Htz()
    registros.vis()
    visual.vis()
    reloj.vis()
    operacion.vis()




    print ("\n                  Proyecto 1 CPU Simulator                           ")
    print ("*--------------------------------------------------------------------*")
    print ("""      Integrantes:
            - Juan Luis Fernandez
            - Rodrigo Reyes
            - Esteban Samayoa\n
                """)
    delay1.tiempo()
    if visual.v == True:
        print ("*--------------------------------*")
        print ("              RAM                    ")
        tabla.valoress()
    delay1.tiempo()
    if registros.b == True:
        print (f"""
*---------------------------------*
            REGISTROS:
        Primer registro : {r1.R0}
        Segundo registro : {r1.R1}
        Tercer registro : {r1.R2}

    """)
    delay1.tiempo()
    if reloj.c == True:
        print ("*--------------------------------*")
        print (f"""
        Tiempo : {hrtzz.htz}
        """)
    delay1.tiempo()
    if operacion.a == True:
        cu1=CU()
        cu1.operate()
Beispiel #5
0
 def __init__(self, manufacturer, build_date, purpose, ram, clock,
              visualizations):
     super().__init__(manufacturer, build_date, purpose)
     self.ram = RAM(manufacturer, build_date, "Random access memory", 16,
                    ram)  #RAM
     self.alu = ALU(manufacturer, build_date,
                    "Arithmetic and Logic unit")  #ALU
     #clock
     self.clock = Clock(manufacturer, build_date,
                        "This component manages the time", clock)
     #Registers
     self.a = Register(manufacturer, build_date, "Register A", 4, "")
     self.b = Register(manufacturer, build_date, "Register B", 4, "")
     self.c = Register(manufacturer, build_date, "Register C", 4, "")
     self.d = Register(manufacturer, build_date, "Register D", 4, "")
     self.pc = Register(manufacturer, build_date, "Program Counter", 4, 0)
     self.ir = Register(manufacturer, build_date, "Instruction Register", 4,
                        "")
     self.irb = Register(manufacturer, build_date, "Instruction Register",
                         4, "")
     self.oR = ORegister(manufacturer, build_date, "Output Register", 4, "")
     self.visualizations = visualizations
Beispiel #6
0
    def __init__(self, RAM_size, cache_size,  block_size, associativity, replacement):

        self.ram = RAM(RAM_size=RAM_size, block_size=block_size)
        self.cache = Cache(RAM_size = RAM_size, cache_size=cache_size, block_size=block_size, associativity=associativity, replacement=replacement)
        self.RAM_size = RAM_size
        self.associativity = associativity
        self.block_size = block_size
        self.cache_size = cache_size
        self.address = Address(self.RAM_size, self.cache_size, self.block_size, self.associativity)
        self.loadcount = 0
        self.storecount = 0
        self.addcount = 0
        self.multcount = 0
Beispiel #7
0
def main():
    global bus, ram, ppi, alu, cu
    bus = Bus()
    ram = RAM(0x0, 64)
    ppi = PPI(0x40)
    bus.AddMemoryPeripheral(ram, 0x0, 0x0+64*1024-1)
    bus.AddIOPeripheral(ppi, 0x40, 0x40+3)
    
    
    alu = ALU()
    cu = CU(alu, bus)
    
    ppi.SetInterruptCallPA(partial(cu.RST, 5.5, ppi))
    ppi.SetInterruptCallPB(partial(cu.RST, 6.5, ppi))
    
    openFile()
    i = 0
    for wd in words:
        ram.Write(0x8000+i, wd)
        i += 1
    
    
    #ram.Write(0x002C, 0x6F)
    #ram.Write(0x002D, 0xC9)
    ram.Write(0x002c, 0xdb)
    ram.Write(0x002d, 0x40)
    ram.Write(0x002e, 0xc9)
    cu.Reset()
    cu.SetPC(0x8000)
    
    thread = Thread(target=execute)
    thread.start()
    
    ppi.a = 0xbb
    while cu.running:
        pass
#        cmd = input("Enter a command: ")
#        if cmd == "quit":
#            cu.running = False
#        elif cmd == "stba":
#            ppi.StrobeA()
#        elif cmd == "stbb":
#            ppi.StrobeB()
#        elif cmd == "show":
#            print("")
#            alu.Show()
#            #print("\n")
#            #ram.Show()
#            print("\n")
#            ppi.Show()

    ram.ShowRange(parser.labels["TABLE"], parser.labels["TABLE"]+0x63)
    alu.Show()
Beispiel #8
0
class CU(IC):
    #attributes for CU
    ram = [None] * 16
    alu = None
    running = None
    #registers
    a = None
    b = None
    c = None
    d = None

    #special register for output
    pc = None
    ir = None
    irb = None
    oR = None
    clock = None
    visualizations = None

    def __init__(self, manufacturer, build_date, purpose, ram, clock,
                 visualizations):
        super().__init__(manufacturer, build_date, purpose)
        self.ram = RAM(manufacturer, build_date, "Random access memory", 16,
                       ram)  #RAM
        self.alu = ALU(manufacturer, build_date,
                       "Arithmetic and Logic unit")  #ALU
        #clock
        self.clock = Clock(manufacturer, build_date,
                           "This component manages the time", clock)
        #Registers
        self.a = Register(manufacturer, build_date, "Register A", 4, "")
        self.b = Register(manufacturer, build_date, "Register B", 4, "")
        self.c = Register(manufacturer, build_date, "Register C", 4, "")
        self.d = Register(manufacturer, build_date, "Register D", 4, "")
        self.pc = Register(manufacturer, build_date, "Program Counter", 4, 0)
        self.ir = Register(manufacturer, build_date, "Instruction Register", 4,
                           "")
        self.irb = Register(manufacturer, build_date, "Instruction Register",
                            4, "")
        self.oR = ORegister(manufacturer, build_date, "Output Register", 4, "")
        self.visualizations = visualizations

    # Intruction Set Table
    def OUTPUT(self, arg):
        pos = int(arg, 2)  #convert binary to decimal
        data = self.ram.getData(pos)  #retrieve data from RAM at position pos
        self.oR.setData(data)  #set data into ORegister

        return "message loaded into ORegister"

    def LD_A(self, RAMLoc):
        pos = int(RAMLoc)
        data = self.ram.getData(pos)
        print(f"Succesfully loaded 'RAM[{pos}]={data}' into Register: A")
        self.a.setData(data)

    def LD_B(self, RAMLoc):
        pos = int(RAMLoc)
        data = self.ram.getData(pos)
        print(f"Succesfully loaded 'RAM[{pos}]={data}' into Register: B")
        self.b.setData(data)

    def AND(self, arg):
        letra1 = self.twoBitToRegLetter(arg[0])
        letra2 = self.twoBitToRegLetter(arg[1])
        value1 = letra1.getData()
        value2 = letra2.getData()
        comparison = self.alu.AND(value1,
                                  value2)  # calls the alu logic operation 'or'
        print(
            f"Register {letra1}: {value1}\nRegister {letra2}: {value2}\And: {bool(comparison)}"
        )
        return comparison

    def ILD_A(self, constant):
        constant = int(constant)
        self.a.setData(constant)
        print(f"Succesfuly loaded {self.a.getData()} into Register A")

    def STR_A(self, addr):
        data = self.a.getData()
        addr = int(addr)
        data = int(data)
        self.ram.setData(addr, data)
        print(f"Succesfuly wrote {self.a.getData()} into RAM address: {addr}")

    def STR_B(self, addr):
        data = self.b.getData()
        addr = int(addr)
        data = int(data)
        self.ram.setData(addr, data)
        print(f"Succesfuly wrote {self.b.getData()} into RAM address: {addr}")

    def OR(self, arg):
        reg1 = self.twoBitToRegLetter(
            arg[0])  # extracts the first 2-bit from the 8bit value
        reg2 = self.twoBitToRegLetter(
            arg[1])  # extracts the first 2-bit from the 8bit value
        value1 = reg1.getData()
        value2 = reg2.getData()
        comparison = self.alu.OR(reg1,
                                 reg2)  # calls the alu logic operation 'or'
        print(
            f"Register {reg1}: {value1}\nRegister {reg2}: {value2}\Or: {bool(comparison)}"
        )
        return comparison

    def ILD_B(self, constant):
        constant = int(constant)
        self.b.setData(constant)
        print(f"Succesfuly read {self.b.getData()} into Register B")

    def ADD(self, arg):
        reg1 = self.twoBitToRegLetter(
            arg[0])  # extracts the first 2-bit from the 8bit value
        reg2 = self.twoBitToRegLetter(
            arg[1])  # extracts the first 2-bit from the 8bit value
        value1 = reg1.getData()
        value2 = reg2.getData()
        addition = self.alu.ADD(value1, value2)
        reg2.setData(addition)
        print(
            f"Register {reg1}: {value1}\nRegister {reg2}: {value2}\Addition: {addition}"
        )

    def SUB(self, arg):
        reg1 = self.twoBitToRegLetter(
            arg[0])  # extracts the first 2-bit from the 8bit value
        reg2 = self.twoBitToRegLetter(
            arg[1])  # extracts the first 2-bit from the 8bit value
        value1 = reg1.getData()
        value2 = reg2.getData()
        substraction = self.alu.SUB(value1, value2)
        reg2.setData(substraction)
        print(
            f"Register {reg1}: {value1}\nRegister {reg2}: {value2}\Substraction: {substraction}"
        )

    def JMP(self, arg):
        self.pc.data = int(arg)

    def JMP_N(self, arg):
        if (self.alu.getNegative() == 1):
            self.JMP(arg)
        else:
            pass

    def ILD_C(self, constant):
        constant = int(constant)
        self.a.setData(constant)
        print(f"Succesfuly loaded {self.c.getData()} into Register C")

    def ILD_D(self, constant):
        constant = int(constant)
        self.a.setData(constant)
        print(f"Succesfuly loaded {self.d.getData()} into Register D")

    def reset(self):
        self.pc.data = 0
        self.ir = self.irb
        self.running = False

    def HALT(self, data):
        print("HALTING...")
        self.reset()

    # Dictionary with commands and functions
    intructionSetTable = {
        "0000": OUTPUT,
        "OUTPUT": OUTPUT,
        "0001": LD_A,
        "LD_A": LD_A,
        "0010": LD_B,
        "LD_B": LD_B,
        "0011": AND,
        "AND": AND,
        "0100": ILD_A,
        "ILD_A": ILD_A,
        "0101": STR_A,
        "STR_A": STR_A,
        "0110": STR_B,
        "STR_B": STR_B,
        "0111": OR,
        "OR": OR,
        "1000": ILD_B,
        "ILD_B": ILD_B,
        "1001": ADD,
        "ADD": ADD,
        "1010": SUB,
        "SUB": SUB,
        "1011": JMP,
        "JMP": JMP,
        "1100": JMP_N,
        "JMP_N": JMP_N,
        "1101": ILD_C,
        "ILD_C": ILD_C,
        "ILD_D": ILD_D,
        "1110": ILD_D,
        "HALT": HALT,
        "1111": HALT
    }

    # Dictionary that returns for each 2bit code a letter corresponding to a reg
    def twoBitToRegLetter(self, param):
        if (param == "00" or param == "A"):
            return self.a
        if (param == "01" or param == "B"):
            return self.b
        if (param == "10" or param == "C"):
            return self.c
        if (param == "11" or param == "D"):
            return self.d

    # twoBitToRegLetter = {
    #     "00": "a",
    #      "A": "a",
    #     "01": "b",
    #      "B": "b",
    #     "10": "c",
    #      "C": "c",
    #     "11": "d",
    #      "D": "d"
    # }

    def getFunction(self, opcode):
        return self.intructionSetTable.get(opcode)

    """ def getRegLetter(self, twoBit):
        return self.twoBitToRegLetter.get(twoBit) """

    def initBios(self, string):
        pass

    def startInstructions(self, codelines):
        for line in codelines:
            if (line[0] != "#"):
                self.fetch(line)
                self.clock.next()

    def run(self, codelines, pc=None):
        if pc:
            self.pc.data = pc
        self.running = True
        while self.running:
            self.startInstructions(codelines)

    def fetch(self, codeline):
        self.decode(codeline)

    def decode(self, lineOfCode):
        opcode = lineOfCode.split()[0]
        print(f"opcode: {opcode}")
        function = self.getFunction(opcode)
        print(f"function: {function}")
        print(f"PC: {self.pc.data}")
        self.pc.data += 1
        self.ir = function
        if (len(lineOfCode.split()) == 3):
            arguments = lineOfCode.split()[1:]
            arguments = list(map(str, arguments))
            print(f"Arguments: {arguments}")
        elif (len(lineOfCode.split()) == 2):
            arguments = lineOfCode.split()[1]
        else:
            arguments = None
        self.execute(function, arguments)

    def execute(self, function, param):
        function(self, param)

    def printStatus(self):
        return f"Running?: {bool(self.running)}"
Beispiel #9
0
from GUI import HackComputerGUI
from CPU import CPU
from ROM import ROM
from RAM import RAM
from VRAM import VRAM

if __name__ == "__main__":

    #def __init__(self, ROM, RAM, is_print_state=False, log_path="log.txt"):
    cpu = CPU(ROM(), RAM(), VRAM(), is_print_state=False)
    hack_computer_GUI = HackComputerGUI(cpu)
    hack_computer_GUI.run()
Beispiel #10
0
	def CLEAR(self):
		RAM().ADDRESS.clear() # Clear all values from RAM
		DEBUG().MSG('BUS', 'DATA', 'CLEAR', 0)
Beispiel #11
0
	def LIST(self):
		print(RAM().ADDRESS)
Beispiel #12
0
    print '\n\nFlags: {}\n\n'.format(FLAGS)
    # ------------------------------

    # data
    mnist = input_data.read_data_sets('MNIST_data', one_hot=False)

    # init model
    config.num_glimpses = FLAGS.num_glimpses
    config.n_patches = FLAGS.n_patches
    config.sensor_size = config.glimpse_size**2 * config.n_patches
    config.N = mnist.train.num_examples  # number of training examples

    if FLAGS.model == 'ram':
        print '\n\n\nTraining RAM\n\n\n'
        model = RAM(config, logdir=FLAGS.logdir)
    elif FLAGS.model == 'dram':
        print '\n\n\nTraining DRAM\n\n\n'
        model = DRAM(config, logdir=FLAGS.logdir)
    elif FLAGS.model == 'dram_loc':
        print '\n\n\nTraining DRAM with location ground truth\n\n\n'
        model = DRAMl(config, logdir=FLAGS.logdir)
    else:
        print 'Unknown model {}'.format(FLAGS.model)
        exit()

    # load if specified
    if FLAGS.load != None:
        model.load(FLAGS.load)

    # display # parameters
def random_search(architecture='dram',
                  task='translated',
                  grid={},
                  k=5,
                  config=None):
    """ Evaluates 'k' random hyper-parameter combinations and returns dict containing scores.

    Parameter names are (same as in config):
        * num_glimpses  (discrete)
        * glimpse_size  (discrete)
        * loc_std       (continuous)

    :param      architecture:   (str) 'ram' or 'dram'
    :param      grid:           (dict) {'parameter_name': np.range(lower,upper)}
    :param      k:              (int) # of combinations tested
    :return:    results         (dict) accuracy for each combination
    """

    print('\n\nModel {}\n\n'.format(architecture))

    # init
    results = {}
    best_score = 0  # higher is better
    best_params = []

    # data
    mnist = input_data.read_data_sets('MNIST_data', one_hot=False)
    config.N = mnist.train.num_examples

    for i in range(k):

        # sample parameter combination
        config.num_glimpses = np.random.choice(grid['num_glimpses'])
        config.loc_std = np.round(
            np.random.choice(grid['loc_std']).astype(np.float32), 2)
        config.glimpse_size = np.random.choice(grid['glimpse_size'])

        # TODO: add other params here

        config.sensor_size = config.glimpse_size**2 * config.n_patches
        config.bandwidth = config.glimpse_size**2

        print('\n\n---- Combination #{} ----\n\n'.format(i))
        print('Num glimpses:\t{}'.format(config.num_glimpses))
        print('Glimpse size:\t{}x{}'.format(config.glimpse_size,
                                            config.glimpse_size))
        print('Loc std:\t{}\n'.format(config.loc_std))

        cur_params = (config.num_glimpses, config.loc_std, config.glimpse_size)

        # log directory
        time_str = datetime.now().strftime('%H%M%S')

        logdir = "./parameter_search/model={}_{}{}x{}_n_glimpses={}_fovea={}x{}_std={:2.3f}_{}_lr={}-{}".format(
            architecture, task, config.new_size, config.new_size,
            config.num_glimpses, config.glimpse_size, config.glimpse_size,
            config.loc_std, time_str, config.lr_start, config.lr_min)

        # init model
        tf.reset_default_graph()

        if architecture == 'ram':
            model = RAM(config, logdir=logdir)
        elif architecture == 'dram':
            model = DRAM(config, logdir=logdir)
        else:
            print('Unknown model {}'.format(architecture))
            exit()

        # train model
        model.train(mnist, task)

        # evaluate
        test, val = model.evaluate(data=mnist, task=task)

        print('\n\nResults:\nTest:\t{}\nVal:\t{}'.format(test, val))

        # store
        results[cur_params] = [test, val]

        # update best score
        if test > best_score:
            print('Best params: {}\tScore: {}'.format(cur_params, test))
            results['best_params'] = cur_params
            best_score = test

    return results
Beispiel #14
0
from CU import CU
from RAM import RAM
from Bus import Bus
from PPI import PPI
from Assembler import Assembler
from PPIWindow import PPIWindow

from threading import Thread
from functools import partial
import re
import time
from enum import Enum
import sys, os

bus = Bus()
ram = RAM(0x0, 64)
bus.AddMemoryPeripheral(ram, 0x0, 0x0 + 64 * 1024 - 1)

alu = ALU()
cu = CU(alu, bus)


def AddPPI(addr):
    ppi = PPI(addr)
    bus.AddIOPeripheral(ppi, addr, addr + 3)
    ppi.SetInterruptCallPA(partial(cu.RST, 5.5, ppi))
    ppi.SetInterruptCallPB(partial(cu.RST, 6.5, ppi))
    return ppi


class State(Enum):
class CU():
    register = Register()

    ram1 = RAM()
    rom1 = Rom()
    ram1.upcc()
    ram1.instt()
    delay1 = delay()
    delay1.Htz()
    ram1.valoress()

    def operate(self):
        for line in self.ram1.d:
            print("-------------------------------------------------")
            print("Fetch:")
            print(f"La instrucción es: {self.ram1.d[line]}")
            self.delay1.tiempo()
            print("Decode:")
            for j in self.rom1.instructions:
                if self.ram1.d[line][0:4] == j:
                    print(self.rom1.instructions[j])
                    print(self.ram1.d[line][5:10])
                    self.delay1.tiempo()
                    print("Execute:")
                    if self.rom1.instructions[j] == "LOAD_R0":
                        self.rom1.valores()
                        posicion = int(self.ram1.d[line][5:10])
                        self.register.getvalue(self.rom1.val[posicion])
                        self.register.r0()

                    elif self.rom1.instructions[j] == "LOAD_R1":
                        self.rom1.valores()
                        posicion = int(self.ram1.d[line][5:10])
                        self.register.getvalue(self.rom1.val[posicion])
                        self.register.r1()

                    elif self.rom1.instructions[j] == "OUTPUT":
                        print(self.register.r1())

                    elif self.rom1.instructions[j] == "ADD":
                        a = self.ram1.d[line][5:7]
                        b = self.ram1.d[line][8:10]
                        print(a)
                        print(b)
                        alu1 = ALU(self.register.R0, self.register.R1, 0)
                        alu1.suma()
                        self.register.getvalue(alu1.result)
                        self.register.r1()

                    elif self.rom1.instructions[j] == "SUB":
                        a = self.ram1.d[line][5:7]
                        b = self.ram1.d[line][8:10]
                        print(a)
                        print(b)
                        alu1 = ALU(self.register.R0, self.register.R1, 0)
                        alu1.resta()

                    elif self.rom1.instructions[j] == "HALT":
                        exit()

                    elif self.rom1.instructions[j] == "AND":
                        a = self.ram1.d[line][5:7]
                        b = self.ram1.d[line][8:10]
                        print(a)
                        print(b)
                        alu1 = ALU(self.register.R0, self.register.R1, 0)
                        if alu1.And() == True:
                            print("La siguiente operación lógica es verdadera")
                        else:
                            print("La operación es falsa")

                    elif self.rom1.instructions[j] == "OR":
                        a = self.ram1.d[line][5:7]
                        b = self.ram1.d[line][8:10]
                        print(a)
                        print(b)
                        alu1 = ALU(self.register.R0, self.register.R1, 0)
                        if alu1.OR() == True:
                            print("La siguiente operación lógica es verdadera")
                        else:
                            print("La operación es falsa")

                    elif self.rom1.instructions[j] == "STORE_R0":
                        rom1 = Rom()
                        rom1.valores()
                        self.rom1.val[line][8:10] = self.register.R0
                        print(self.rom1.val[line][8:10])

                    elif self.rom1.instructions[j] == "STORE_R0":
                        rom1 = Rom()
                        rom1.valores()
                        self.rom1.val[line][8:10] = self.register.R1
                        print(self.rom1.val[line][8:10])

                    elif self.rom1.instructions[j] == "ILD_R0":
                        self.rom1.valores()
                        posicion = int(self.ram1.d[line][5:10])
                        self.register.getvalue(self.rom1.val[posicion])
                        self.register.r0()

                    elif self.rom1.instructions[j] == "ILD_R1":
                        self.rom1.valores()
                        posicion = int(self.ram1.d[line][5:10])
                        self.register.getvalue(self.rom1.val[posicion])
                        self.register.r1()

                    elif self.rom1.instructions[j] == "LOAD_R2":
                        self.rom1.valores()
                        posicion = int(self.ram1.d[line][5:10])
                        self.register.getvalue(self.rom1.val[posicion])
                        self.register.r2()

                    elif self.rom1.instructions[j] == "LOAD_R3":
                        pass

            print("-------------------------------------------------")
            self.delay1.tiempo()
Beispiel #16
0
# -*- encoding: utf-8 -*-
#
# Authors: Asger Anders Lund Hansen, Mads Ynddal and Troels Ynddal
# License: See LICENSE file
# GitHub: https://github.com/Baekalfen/PyBoy
#

from RAM import RAM
import random
import unittest

# cart = Cartridge("pokemon_blue.gb")

RAM = RAM(None, None, False)


def funky(self, ram, x, y):
    y = y - 1
    r = random.random()

    random.seed(r)
    for n in xrange(x, y):
        ram[n].setInt(random.randint(0, 255))

    random.seed(r)
    for n in xrange(x, y):
        self.assertEqual(ram[n], random.randint(0, 255))


class Test_RAM(unittest.TestCase):
    def test_videoRAM(self):
Beispiel #17
0
	def LOAD(self, BYTE):
		#RAM().ADDRESS.append(bytes(BYTE)) # Add Byte to next RAM Address
		RAM().ADDRESS.append(BYTE)
		DEBUG().MSG('BUS', 'DATA', 'LOAD', BYTE)
    print(('\n\nFlags: {}\n\n'.format(FLAGS)))
    # ------------------------------

    # data
    mnist = input_data.read_data_sets('MNIST_data', one_hot=False)

    # init model
    config.num_glimpses = FLAGS.num_glimpses
    config.n_patches = FLAGS.n_patches
    config.sensor_size = config.glimpse_size**2 * config.n_patches
    config.N = mnist.train.num_examples  # number of training examples

    if FLAGS.model == 'ram':
        print('\n\n\nTraining RAM\n\n\n')
        model = RAM(config, logdir=FLAGS.logdir)
    elif FLAGS.model == 'dram':
        print('\n\n\nTraining DRAM\n\n\n')
        model = DRAM(config, logdir=FLAGS.logdir)
    elif FLAGS.model == 'dram_loc':
        print('\n\n\nTraining DRAM with location ground truth\n\n\n')
        model = DRAMl(config, logdir=FLAGS.logdir)
    else:
        print(('Unknown model {}'.format(FLAGS.model)))
        exit()

    # load if specified
    if FLAGS.load is not None:
        model.load(FLAGS.load)
        model.visualize(config=[],
                        data=mnist,
def evaluate_numglimpses(model='dram_loc', visualize=False, N=10):
    """Tests performance of trained model on larger/noisier mnist images."""

    # data
    mnist = input_data.read_data_sets('MNIST_data', one_hot=False)

    # set parameters
    n_glimpses = [1, 2, 3, 4, 5, 6, 7, 8]
    n_reps = N
    width, noise = 100, 4

    RESULTS = {}

    for n in n_glimpses:

        # set parameters
        config.num_glimpses = n
        config.n_patches = FLAGS.n_patches
        config.use_context = FLAGS.use_context
        config.convnet = FLAGS.convnet

        config.sensor_size = config.glimpse_size**2 * config.n_patches * config.num_channels
        config.N = mnist.train.num_examples  # number of training examples

        config.new_size = width
        config.n_distractors = noise

        # init model
        print('\n-- Model: {} --'.format(model))
        print('Setting samplding SD to {:.4e}'.format(config.loc_std))
        tf.reset_default_graph()
        if model == 'ram':
            net = RAM(config)
        elif model == 'dram':
            net = DRAM(config)
        elif model == 'dram_loc':
            net = DRAMl(config)
        else:
            print('Unknown model {}'.format(model))
            exit()
        net.load(FLAGS.load)  # restore

        if FLAGS.visualize:
            n_reps = 1

            # create plot for current parameters
            subfolder = os.path.join(FLAGS.load, FLAGS.plot_dir)
            if not os.path.exists(subfolder):
                os.mkdir(subfolder)
            plot_dir = os.path.join(
                subfolder, 'w={}_n_distractors={}'.format(width, noise))
            if not os.path.exists(plot_dir):
                os.mkdir(plot_dir)

            task = {
                'variant': FLAGS.task,
                'width': width,
                'n_distractors': noise
            }
            net.visualize(data=mnist,
                          task=task,
                          config=config,
                          plot_dir=plot_dir,
                          N=N)

        # evaluate (n_reps) times
        acc, _ = evaluate_repeatedly(ram=net,
                                     data=mnist,
                                     task=FLAGS.task,
                                     n_reps=n_reps)
        print(acc)

        # store results
        RESULTS[n] = acc

    # save dictionary
    with open(
            os.path.join(
                FLAGS.load,
                'glimpses{}_results.pickle'.format(FLAGS.num_glimpses)),
            'wb') as handle:
        pickle.dump(RESULTS, handle, protocol=pickle.HIGHEST_PROTOCOL)