class MemoryManagerTest(unittest.TestCase):

    #Arrange
    def setUp(self):
        self.hdd = HDD(10)
        self.fs = self.hdd.generate_file_system()
        self.instruction1 = InstructionIO()
        self.instruction2 = InstructionCPU()
        self.instruction3 = InstructionIO()
        self.instructionList1 = [self.instruction1, self.instruction2]
        self.instructionList2 = [self.instruction1, self.instruction2, self.instruction3]
        self.program1 = Program(self.instructionList1, "AProgram")
        self.program2 = Program(self.instructionList2, "BProgram")
        self.fs.add_file("AProgram", self.program1)
        self.fs.add_file("BProgram", self.program2)
        self.file1 = self.fs.get_program("AProgram")
        self.file2 = self.fs.get_program("BProgram")
        self.pcb1 = PCB(0, 2, BlockHolder(self.file1))
        self.pcb2 = PCB(0, 3 , BlockHolder(self.file2))
        self.memoryManager = MemoryManager()
        self.memoryManager.set_as_ca(FirstFit())

    def test_whenTheMemoryManagerAddsTwoProgramsAndIAskForThe6thPosition_thenIShouldGetException(self):
        self.memoryManager.write(self.pcb1)
        self.memoryManager.write(self.pcb2)
Example #2
0
class MemoryManagerTest(unittest.TestCase):

    #Arrange
    def setUp(self):
        self.hdd = HDD(10)
        self.fs = self.hdd.generate_file_system()
        self.instruction1 = InstructionIO()
        self.instruction2 = InstructionCPU()
        self.instruction3 = InstructionIO()
        self.instructionList1 = [self.instruction1, self.instruction2]
        self.instructionList2 = [
            self.instruction1, self.instruction2, self.instruction3
        ]
        self.program1 = Program(self.instructionList1, "AProgram")
        self.program2 = Program(self.instructionList2, "BProgram")
        self.fs.add_file("AProgram", self.program1)
        self.fs.add_file("BProgram", self.program2)
        self.file1 = self.fs.get_program("AProgram")
        self.file2 = self.fs.get_program("BProgram")
        self.pcb1 = PCB(0, 2, BlockHolder(self.file1))
        self.pcb2 = PCB(0, 3, BlockHolder(self.file2))
        self.memoryManager = MemoryManager()
        self.memoryManager.set_as_ca(FirstFit())

    def test_whenTheMemoryManagerAddsTwoProgramsAndIAskForThe6thPosition_thenIShouldGetException(
            self):
        self.memoryManager.write(self.pcb1)
        self.memoryManager.write(self.pcb2)
Example #3
0
def main():

    thread = threading.Thread(target=recv_package)
    thread.start()
    ### Leer cuantos sensores hay conectados para poder realizar el handshake(malloc mágico)
    ### Crear barrera con contador = cuantos sensores hay
    ### Crear cola para cada thread
    ### Crear semaforo para cada cola de rocolectores
    ### Crear threads recolectores (se envía de parámetro su cola y su identificador respectivo)
    #abre el archivo csv en modo lectura
    interface_queue = queue.Queue(queue_size)
    collectors = Collectors()
    collectors_info = collectors.initializer(interface_queue)

    memoryManager = MemoryManager()

    plotter = Plotter()

    #Por cuestiones de comodidad se inicializa acá pero no se usa posteriormente.
    interface = Interface()
    #plotter.initializer(interface)
    interface.initializer(interface_queue, collectors_info, memoryManager,
                          plotter)

    while True:
        with open('identificadores.csv', 'r') as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            next(csv_reader)
            next(csv_reader)
            semaphore.acquire()
            #cierra el mutex, saca el paquete respectivo de la cola, y lo vuelve a abrir
            lock.acquire
            package = packet_queue.get()
            lock.release
            #Si hubo un timeout, el servidor termina su ejecución; si no, imprime el paquete.
            timeout = package[5]
            if (timeout == 0):
                #Multiplexor: Envia el paquete a su cola correspondiente
                #print(package)
                for line in collectors_info:
                    plot_data = [package[0], package[4]]
                    #print(plot_data)
                    """print(line[0], package[1])
					print(line[1], package[2])
					print(line[2], package[3])"""
                    if (line[0] == package[1] and line[2] == package[2]
                            and line[1] == package[3]):
                        #print("entre")
                        line[4].acquire()
                        line[3].put(plot_data)
                        line[4].notify()
                        line[4].release()
            else:
                print("cliente caido")
                break
Example #4
0
 def setUp(self):
     self.hdd = HDD(10)
     self.fs = self.hdd.generate_file_system()
     self.instruction1 = InstructionIO()
     self.instruction2 = InstructionCPU()
     self.instruction3 = InstructionIO()
     self.instructionList1 = [self.instruction1, self.instruction2]
     self.instructionList2 = [
         self.instruction1, self.instruction2, self.instruction3
     ]
     self.program1 = Program(self.instructionList1, "AProgram")
     self.program2 = Program(self.instructionList2, "BProgram")
     self.fs.add_file("AProgram", self.program1)
     self.fs.add_file("BProgram", self.program2)
     self.file1 = self.fs.get_program("AProgram")
     self.file2 = self.fs.get_program("BProgram")
     self.pcb1 = PCB(0, 2, BlockHolder(self.file1))
     self.pcb2 = PCB(0, 3, BlockHolder(self.file2))
     self.memoryManager = MemoryManager()
     self.memoryManager.set_as_ca(FirstFit())
Example #5
0
class PlanningNode(object):
    """
    """

    def __init__(self, parent, builder, action, memory=None):
        self.parent = parent
        self.builder = builder
        self.action = action
        self.memory = MemoryManager()
        self.delta = MemoryManager()
        #self.cost = action.calc_cost()
        self.cost = 1
        self.g = calcG(self)
        self.h = 1

        if parent:
            self.memory.update(parent.memory)

        elif memory:
            self.memory.update(memory)

        action.touch(self.memory)
        action.touch(self.delta)

    def __eq__(self, other):
        if isinstance(other, PlanningNode):
            return self.delta == other.delta
        else:
            return False

    def __repr__(self):
        if self.parent:
            return "<PlanNode: '%s', cost: %s, p: %s>" % \
            (self.action.__class__.__name__,
                self.cost,
                self.parent.action.__class__.__name__)

        else:
            return "<PlanNode: '%s', cost: %s, p: None>" % \
            (self.action.__class__.__name__,
                self.cost)
Example #6
0
    def __init__(self, name=None):
        super(GoapAgent, self).__init__(name)
        self.memory = MemoryManager()
        self.planner = plan

        self.current_goal = None

        self.goals = []             # all goals this instance can use
        self.filters = []           # list of methods to use as a filter
        self.actions = []           # all actions this npc can perform
        self.plan = []              # list of actions to perform
                                    # '-1' will be the action currently used

        # this special filter will prevent time precepts from being stored
        self.filters.append(time_filter)
 def setUp(self):
     self.hdd = HDD(10)
     self.fs = self.hdd.generate_file_system()
     self.instruction1 = InstructionIO()
     self.instruction2 = InstructionCPU()
     self.instruction3 = InstructionIO()
     self.instructionList1 = [self.instruction1, self.instruction2]
     self.instructionList2 = [self.instruction1, self.instruction2, self.instruction3]
     self.program1 = Program(self.instructionList1, "AProgram")
     self.program2 = Program(self.instructionList2, "BProgram")
     self.fs.add_file("AProgram", self.program1)
     self.fs.add_file("BProgram", self.program2)
     self.file1 = self.fs.get_program("AProgram")
     self.file2 = self.fs.get_program("BProgram")
     self.pcb1 = PCB(0, 2, BlockHolder(self.file1))
     self.pcb2 = PCB(0, 3 , BlockHolder(self.file2))
     self.memoryManager = MemoryManager()
     self.memoryManager.set_as_ca(FirstFit())
Example #8
0
    def __init__(self, parent, builder, action, memory=None):
        self.parent = parent
        self.builder = builder
        self.action = action
        self.memory = MemoryManager()
        self.delta = MemoryManager()
        #self.cost = action.calc_cost()
        self.cost = 1
        self.g = calcG(self)
        self.h = 1

        if parent:
            self.memory.update(parent.memory)

        elif memory:
            self.memory.update(memory)

        action.touch(self.memory)
        action.touch(self.delta)
Example #9
0
 def requestMemory(self, functionName):
     neccesaryMemory = self.memoryMap[functionName]
     self.tempMemory = MemoryManager(
     int(neccesaryMemory[3]),
     int(neccesaryMemory[4]),
     int(neccesaryMemory[5]),
     int(neccesaryMemory[0]),
     int(neccesaryMemory[1]),
     int(neccesaryMemory[2]),
     self.counter.tempInt,
     self.counter.tempDouble,
     self.counter.tempBoolean,
     self.counter.localInt,
     self.counter.localDouble,
     self.counter.localBoolean)
     #memory added to counter
     self.counter.tempInt += int(neccesaryMemory[3])
     self.counter.tempDouble += int(neccesaryMemory[4])
     self.counter.tempBoolean += int(neccesaryMemory[5])
     self.counter.localInt += int(neccesaryMemory[0])
     self.counter.localDouble += int(neccesaryMemory[1])
     self.counter.localBoolean += int(neccesaryMemory[2])
 def __init__(self):
     self.variables = {}
     self.shadowed = {}
     self.Memory = MemoryManager()
     self.error = False
class VariableManager(object):
    def __init__(self):
        self.variables = {}
        self.shadowed = {}
        self.Memory = MemoryManager()
        self.error = False

    def __getitem__(self, var_name):
        return self.variables[var_name]

    def new_variable(self,
                     name,
                     _type,
                     line,
                     start_index=None,
                     end_index=None):
        if name in self.variables.keys():
            self.error = True
            original_var = self.variables[name]
            print(
                "Error! line {}\n"
                "Multiple declaration of a variable. {} already declared in {} line"
                .format(line, name, original_var.lineno),
                file=sys.stderr)
        else:
            if _type == "int":
                address = self.Memory.allocate(1)
                self.variables[name] = Int(lineno=line, address=address)
            elif _type == "tab":
                if start_index > end_index:
                    print("Error! line {}\n"
                          "Invalid range of tab {}\n".format(line, name),
                          file=sys.stderr)
                tab_size = end_index - start_index + 1
                address = self.Memory.allocate(tab_size)
                self.variables[name] = Tab(lineno=line,
                                           start_index=start_index,
                                           end_index=end_index,
                                           address=address)

            else:
                raise ValueError("No variable type ", _type)

    def new_iterator(self, name, line):
        if name in self.variables.keys():
            self.shadowed[name] = self.variables[name]
            self.variables.__delitem__(name)
            # raise Warning("might be a problem")
        address = self.Memory.allocate_iterator()
        self.variables[name] = Int(lineno=line,
                                   address=address,
                                   is_iterator=True)
        # is initialized too

    def get_iterator_address(self, name):
        iterator = self.variables[name]
        if not iterator.is_iterator:
            raise Exception("U ARE PICKING NOT AN ITERATOR")
        return iterator.address

    def delete_iterator(self, name):
        iterator = self.variables[name]
        if not iterator.is_iterator:
            raise Exception("U ARE DELETING A VAR NOT ITER !!!")
        self.Memory.deallocate_iterator(iterator.address)
        self.variables.__delitem__(name)
        if name in self.shadowed.keys():
            self.variables[name] = self.shadowed[name]

    def check_if_in_bounds(self, tab_name, index, line):
        tab = self[tab_name]
        if index < tab.start_index or tab.end_index < index:
            self.error = True
            print("Error! line {}\n"
                  "Index {} is out of bounds for tab '{}'\n".format(
                      line, index, tab_name),
                  file=sys.stderr)
            return False
        return True
Example #12
0
class GoapAgent(ObjectBase):
    """
    AI Agent

    inventories will be implemented using precepts and a list.
    currently, only one action running concurrently is supported.
    """

    # this will set this class to listen for this type of precept
    # not implemented yet
    interested = []
    idle_timeout = 30

    def __init__(self, name=None):
        super(GoapAgent, self).__init__(name)
        self.memory = MemoryManager()
        self.planner = plan

        self.current_goal = None

        self.goals = []             # all goals this instance can use
        self.filters = []           # list of methods to use as a filter
        self.actions = []           # all actions this npc can perform
        self.plan = []              # list of actions to perform
                                    # '-1' will be the action currently used

        # this special filter will prevent time precepts from being stored
        self.filters.append(time_filter)

    def add_goal(self, goal):
        self.goals.append(goal)

    def remove_goal(self, goal):
        self.goals.remove(goal)

    def add_action(self, action):
        self.actions.append(action)

    def remove_action(self, action):
        self.actions.remove(action)

    def filter_precept(self, precept):
        """
        precepts can be put through filters to change them.
        this can be used to simulate errors in judgement by the agent.
        """

        for f in self.filters:
            precept = f(precept)
            if precept is None:
                break

        return precept

    def process(self, precept):
        """
        used by the environment to feed the agent precepts.
        agents can respond by sending back an action to take.
        """
        precept = self.filter_precept(precept)

        if precept:
            debug("[agent] %s recv'd precept %s", self, precept)
            self.memory.add(precept)

        return self.next_action()

    def replan(self):
        """
        force agent to re-evaluate goals and to formulate a plan
        """

        # get the relevancy of each goal according to the state of the agent
        s = ( (g.get_relevancy(self.memory), g) for g in self.goals )
        s = [ g for g in s if g[0] > 0.0 ]
        s.sort(reverse=True)

        debug("[agent] goals %s", s)

        # starting for the most relevant goal, attempt to make a plan
        plan = []      
        for score, goal in s:
            tentative_plan = self.planner(self, self.actions,
                self.current_action, self.memory, goal)

            print score, goal, tentative_plan

            if tentative_plan:
                pretty = list(reversed(tentative_plan[:]))
                debug("[agent] %s has planned to %s", self, goal)
                debug("[agent] %s has plan %s", self, pretty)
                plan = tentative_plan
                break

        return plan

    @property
    def current_action(self):
        try:
            return self.plan[-1]
        except IndexError:
            return NullAction

    def running_actions(self):
        return self.current_action

    def next_action(self):
        """
        get the next action of the current plan
        """

        if self.plan == []:
            self.plan = self.replan()

        # this action is done, so return the next one
        if self.current_action.state == ACTIONSTATE_FINISHED:
            return self.plan.pop() if self.plan else self.current_action

        # this action failed somehow
        elif self.current_action.state == ACTIONSTATE_FAILED:
            raise Exception, "action failed, don't know what to do now!"

        # our action is still running, just run that
        elif self.current_action.state == ACTIONSTATE_RUNNING:
            return self.current_action
Example #13
0
import ply.yacc as yacc

from config import CONST_PREFIX, DYNAMIC_PREFIX, ITERATOR_PREFIX, STATIC_PREFIX
from generator.assign import assign
from generator.condition import (con_eq, con_ge, con_geq, con_le, con_leq,
                                 con_neq)
from generator.conditional import if_then, if_then_else
from generator.expression import div, minus, mod, plus, times, value
from generator.io import read, write
from generator.loop import do_while, for_downto, for_to, while_do
from lexer import tokens  # noqa: F401
from memory import MemoryManager

memory_manager = MemoryManager()


def p_program_declarations_commands(p):
    '''program : DECLARE declarations BEGIN commands END'''
    p[0] = p[4] + ['HALT']


def p_program_commands(p):
    '''program : BEGIN commands END'''
    p[0] = p[2] + ['HALT']


def p_declarations_declarations_id(p):
    '''declarations : declarations COMMA ID'''
    memory_manager.add_variable(p[3], p.lexer.lineno)