Ejemplo n.º 1
0
    def create_dcop(self, tasks, robots, is_hetero):
        variables = set()        
        functions = { }
        agents = [Agent(robot.id) for robot in robots]        

        for task in tasks:
            function = NodeFunction(task.id)
            function.setFunction(TabularFunction())
            functions[task.id] = function
            random.choice(agents).addNodeFunction(function)

        for robot in robots:        
            variable = NodeVariable(robot.id)            
            domain = []

            for task in tasks:
                if is_hetero and not robot.is_capable(task):
                    continue

                min_cost, min_pos = robot.get_best_cost(task, self._tasks_preconditions)
                if task.id in self._cost_table:
                    self._cost_table[task.id][robot.id] = (1/min_cost, min_pos)
                else:
                    self._cost_table[task.id] = {robot.id: (1/min_cost, min_pos)}

                #if robot can fit this task in its schedule
                if min_cost < float("inf"):
                    function = functions[task.id]
                    domain.append(function.function_id)                    
                    variable.addNeighbour(function)
                    function.addNeighbour(variable)

            #if robot can do atleast one task
            if len(domain) > 0:                
                domain = domain + [-func_id for func_id in domain]                                
                variable.addDomain(domain)
                variables.add(variable)
                agent = [agent for agent in agents if agent.agent_id == robot.id][0]
                agent.addNodeVariable(variable)    

        for _, function in functions.iteritems():
            size = len(function.params)                        
            if size > 0:
                func_id = function.function_id                                  
                all_values = list(product(*[(func_id, -func_id)] * size))          
                
                task = [t for t in tasks if t.id == function.function_id][0]                 
                for values in all_values:
                    func_args = [NodeArgument(v) for v in values]                                                                                                           
                    utility = self._calc_function_utility(function, func_args, deepcopy(task), robots)                                        
                    function.getFunction().addParametersCost(func_args, utility)
                    
        if len(variables) == 0:            
            return None

        dcop = COP_Instance(variables, list(functions.values()), agents)
        return dcop
Ejemplo n.º 2
0
    def backedges(self, stack, neighbours):
        acstack = stack
        node = acstack[-1]  #current node
        backedges = list()
        for s in acstack:  #scorro lo stack
            for n in neighbours:  #se tra i vicini ho nodi nello stack vuol dire che potevo venire da li aka backedge

                if s == n.getId() and s != acstack[-1] and s != acstack[
                        -2]:  #tutta via non devo considerare mio padre
                    backedges.append(str(node) + ";" + str(s))

                    node1 = self.getDcopNodeById(node)
                    node2 = self.getDcopNodeById(s)

                    nodefunction = NodeFunction(self.function_be_id)

                    fe = TabularFunction()
                    nodefunction.setFunction(fe)

                    node1.addNeighbour(nodefunction)
                    node2.addNeighbour(nodefunction)

                    nodefunction.addNeighbour(node1)
                    nodefunction.addNeighbour(node2)

                    argsOfFunction = list()
                    argsOfFunction.append(node1)
                    argsOfFunction.append(node2)

                    nodefunction.getFunction().setParameters(argsOfFunction)

                    for i in range(0, self.domain):
                        for j in range(0, self.domain):
                            t = (i, j)
                            cost = random.randint(1, 10)

                            nodefunction.getFunction().addParametersCost(
                                t, cost)
                    self.nodeFunctions.append(nodefunction)
                    self.function_be_id = self.function_be_id + 1
        return backedges
Ejemplo n.º 3
0
def create_DCop2():

    nodeVariables = list()
    nodeFunctions = list()

    agent1 = Agent(1)
    agent2 = Agent(2)
    agent3 = Agent(1)
    agent4 = Agent(2)
    agents = [agent1, agent2, agent3, agent4]

    nodeVariable1 = NodeVariable(1)
    nodeVariable2 = NodeVariable(2)
    nodeVariable3 = NodeVariable(3)
    nodeVariable4 = NodeVariable(4)

    nodeVariable1.addDomain([1, -1])
    nodeVariable2.addDomain([2, -2])
    nodeVariable3.addDomain([1, 2, -1, -2])
    nodeVariable4.addDomain([2, -2])

    nodefunction1 = NodeFunction(1)
    nodefunction2 = NodeFunction(2)

    nodefunction1.setFunction(TabularFunction())
    nodefunction2.setFunction(TabularFunction())

    nodeVariable1.addNeighbour(nodefunction1)
    nodeVariable2.addNeighbour(nodefunction2)
    nodeVariable3.addNeighbour(nodefunction1)
    nodeVariable3.addNeighbour(nodefunction2)
    nodeVariable4.addNeighbour(nodefunction2)

    nodefunction1.addNeighbour(nodeVariable1)
    nodefunction1.addNeighbour(nodeVariable3)
    nodefunction2.addNeighbour(nodeVariable2)
    nodefunction2.addNeighbour(nodeVariable3)
    nodefunction2.addNeighbour(nodeVariable4)

    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(-1), NodeArgument(-1)], -100000)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(-1), NodeArgument(1)], 15)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(1), NodeArgument(-1)], 10)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(1), NodeArgument(1)], -100000)

    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(-2),
         NodeArgument(-2),
         NodeArgument(-2)], -100000)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(-2), NodeArgument(-2),
         NodeArgument(2)], 2)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(-2), NodeArgument(2),
         NodeArgument(-2)], 16)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(2), NodeArgument(-2),
         NodeArgument(-2)], 17)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(2), NodeArgument(2),
         NodeArgument(-2)], -100000)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(-2), NodeArgument(2),
         NodeArgument(2)], -100000)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(2), NodeArgument(-2),
         NodeArgument(2)], -100000)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(2), NodeArgument(2),
         NodeArgument(2)], -100000)

    nodeVariables.append(nodeVariable1)
    nodeVariables.append(nodeVariable2)
    nodeVariables.append(nodeVariable3)
    nodeVariables.append(nodeVariable4)

    nodeFunctions.append(nodefunction1)
    nodeFunctions.append(nodefunction2)

    agent1.addNodeVariable(nodeVariable1)
    agent2.addNodeVariable(nodeVariable2)
    agent3.addNodeVariable(nodeVariable3)
    agent4.addNodeVariable(nodeVariable4)

    agent1.addNodeFunction(nodefunction1)
    agent2.addNodeFunction(nodefunction2)

    cop = COP_Instance(nodeVariables, nodeFunctions, agents)

    return cop
Ejemplo n.º 4
0
    def create_dcop(self, tasks, robots, is_hetero):
        variables = set()
        functions = {}
        agents = [Agent(robot.id) for robot in robots]

        # function == task
        # varibale  == robot

        for task in tasks:
            function = NodeFunction(task.id)
            function.setFunction(TabularFunction())
            functions[task.id] = function
            random.choice(agents).addNodeFunction(
                function)  #randomly choosing a robot and adding task to it

        for robot in robots:
            variable = NodeVariable(robot.id)
            domain = []

            for task in tasks:
                if is_hetero and not robot.is_capable(task):
                    continue
                # if len(functions[task.id].getNeighbour()) > 3:
                #     continue
                # print("neighbor count", len(functions[task.id].getNeighbour()))
                min_cost, min_pos = robot.get_best_cost(
                    task, self._tasks_preconditions)
                if task.id in self._cost_table:
                    self._cost_table[task.id][robot.id] = (1 / min_cost,
                                                           min_pos)
                else:
                    self._cost_table[task.id] = {
                        robot.id: (1 / min_cost, min_pos)
                    }

                # if robot can fit this task in its schedule
                if min_cost < float("inf"):
                    function = functions[task.id]
                    domain.append(function.function_id)
                    variable.addNeighbour(function)
                    function.addNeighbour(variable)

            # if robot can do atleast one task
            if len(domain) > 0:
                domain = domain + [-func_id for func_id in domain]
                variable.addDomain(domain)
                variables.add(variable)
                agent = [
                    agent for agent in agents if agent.agent_id == robot.id
                ][0]
                agent.addNodeVariable(variable)

        for _, function in functions.iteritems():
            size = len(function.params)
            if size > 0:
                func_id = function.function_id
                all_values = list(product(*[(func_id, -func_id)] * size))
                #[(1, 1, 1, 1), (1, 1, 1, -1), (1, 1, -1, 1), (1, 1, -1, -1), (1, -1, 1, 1), (1, -1, 1, -1), (1, -1, -1, 1), (1, -1, -1, -1), (-1, 1, 1, 1), (-1, 1, 1, -1), (-1, 1, -1, 1), (-1, 1, -1, -1), (-1, -1, 1, 1), (-1, -1, 1, -1), (-1, -1, -1, 1), (-1, -1, -1, -1)]
                task = [t for t in tasks if t.id == function.function_id][0]
                for values in all_values:
                    count = 0
                    func_args = []
                    for v in values:
                        func_args.append(NodeArgument(v))
                        # if v > 0:
                        #     count += 1
                    # if count >= 2:
                    #     function.getFunction().addParametersCost(func_args, -1000000000)
                    # else:
                    utility = self._calc_function_utility(
                        function, func_args, deepcopy(task), robots)
                    function.getFunction().addParametersCost(
                        func_args, utility)

                    # func_args = [NodeArgument(v) for v in values]
            # print("----------------- print result ----------------")
            #print(function.getFunction().toString())

        if len(variables) == 0:
            return None

        dcop = COP_Instance(variables, list(functions.values()), agents)
        return dcop
Ejemplo n.º 5
0
def create_DCop(infoGraphPathFile, nVariables, run):
    '''
        infoGraphPathFile: location where saving the factor graph
        nVariables: how many variables are there in Dcop instance?
        run: number of Dcop instance 
    '''
    
    '''
        configurations of variables's values in a function (10 values in domain):
        0 0, 0 1, 0 2, 1 0 ....
    '''
    arguments = [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9),
                 (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9),
                 (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9),
                 (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9),
                 (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9),
                 (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9),
                 (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (6, 9),
                 (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 7), (7, 8), (7, 9),
                 (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (8, 8), (8, 9),
                 (9, 0), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8), (9, 9),          
                ]
    
    '''
        list of variable in Dcop
    '''
    nodeVariables = list()
    '''
        list of function in Dcop
    '''
    nodeFunctions = list()
    '''
        list of agents in Dcop
        In this case there is only one agent
    '''
    agents = list()
    
    '''
        agent identifier
    '''    
    agent_id = 0
    '''
        variable identifier
    '''
    variable_id = 0
    '''
        function identifier
    '''
    function_id = 0
    '''
        variable identifier as parameter in the function
    '''
    variable_to_function = 0
    
    '''
        list of arguments in the function
    '''
    argumentsOfFunction = list()
    
    '''
       each variable has 10 values in its domain (0..9) 
    '''
    number_of_values = 10    
    
    '''
        only one agent controls all the variables and functions
    '''
    agent = Agent(agent_id)  
    
    nodeVariable = None
    nodefunction = None
    functionEvaluator = None     
    '''
        activation probability (random) to create an edge
    '''
    p = None
     
    '''
        create nVariables dcop variables
    '''
    for j in range(nVariables):
        '''
            create new NodeVariable with variable_id
        '''     
        nodeVariable = NodeVariable(variable_id)
        '''
            create the variable's domain with 10 values (0...9)
        '''
        nodeVariable.addIntegerValues(number_of_values)
        '''
            append this variable to Dcop's list of variable
        '''
        nodeVariables.append(nodeVariable)
            
        '''
           add the variable under its control
        '''
        agent.addNodeVariable(nodeVariable)
            
        variable_id = variable_id + 1  
  
    
    '''
        for each variable in Dcop's list
    '''
    for j in range(0, len(nodeVariables)):        
        '''
            for each variable close to variable j with bigger id 
        '''        
        for u in range(j+1, len(nodeVariables)):   
            '''
                generate a random value to enable the edge (if p <= 0.6)
            '''                
            p = random.random()    
            
            '''
                if activation prabability is less than 0.6
            '''    
            if (p < 0.6):    
                    '''
                        if you can create an edge between the two node
                    '''
                                           
                    '''
                       list of the arguments of the function 
                       each function is binary
                    '''          
                    argumentsOfFunction = list()
                                
                    nodefunction = NodeFunction(function_id)
                                
                    functionEvaluator = TabularFunction()  
                    nodefunction.setFunction(functionEvaluator)
                                
                    '''
                        add the function_id function to the neighbors 
                        of variable_to_function
                    '''    
                    for v in range(len(nodeVariables)):
                        if (((nodeVariables[v].getId()) == nodeVariables[j].getId())
                        
                            | ((nodeVariables[v].getId()) == nodeVariables[u].getId()) ):
                            '''
                                add this nodefunction to the actual nodevariable's neighbour
                            '''
                            nodeVariables[v].addNeighbour(nodefunction)
                                        
                            '''
                                add this variable as nodefunction's neighbour
                            '''
                            nodefunction.addNeighbour(nodeVariables[v])
                            '''
                                add the variable as an argument of the function
                            '''      
                            argumentsOfFunction.append(nodeVariables[v])
              
                    '''
                        add the function parameters
                    '''
                    nodefunction.getFunction().setParameters(argumentsOfFunction)         
                                
                    for tuple in arguments:
                        '''
                            generate a random uniform cost between 1 and 10
                        '''
                        cost = random.randint(1, 10)
                        '''
                            add to the cost function: [parameters -> cost]
                        '''        
                        nodefunction.getFunction().addParametersCost(tuple, cost)
                                
                    '''
                        add the function node
                    '''
                    nodeFunctions.append(nodefunction) 
                                
                    '''
                        add the function node to the agent
                    '''
                    agent.addNodeFunction(nodefunction)
                
                    '''
                        update the id of the next function node
                    '''
                    function_id = function_id + 1                              

    '''
        there is only one agent in this Dcop
    '''    
    agents.append(agent)
          
    string = ""         
    
    '''
        create the COP: list of variables, list of functions, agents
    '''                
    cop = COP_Instance(nodeVariables, nodeFunctions, agents)
    
    string = string + "How many agents?" + str(len(agents)) + "\n"
    
    '''
        create the factor graph report
    '''
    for agent in agents:
            string = string + "\nAgent Id: " + str(agent.getId()) + "\n\n"
            string = string + "How many NodeVariables?" + str(len(agent.getVariables())) + "\n"
            for variable in agent.getVariables():
                string = string + "Variable: " + str(variable.toString()) + "\n"
                
            string = string + "\n"
            
            for function in agent.getFunctions():
                string = string + "Function: " + str(function.toString()) + "\n"
                
            string = string + "\n"    
    
    for variable in nodeVariables:
            string = string + "Variable: " + str(variable.getId()) + "\n"
            for neighbour in variable.getNeighbour():
                string = string + "Neighbour: " + str(neighbour.toString()) + "\n"
            string = string + "\n"
    
    for function in nodeFunctions:
            string = string + "\nFunction: " + str(function.getId()) + "\n"
            string = string + "Parameters Number: " + str(function.getFunction().parametersNumber()) + "\n"
            for param in function.getFunction().getParameters():
                string = string + "parameter:" + str(param.toString()) + "\n"
                
            string = string + "\n\tCOST TABLE\n"
            
            string = string + str(function.getFunction().toString()) + "\n" 
    
    string = string + "\t\t\t\t\t\t\tFACTOR GRAPH\n\n" + str(cop.getFactorGraph().toString())
    
    info_graph_file = open(infoGraphPathFile + "ParallelConditioningID/FactorGraph/factor_graph_run_" + str(run) + ".txt", "w")
    info_graph_file.write(string)
    info_graph_file.write("\n")
    info_graph_file.close()   
    
    return cop  
Ejemplo n.º 6
0
def main():    
    '''
        invoke the parser that takes parameters from the command line
    '''
    args = getParser()
    '''
        How many iterations?
    '''
    nIterations = args.iterations
    '''
        How many instances? 
    '''   
    nIstances = args.instances
    '''
        number of variables in Dcop
    '''
    nVariables = args.variables
    '''
        max/min
    '''
    op = args.op
    '''
        location of MaxSum report
    '''
    reportMaxSum = args.reportMaxSum 
     
    '''
        location of FactorGraph report
    '''
    infoGraphPathFile = args.reportFactorGraph 
         
    '''
        location of Charts
    '''
    chartsFile = args.reportCharts    
     
    '''
        Constraint Optimization Problem
    '''
    cop = None 
     
    '''
        average of 50 instances of problem
    '''
    average = list()
     
    for i in range(nVariables + 1):
        average.append(0) 
         
    state = 0
     
    variables = list()
    functions = list()
    agents = list()
     
    agent = None
     
    finalAssignaments = list()
     
    oldAssignaments = list()
     
    core = None
    
    originalCop = None
    
    actualValue = 0

    '''
        list of all values of RUN for each iteration
    '''
    averageValues = list()
    
    iterations = list()
    
    iterationsInstances = list()
    
    averageValuesInstances= list()

    varSet = (0.1 * nVariables)
  	
    '''
	create directories
    '''
    if not os.path.exists("ParallelConditioningID/"):
	os.makedirs("ParallelConditioningID/")
	if not os.path.exists("ParallelConditioningID/Charts/"):
    	   os.makedirs("ParallelConditioningID/Charts/")
	if not os.path.exists("ParallelConditioningID/FactorGraph/"):
    	   os.makedirs("ParallelConditioningID/FactorGraph/")
    
    string = "Max Sum\t Average Conflicts\n"
 
    for run in range(nIstances): 
    
            averageValues = list()
            
            iterations = list()
            '''
                fileName of log (Iteration Conflicts AverageDifferenceLink)
                save on file Iteration Conflicts AverageDifferenceLink
            '''           
            finalAssignaments = list()
             
            oldAssignaments = list()
             
            for i in range(nVariables):
                finalAssignaments.append(0)
                oldAssignaments.append(0)
                         
            '''
                values of MaxSum for each iteration
            '''
            values = list()    
           
            '''
                create a new COP with a colored Graph and 
                save the factorgraph on file
            '''
            cop = create_DCop(infoGraphPathFile, nVariables, run) 
             
            i = 0
             
            going = False
             
            functions = cop.getNodeFunctions()
            variables = cop.getNodeVariables()
             
            '''
                repeat the algorithm for 50 times
                every exec set the value of variable
            '''
            while((len(variables) > 0) & (len(functions) > 0)):
                '''
                    if it isn't the first exec of MaxSum,
                    change the factor graph and repeat the algorithm
                '''
                if(going == True):                    
                    '''
                        the agent of the cop
                    '''
                    agent = (core.getCop().getAgents())[0]
                     
                    '''
                        the variables of the cop
                    '''
                    variables = core.getCop().getNodeVariables()
                     
                    '''
                        the functions of the cop
                    '''
                    functions = core.getCop().getNodeFunctions()
                                       
                    variablesToRemove = list()                   
                                    
                    w = 0
                    
                    '''
                        choose variables in order by ID
                    '''
                    while((w < varSet) & (w < len(variables))):
                        variablesToRemove.append(variables[w])
                        w = w + 1 
                    
                    for j in range(len(variablesToRemove)):     
                        '''
                            state of variable i
                        '''
                        state = variablesToRemove[j].getStateArgument()
                         
                        print('state of variable:', variablesToRemove[j].toString(), state.getValue())
                        
                        index = getIndex(originalCop,variablesToRemove[j])
                        '''
                            save the value of the variable
                        '''
                        finalAssignaments[index] = state.getValue()
                         
                        oldAssignaments[index] = finalAssignaments[index]
                    
                    
                    for var in variablesToRemove:
                        '''
                            remove the variable on the agent
                        '''
                        agent.removeNodeVariable(var)
                     
                    for var in variablesToRemove:
                        '''
                            neighbours of variable  
                        '''
                        neighbours = var.getNeighbour()
                         
                        for function in neighbours:
                            functions.remove(function)
                            agent.removeNodeFunction(function)
                                                                                 
                        '''
                            remove the variable from the list
                        '''
                        variables.remove(var)
                             
                        for variable in variables:
                             
                            n1 = set(neighbours)
                            n2 = set(variable.getNeighbour())
                             
                            if((len(set(n1).intersection(n2))) > 0 ):
                                
                                '''
                                    intersection of neighbours
                                '''
                                inter = (set(n1).intersection(n2))
                                
                                while(len(inter) > 0):
                                
                                    func = inter.pop()
                                    
                                    '''
                                        list of the arguments of the function
                                    '''
                                    argumentsOfFunction = list()
                                     
                                    funId = 0
                    
                                    '''
                                        there is at least a function
                                    '''
                                    if((len(functions)) > 0):
                                         funId = ((functions[len(functions) - 1]).getId()) + 1   
                                    else:
                                         funId = 0
                                    
                                    '''
                                        creates an unary function linked to the variable
                                    '''
                                    nodefunction = NodeFunction(funId)
                                     
                                    functionevaluator = TabularFunction()  
                                    nodefunction.setFunction(functionevaluator) 
                                     
                                    '''
                                        add this nodefunction to the actual nodevariable's neighbour
                                    '''
                                    variable.addNeighbour(nodefunction)         
                                    '''
                                        add this variable as nodefunction's neighbour
                                    '''
                                    nodefunction.addNeighbour(variable)
                                     
                                    '''
                                        add the variable as an argument of the function
                                    '''    
                                    argumentsOfFunction.append(variable)
                                    
                                    costTable = (func.getFunction()).getCostTable()
                                    
                                    cost = 0
                                    
                                    '''
                                        state of variableToRemove
                                    '''
                                    state = var.getStateArgument()
                                    
                                    index = (func.getFunction()).getParameterPosition(var)
                                        
                                    '''
                                        create the unary function
                                    '''      
                                    for j in range(0, variable.size()):
                                        
                                        t = (j)
                                        
                                        if(index == 0):     
                                            cost = costTable[(state.getValue(),j)]
                                        else:
                                            cost = costTable[(j,(state.getValue()))]
                                        '''
                                            add to the cost function: [parameters -> cost]
                                        '''
                                        nodefunction.getFunction().addParametersCost(t, cost) 
                                        
                                    '''
                                        add the neighbors of the function node
                                    '''
                                    nodefunction.getFunction().setParameters(argumentsOfFunction)
                                     
                                    '''
                                        add the function node
                                    '''
                                    functions.append(nodefunction) 
                                     
                                    '''
                                        add the function node to the agent
                                    '''
                                    agent.addNodeFunction(nodefunction)
        
                                variable.removeNeighbours(neighbours)
                                 
  
                    if((len(variables) > 0) & (len(functions) > 0)):
                    
                        agents = list() 
                             
                        agents.append(agent)    
                                 
                        cop = COP_Instance(variables, functions, agents)
                             
                        i = i + varSet
 
                     
                if((len(variables) > 0) & (len(functions) > 0)):
                    '''
                        create new MaxSum instance (max/min)
                    '''           
                    core = MaxSum(cop, op) 
                    '''
                        update only at end?
                    '''
                    core.setUpdateOnlyAtEnd(False)    
         
                    core.setIterationsNumber(nIterations)
                             
                    start_time = time.time()          
                                                                     
                    '''
                        invoke the method that executes the MaxSum algorithm
                    '''
                    core.solve_complete()
                    
                    values = core.getValues()

                    elapse_time = time.time() - start_time
                    print('MaxSum elapse_time:', elapse_time)  
                     
                    going = True 
                     
                    if(i == 0):
                        '''
                             create a copy of cop
                        '''
                        originalCop = deepcopy(core.getCop())
                         
                        oldVariables = originalCop.getNodeVariables()
                         
                        for k in range(len(oldVariables)):
                            oldAssignaments[k] = oldVariables[k].getStateIndex()
                                         
                                
                    actualValue = calculateActualValue(originalCop,oldAssignaments) 
                    
                    averageValues.append(actualValue)
                    
                    iterations.append(len(values))
                     
            if((len(variables) > 0) & (len(functions) == 0)):
                '''
                    the variables of the cop
                '''
                variables = core.getCop().getNodeVariables()

                '''
                    remaining variables to set
                '''
                index = (nVariables - i) - 1
                
                k = 0   
                
                j = 1

                while(j < ((index / varSet) + 1)):   
                
                    while(k < (varSet * j)):
                        '''
                            state of variable i
                        '''
                        state = (variables[k]).getStateArgument() 
                        '''
                            save the value of the variable
                        '''
                        finalAssignaments[i] = state.getValue()
                         
                        oldAssignaments[i] = finalAssignaments[i]

                        i = i + k
                        
                        k = k + 1
                        
                    actualValue = calculateActualValue(originalCop,oldAssignaments)
                         
                    averageValues.append(actualValue)
                        
                    iterations.append(len(values))
                    
                    j = j + 1
 
            for i in range(len(iterations)):
                if(i > 0):
                    iterations[i] = iterations[i] + iterations[i-1]
                    
            averageValuesInstances.append(averageValues)
            iterationsInstances.append(iterations)
             
            # draw the chart 
            # x axis: number of MaxSum exec
            # y axis: conflicts
            x = iterations
             
            '''
                x axis: number of MaxSum exec
            '''
            y = averageValues
            pl.title('Cost / Iterations chart')
            pl.xlabel('Iterations')
            pl.ylabel('Cost')
            pl.plot(x, y)
            pl.savefig(chartsFile + "ParallelConditioningID/Charts/Chart_RUN_" + str(run) + ".png")
            pl.close()
      
    sumIterations = [sum(x) for x in zip(*iterationsInstances)] 
    sumValues = [sum(x) for x in zip(*averageValuesInstances)] 
    
    for i in range(len(sumIterations)):
        sumIterations[i] = sumIterations[i] / nIstances
        
    for i in range(len(sumValues)):
        sumValues[i] = sumValues[i] / nIstances
    
    # draw the chart 
    # x axis: number of MaxSum exec
    # y axis: conflicts
    x = sumIterations
             
    '''
        x axis: number of MaxSum exec
    '''
    y = sumValues
    pl.title('Cost / Iterations chart')
    pl.xlabel('Iterations')
    pl.ylabel('Cost')
    pl.plot(x, y)
    #pl.show()
    pl.savefig(chartsFile + "ParallelConditioningID/Charts/AverageAllInstances.png")
    pl.close()    
    
    string = 'Iteration\tConflict\n'
    
    for i in range(len(sumIterations)):
        string = string + str(sumIterations[i]) + '\t\t' + str(sumValues[i]) + '\n'
            
    output_file = open(infoGraphPathFile + "ParallelConditioningID/FactorGraph/reportIterations.txt", "w")
    output_file.write(string)
    output_file.write("\n")
    output_file.close()
Ejemplo n.º 7
0
def create_DCop():
    nodeVariables = list()
    nodeFunctions = list()

    agent1 = Agent(1)
    agent2 = Agent(2)
    agents = [agent1, agent2]

    nodeVariable1 = NodeVariable(1)
    nodeVariable2 = NodeVariable(2)

    nodeVariable1.addDomain([1, -1])  # robot1 can do task 1 or -1
    nodeVariable2.addDomain([1, -1])

    nodefunction1 = NodeFunction(1)

    nodefunction1.setFunction(TabularFunction())

    nodeVariable1.addNeighbour(nodefunction1)
    nodeVariable2.addNeighbour(nodefunction1)

    nodefunction1.addNeighbour(nodeVariable1)
    nodefunction1.addNeighbour(nodeVariable2)

    # NodeArgument is a possible NodeVariable's value
    # function is task, variable is robot; agent=Agent controls variables in a COP problem instance.
    # Agent can control one or more variables or functions
    # taks1 -> robot1
    # task2 -> robot1, robot2
    # task3 -> robot2

    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(-1), NodeArgument(-1)], -100000)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(-1), NodeArgument(1)], 0.0160744478407)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(1), NodeArgument(-1)], 0.0140725087427)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(1), NodeArgument(1)], 0.0012481234778)

    print("----------------- print result ----------------")
    print(nodefunction1.getFunction().toString())

    nodeVariables.append(nodeVariable1)
    nodeVariables.append(nodeVariable2)

    nodeFunctions.append(nodefunction1)

    agent1.addNodeVariable(nodeVariable1)
    agent2.addNodeVariable(nodeVariable2)

    agent1.addNodeFunction(nodefunction1)
    # agent2.addNodeFunction(nodefunction1)

    cop = COP_Instance(nodeVariables, nodeFunctions, agents)

    return cop
Ejemplo n.º 8
0
def create_DCop2():

    nodeVariables = list()
    nodeFunctions = list()

    agent1 = Agent(1)
    agent2 = Agent(2)
    agent3 = Agent(3)
    agent4 = Agent(4)
    agents = [agent1, agent2, agent3, agent4]

    nodeVariable1 = NodeVariable(1)
    nodeVariable2 = NodeVariable(2)
    nodeVariable3 = NodeVariable(3)
    nodeVariable4 = NodeVariable(4)

    nodeVariable1.addDomain([1, -1])  #robot1 can do task 1 or -1
    nodeVariable2.addDomain([2, -2])
    nodeVariable3.addDomain([1, 2, -1, -2])
    nodeVariable4.addDomain([2, -2])

    nodefunction1 = NodeFunction(1)
    nodefunction2 = NodeFunction(2)

    nodefunction1.setFunction(TabularFunction())
    nodefunction2.setFunction(TabularFunction())

    nodeVariable1.addNeighbour(nodefunction1)
    nodeVariable2.addNeighbour(nodefunction2)
    nodeVariable3.addNeighbour(nodefunction1)
    nodeVariable3.addNeighbour(nodefunction2)
    nodeVariable4.addNeighbour(nodefunction2)

    nodefunction1.addNeighbour(nodeVariable1)
    nodefunction1.addNeighbour(nodeVariable3)
    nodefunction2.addNeighbour(nodeVariable2)
    nodefunction2.addNeighbour(nodeVariable3)
    nodefunction2.addNeighbour(nodeVariable4)

    #NodeArgument is a possible NodeVariable's value
    #function is task, variable is robot; agent=Agent controls variables in a COP problem instance.
    #Agent can control one or more variables or functions
    #taks1 -> robot1, robot3
    #task2 -> robot2, robot3, robot4
    '''
    f1:
        best case with r3 -> line4, 22
        best case without r3 -> line1, 20
    f2:
        best case with r3 -> line8 58
        best case without r3 -> line7 57
    r3 making decision:
        r3 chooses f1 -> 22 + 57 = 79 
        r3 chooses f2 -> 20 + 58 = 78
       ==>r3 chooses f1 
    '''
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(-1), NodeArgument(-1)], 20)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(-1), NodeArgument(1)], 15)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(1), NodeArgument(-1)], 10)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(1), NodeArgument(1)], 22)

    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(-2),
         NodeArgument(-2),
         NodeArgument(-2)], 51)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(-2), NodeArgument(-2),
         NodeArgument(2)], 52)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(-2), NodeArgument(2),
         NodeArgument(-2)], 53)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(2), NodeArgument(-2),
         NodeArgument(-2)], 54)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(2), NodeArgument(2),
         NodeArgument(-2)], 55)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(-2), NodeArgument(2),
         NodeArgument(2)], 56)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(2), NodeArgument(-2),
         NodeArgument(2)], 57)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(2), NodeArgument(2),
         NodeArgument(2)], 58)

    print("Node function 1 values: ")
    print(nodefunction1.getFunction().getCostValues())
    print("Node function 2 values: ")
    print(nodefunction2.getFunction().getCostValues())

    nodeVariables.append(nodeVariable1)
    nodeVariables.append(nodeVariable2)
    nodeVariables.append(nodeVariable3)
    nodeVariables.append(nodeVariable4)

    nodeFunctions.append(nodefunction1)
    nodeFunctions.append(nodefunction2)

    agent1.addNodeVariable(nodeVariable1)
    agent2.addNodeVariable(nodeVariable2)
    agent3.addNodeVariable(nodeVariable3)
    agent4.addNodeVariable(nodeVariable4)

    agent1.addNodeFunction(nodefunction1)
    agent2.addNodeFunction(nodefunction2)

    cop = COP_Instance(nodeVariables, nodeFunctions, agents)

    return cop
Ejemplo n.º 9
0
def create_DCop(infoGraphPathFile, nVariables, run):
    '''
        infoGraphPathFile: location where saving the factor graph
        This function creates a colored graph with one agent that controls
        variables and functions. Each variable has 3 values in its domain (0,1,2).
        For each variable there is a a fictitious function useful for 
        breaking the symmetry of colorability.
        nVariables: how many variables are there in Dcop instance?
        run: number of Dcop instance 
    '''
    '''
        configurations of variables's values in a function:
        0 0, 0 1, 0 2, 1 0 ....
    '''
    arguments = [0, 0, 0, 1, 0, 2, 1, 0, 1, 1, 1, 2, 2, 0, 2, 1, 2, 2]
    '''
        list of variable in Dcop
    '''
    nodeVariables = list()
    '''
        list of function in Dcop
    '''
    nodeFunctions = list()
    '''
        list of agents in Dcop
        In this case there is only one agent
    '''
    agents = list()
    '''
        agent identifier
    '''
    agent_id = 0
    '''
        variable identifier
    '''
    variable_id = 0
    '''
        function identifier
    '''
    function_id = 0
    '''
        variable identifier as parameter in the function
    '''
    variable_to_function = 0
    '''
        list of arguments in the function
    '''
    argumentsOfFunction = list()
    '''
       each variable has 3 values in its domain (0..2) 
    '''
    number_of_values = 3
    '''
        only one agent controls all the variables and functions
    '''
    agent = Agent(agent_id)

    nodeVariable = None
    nodefunction = None
    functionEvaluator = None
    '''
        it is True if it is possible to create an edge between node j and node u
     '''
    found = False
    '''
        it is True if it is possible to color the node u
    '''
    colored = False
    '''
        if It is true you can create an edge with the next variable (bigger id)
        else you can't do it
    '''
    k = 0
    '''
        activation probability (random) to create an edge
    '''
    p = None
    '''
        create nVariables dcop variables
    '''
    for j in range(nVariables):
        '''
            create new NodeVariable with variable_id
        '''
        nodeVariable = NodeVariable(variable_id)
        '''
            create the variable's domain with 3 values (0,1,2)
        '''
        nodeVariable.addIntegerValues(number_of_values)
        '''
            append this variable to Dcop's list of variable
        '''
        nodeVariables.append(nodeVariable)
        '''
           add the variable under its control
        '''
        agent.addNodeVariable(nodeVariable)

        variable_id = variable_id + 1
    '''
        for each variable in Dcop's list
    '''
    for j in range(0, len(nodeVariables)):
        '''
            if the variable j has not taken on a color
        '''
        if (((nodeVariables[j]).getColor()) == -1):
            '''
                choose a random color between 0 and 2
            '''
            val = random.randint(0, 100)
            if (val < 50):
                '''
                    choose 0
                '''
                (nodeVariables[j]).setColor(0)
            elif (val >= 50 & val < 70):
                '''
                    choose 1
                '''
                (nodeVariables[j]).setColor(1)
            else:
                '''
                    choose 2
                '''
                (nodeVariables[j]).setColor(2)
        ''''
            if it is the first node variable
            it can create an edge with the next node.
            So there is no cycle
        '''
        if ((nodeVariables[j]).getId() == 0):
            k = j + 1
        else:
            '''
                else you can't create an edge with the next node variable, to 
                avoid cycles
            '''
            k = j + 2
        '''
            for each variable close to variable j with bigger id 
        '''
        for u in range(k, len(nodeVariables)):

            color_neighbour_j = list()
            '''
                neighbors can assume one in three color types (0,1,2)
            '''
            color_neighbour_j.append(0)
            color_neighbour_j.append(1)
            color_neighbour_j.append(2)
            '''
                remove the variable j's color
            '''
            color_neighbour_j.remove(nodeVariables[j].getColor())
            '''
                function nodes close to the variable j
            '''
            function_neighbour_j = (nodeVariables[j]).getNeighbour()
            '''
                remove the colors of the neighbors at the variable j
            '''
            for function in function_neighbour_j:
                for variable in function.getNeighbour():
                    if (not ((variable.getId())
                             == (nodeVariables[j].getId()))):
                        '''
                                if you can remove a color
                            '''
                        if (len(color_neighbour_j) > 0):
                            index = search_Index(color_neighbour_j,
                                                 variable.getColor())
                            if (index > -1):
                                color_neighbour_j.remove(
                                    color_neighbour_j[index])

            found = False
            colored = False
            '''
                generate a random value to enable the edge (if p > 50)
            '''
            p = random.randrange(0, 100)
            '''
                if the two nodes have different colors
            '''
            if ((not ((nodeVariables[j].getColor())
                      == (nodeVariables[u].getColor()))) & (p > 50)):
                '''
                    if variable u doesn't have a color and variable j has neighbours
                '''
                if (((nodeVariables[u]).getColor()) == -1):
                    '''
                        in variable j has 2 available colors
                    '''
                    if (len(color_neighbour_j) == 2):
                        index = 0
                        '''
                            choose the color index to select, choose a color from those left
                        '''
                        val = random.randint(0, 100)
                        if (val < 50):
                            index = 0
                        else:
                            index = 1
                        '''
                            set the color based on the index choosen
                        '''
                        (nodeVariables[u]).setColor(color_neighbour_j[index])
                        color_neighbour_j.remove(color_neighbour_j[index])
                        '''
                            it is possible to color node u
                        '''
                        colored = True
                    elif (len(color_neighbour_j) == 1):
                        '''
                            if there is only one available color for variable u
                        '''
                        (nodeVariables[u]).setColor(color_neighbour_j[0])
                        color_neighbour_j.remove(color_neighbour_j[0])
                        '''
                            it is possible to color node u
                        '''
                        colored = True
                elif (((nodeVariables[u].getColor()) > -1) & (p > 50)):

                    if (len(function_neighbour_j) == 0):

                        color_neighbour_u = list()
                        '''
                            neighbors can assume one in three color types (0,1,2)
                        '''
                        color_neighbour_u.append(0)
                        color_neighbour_u.append(1)
                        color_neighbour_u.append(2)
                        '''
                            the color of node u can not be used
                        '''
                        color_neighbour_u.remove(nodeVariables[u].getColor())

                        function_neighbour_u = (
                            nodeVariables[u]).getNeighbour()
                        '''
                            remove the colors of the neighbors at the variable u
                        '''
                        for function in function_neighbour_u:
                            for variable in function.getNeighbour():
                                if (not ((variable.getId())
                                         == (nodeVariables[u].getId()))):
                                    if (len(color_neighbour_u) > 0):
                                        index = search_Index(
                                            color_neighbour_u,
                                            variable.getColor())
                                        if (index > -1):
                                            color_neighbour_u.remove(
                                                color_neighbour_u[index])
                        '''
                            if node u has at least an available color
                        '''
                        if (len(color_neighbour_u) > 0):
                            for color in color_neighbour_u:
                                '''
                                    if there is the color in the available colors of variable j
                                '''
                                if (color == (nodeVariables[j].getColor())):
                                    '''
                                        you can create an adge between node j and node u
                                        because they have different colors and their neighbours
                                        don't use color
                                    '''
                                    found = True

                    elif ((len(function_neighbour_j) > 0)):

                        color_neighbour_u = list()
                        '''
                            neighbors can assume one in three color types (0,1,2)
                        '''
                        color_neighbour_u.append(0)
                        color_neighbour_u.append(1)
                        color_neighbour_u.append(2)
                        '''
                            the color of node u can not be used
                        '''
                        color_neighbour_u.remove(nodeVariables[u].getColor())

                        function_neighbour_u = (
                            nodeVariables[u]).getNeighbour()
                        '''
                            remove the colors of the neighbors at the variable u
                        '''
                        for function in function_neighbour_u:
                            for variable in function.getNeighbour():
                                if (not ((variable.getId())
                                         == (nodeVariables[u].getId()))):
                                    if (len(color_neighbour_u) > 0):
                                        index = search_Index(
                                            color_neighbour_u,
                                            variable.getColor())
                                        if (index > -1):
                                            color_neighbour_u.remove(
                                                color_neighbour_u[index])
                        '''
                            if node u and node j have at least an available color
                        '''
                        if ((len(color_neighbour_u) > 0) &
                            (len(color_neighbour_j)) > 0):
                            found_j = False
                            found_u = False
                            '''
                                if color j is available in color_u
                            '''
                            for color in color_neighbour_u:
                                if ((nodeVariables[j].getColor()) == color):
                                    found_j = True
                            '''
                                if color u is available in color_j
                            '''
                            for color in color_neighbour_j:
                                if (color == (nodeVariables[u].getColor())):
                                    found_u = True
                            '''
                                you can create an edge between the two variables
                            '''
                            if ((found_j == True) & (found_u == True)):
                                found = True
                            else:
                                found = False

                if ((colored == True) | (found == True)):
                    '''
                        if you can create an edge between the two node
                    '''
                    '''
                       list of the arguments of the function 
                       each function is binary
                    '''
                    argumentsOfFunction = list()

                    nodefunction = NodeFunction(function_id)

                    functionEvaluator = TabularFunction()
                    nodefunction.setFunction(functionEvaluator)
                    '''
                        id variable in the function
                    '''
                    variable_to_function = nodeVariables[j].getId()
                    '''
                        add the function_id function to the neighbors 
                        of variable_to_function
                    '''
                    for v in range(len(nodeVariables)):
                        if nodeVariables[v].getId() == variable_to_function:
                            '''
                                add this nodefunction to the actual nodevariable's neighbour
                            '''
                            nodeVariables[v].addNeighbour(nodefunction)
                            '''
                                add this variable as nodefunction's neighbour
                            '''
                            nodefunction.addNeighbour(nodeVariables[v])
                            '''
                                add the variable as an argument of the function
                            '''
                            argumentsOfFunction.append(nodeVariables[v])
                    '''
                        id variable in the function
                    '''
                    variable_to_function = nodeVariables[u].getId()
                    '''
                        add the function_id function to the neighbors of variable_to_function
                    '''
                    for v in range(len(nodeVariables)):
                        if nodeVariables[v].getId() == variable_to_function:
                            '''
                                add the function as close to the variable
                            '''
                            nodeVariables[v].addNeighbour(nodefunction)
                            '''
                                add this variable as nodefunction's neighbour
                            '''
                            nodefunction.addNeighbour(nodeVariables[v])
                            '''
                                add the variable as an argument of the function
                            '''
                            argumentsOfFunction.append(nodeVariables[v])
                    '''
                        add the function parameters
                    '''
                    nodefunction.getFunction().setParameters(
                        argumentsOfFunction)

                    for index in range(0, 9):
                        parameters_list = list()
                        for v in range(0, 2):
                            '''
                                insert the function parameters: 0 0 ,0 1, 0 2 ...
                            '''
                            if v == 0:
                                parameters_list.insert(
                                    v, NodeArgument(arguments[(index * 2)]))
                            else:
                                parameters_list.insert(
                                    v,
                                    NodeArgument(arguments[(index * 2) + 1]))
                        '''
                            if the colorability constraint is not respected
                        '''
                        if (parameters_list[0].equals(parameters_list[1])):
                            cost = -1
                        else:
                            '''
                                if it is respected
                            '''
                            cost = 0
                        '''
                            add to the cost function: [parameters -> cost]
                        '''
                        nodefunction.getFunction().addParametersCost(
                            parameters_list, cost)
                    '''
                        add the function node
                    '''
                    nodeFunctions.append(nodefunction)
                    '''
                        add the function node to the agent
                    '''
                    agent.addNodeFunction(nodefunction)
                    '''
                        update the id of the next function node
                    '''
                    function_id = function_id + 1
    '''
        for each variable add a fictitious function
        to break symmetry. A fictitious function is
        an unary function (0, 1, 2) with a domain
        built with very small random numbers
    '''
    for variable in nodeVariables:
        '''
            creates an unary function linked to the variable
        '''
        nodefunction = NodeFunction(function_id)

        functionevaluator = TabularFunction()
        nodefunction.setFunction(functionevaluator)
        '''
            list of the arguments of the function
        '''
        argumentsOfFunction = list()
        '''
            Id of the variable associated with the function
        '''
        variable_to_function = variable.getId()
        '''
            add the function_id function to the neighbors 
            of variable_to_function
        '''
        for v in range(len(nodeVariables)):
            if nodeVariables[v].getId() == variable_to_function:
                '''
                    add this nodefunction to the actual nodevariable's neighbour
                '''
                nodeVariables[v].addNeighbour(nodefunction)
                '''
                    add this variable as nodefunction's neighbour
                '''
                nodefunction.addNeighbour(nodeVariables[v])
                '''
                    add the variable as an argument of the function
                '''
                argumentsOfFunction.append(nodeVariables[v])

        parameters_list = list()
        '''
            create the fictitious functions
        '''
        for i in range(0, 3):

            parameters_list = list()

            parameters_list.append(NodeArgument(i))
            '''
                assigns a small random value to each value of the domain
            '''
            cost = random.random() / (10 ^ 6)
            '''
                add to the cost function: [parameters -> cost]
            '''
            nodefunction.getFunction().addParametersCost(parameters_list, cost)
        '''
            add the neighbors of the function node
        '''
        nodefunction.getFunction().setParameters(argumentsOfFunction)
        '''
            add the function node
        '''
        nodeFunctions.append(nodefunction)
        '''
            add the function node to the agent
        '''
        agent.addNodeFunction(nodefunction)
        '''
            update the id of the next function node
        '''
        function_id = function_id + 1
    '''
        there is only one agent in this Dcop
    '''
    agents.append(agent)

    string = ""
    '''
        create the COP: list of variables, list of functions, agents
    '''
    cop = COP_Instance(nodeVariables, nodeFunctions, agents)

    string = string + "How many agents?" + str(len(agents)) + "\n"
    '''
        create the factor graph report
    '''
    for agent in agents:
        string = string + "\nAgent Id: " + str(agent.getId()) + "\n\n"
        string = string + "How many NodeVariables?" + str(
            len(agent.getVariables())) + "\n"
        for variable in agent.getVariables():
            string = string + "Variable: " + str(variable.toString()) + "\n"

        string = string + "\n"

        for function in agent.getFunctions():
            string = string + "Function: " + str(function.toString()) + "\n"

        string = string + "\n"

    for variable in nodeVariables:
        string = string + "Variable: " + str(variable.getId()) + "\n"
        for neighbour in variable.getNeighbour():
            string = string + "Neighbour: " + str(neighbour.toString()) + "\n"
        string = string + "\n"

    for function in nodeFunctions:
        string = string + "\nFunction: " + str(function.getId()) + "\n"
        string = string + "Parameters Number: " + str(
            function.getFunction().parametersNumber()) + "\n"
        for param in function.getFunction().getParameters():
            string = string + "parameter:" + str(param.toString()) + "\n"

        string = string + "\n\tCOST TABLE\n"

        string = string + str(function.getFunction().toString()) + "\n"

    string = string + "\t\t\t\t\t\t\tFACTOR GRAPH\n\n" + str(
        cop.getFactorGraph().toString())

    info_graph_file = open(
        infoGraphPathFile + "FactorGraph/factor_graph_run_" + str(run) +
        ".txt", "w")
    info_graph_file.write(string)
    info_graph_file.write("\n")
    info_graph_file.close()

    return cop
Ejemplo n.º 10
0
def getConnectedFactorGraph(num_nodes):
    nodeVariables = list()
    nodeFunctions = list()
    agents = list()

    edges = 0

    variable_id = 0
    function_id = 0
    agent_id = 0

    arguments = [0, 0, 0, 1, 0, 2, 1, 0, 1, 1, 1, 2, 2, 0, 2, 1, 2, 2]

    agent = Agent(agent_id)

    #creo i nodi variabile
    for i in range(0, num_nodes):
        nodeVariable = NodeVariable(variable_id)
        nodeVariable.addIntegerValues(3)

        val = random.randint(0, 100)
        if (val < 34):
            nodeVariable.setColor(0)
        if (val >= 34 and val < 66):
            nodeVariable.setColor(1)
        else:
            nodeVariable.setColor(2)

        nodeVariables.append(nodeVariable)
        agent.addNodeVariable(nodeVariable)

        variable_id = variable_id + 1

    #creo matrice di adiacenza del grafo
    adjmatrix = numpy.zeros((num_nodes, num_nodes))
    for i in range(0, num_nodes):
        for j in range(0, num_nodes):
            if j > i:
                adjmatrix[i][j] = 1
                edges = edges + 1  #numero di archi da fare
            else:
                adjmatrix[i][j] = 0

    #scorri nella adjmatrix e da li fai i nodi

    for i in range(0, num_nodes):
        for j in range(0, num_nodes):
            if adjmatrix[i][j] == 1:
                nodefunction = NodeFunction(function_id)
                functionEvaluator = TabularFunction()
                nodefunction.setFunction(functionEvaluator)

                nodeVariables[i].addNeighbour(nodefunction)
                nodeVariables[j].addNeighbour(nodefunction)

                nodefunction.addNeighbour(nodeVariables[i])
                nodefunction.addNeighbour(nodeVariables[j])

                argsOfFunction = list()
                argsOfFunction.append(nodeVariables[i])
                argsOfFunction.append(nodeVariables[j])
                nodefunction.getFunction().setParameters(argsOfFunction)

                for index in range(0, 9):
                    param = list()
                    for v in range(0, 2):
                        if v == 0:
                            param.insert(
                                v,
                                NodeArgument(arguments[(index *
                                                        2)]).getValue())
                        else:
                            param.insert(
                                v,
                                NodeArgument(arguments[(index * 2) +
                                                       1]).getValue())
                    if (param[0].equals(param[1])):
                        cost = -1
                    else:
                        cost = 0
                    nodefunction.getFunction().addParametersCost(param, cost)

                nodeFunctions.append(nodefunction)
                agent.addNodeFunction(nodefunction)
                function_id = function_id + 1

    agents.append(agent)

    cop = COP_Instance(nodeVariables, nodeFunctions, agents)
    return cop
Ejemplo n.º 11
0
def loadDcopFromFile1(file):
    nodevariables = list()
    nodefunctions = list()
    agents = list()

    domain = 0
    agent_id = 0
    variable_id = 0
    function_id = 0

    f = open(file, "r")
    for line in f:
        if line.startswith('AGENT'):
            splitted = line.split(" ")
            agent_id = int(splitted[1])
            agent = Agent(agent_id)
            agents.append(agent)

        if line.startswith('VARIABLE'):
            splitted = line.split(" ")
            variable_id = int(splitted[1])
            agent_id = int(splitted[2])
            domain = int(splitted[3])
            nodevariable = NodeVariable(variable_id)
            nodevariable.addIntegerValues(domain)
            nodevariables.append(nodevariable)
            for agent in agents:
                if int(agent.getId()) == agent_id:
                    agent.addNodeVariable(nodevariable)

        if line.startswith('CONSTRAINT'):
            splitted = line.split(" ")
            nodefunction = NodeFunction(function_id)
            functionevaluator = TabularFunction()
            nodefunction.setFunction(functionevaluator)
            nodefunctions.append(nodefunction)

            for agent in agents:
                agent.addNodeFunction(nodefunction)

            argsOfFunction = list()

            variable_id1 = int(splitted[1])
            variable_id2 = int(splitted[2])

            #aggiungi ste due id var
            for variable in nodevariables:
                if int(variable.getId()) == variable_id1:
                    variable.addNeighbour(nodefunction)
                    nodefunction.addNeighbour(variable)
                    argsOfFunction.append(variable)

                if int(variable.getId()) == variable_id2:
                    variable.addNeighbour(nodefunction)
                    nodefunction.addNeighbour(variable)
                    argsOfFunction.append(variable)

            nodefunction.getFunction().setParameters(argsOfFunction)

            function_id = function_id + 1

        if line.startswith('F'):
            splitted = line.split(' ')
            node_id0 = int(splitted[1])
            node_id1 = int(splitted[2])
            cost = int(splitted[3])
            parameters = (NodeArgument(node_id0).getValue(),
                          NodeArgument(node_id1).getValue())
            nodefunction.getFunction().addParametersCost(parameters, cost)

    cop = COP_Instance(nodevariables, nodefunctions, agents)
    f.close()

    return cop
Ejemplo n.º 12
0
def loadDcopFromFile(file):
    if file.lower().endswith('.r'):
        nodevariables = list()
        nodefunctions = list()
        agents = list()
        nogoods = list()
        domain = 0
        agent_id = 0
        variable_id = 0
        function_id = 0

        f = open(file, "r")
        for line in f:
            if line.startswith('AGENT'):
                splitted = line.split(" ")
                agent_id = int(splitted[1])
                agent = Agent(agent_id)
                agents.append(agent)

            if line.startswith('VARIABLE'):
                splitted = line.split(" ")
                variable_id = int(splitted[1])
                agent_id = int(splitted[2])
                domain = int(splitted[3])

                nodevariable = NodeVariable(variable_id)
                nodevariable.addIntegerValues(domain)
                nodevariables.append(nodevariable)

                for agent in agents:
                    if int(agent.getId()) == agent_id:
                        agent.addNodeVariable(nodevariable)

            if line.startswith('CONSTRAINT'):
                splitted = line.split(" ")
                nodefunction = NodeFunction(function_id)
                functionevaluator = TabularFunction()
                nodefunction.setFunction(functionevaluator)
                nodefunctions.append(nodefunction)

                for agent in agents:
                    agent.addNodeFunction(nodefunction)

                argsOfFunction = list()

                variable_id1 = int(splitted[1])
                variable_id2 = int(splitted[2])
                #print('vars ' + str(variable_id1) + ' ' + str(variable_id2))
                #aggiungi ste due id var
                for variable in nodevariables:
                    if int(variable.getId()) == variable_id1:
                        variable.addNeighbour(nodefunction)
                        nodefunction.addNeighbour(variable)
                        argsOfFunction.append(variable)

                    if int(variable.getId()) == variable_id2:
                        variable.addNeighbour(nodefunction)
                        nodefunction.addNeighbour(variable)
                        argsOfFunction.append(variable)

                nodefunction.getFunction().setParameters(argsOfFunction)
                function_id = function_id + 1

            if line.startswith('NOGOOD'):
                splitted = line.split(" ")
                nogoods.append(str(splitted[1]) + " " + splitted[2])

        computeIntegerArguments(nodefunctions,
                                domain)  #constraints have a domain of 0-9
        cop = COP_Instance(nodevariables, nodefunctions, agents)
        f.close()
        #print(cop.getFactorGraph().toString())
        return cop
Ejemplo n.º 13
0
def main():
    '''
        invoke the parser that takes parameters from the command line
    '''
    args = getParser()
    '''
        How many iterations?
    '''
    nIterations = args.iterations
    '''
        How many instances? 
    '''
    nIstances = args.instances
    '''
        file of the factor graph
    '''
    file = args.file
    dire = file[:-2]
    '''
        max/min
    '''
    op = args.op
    '''
        Constraint Optimization Problem
    '''
    cop = None

    domain = 0

    variables = list()
    functions = list()
    agents = list()

    agent = None

    finalAssignaments = list()

    oldAssignaments = list()

    core = None

    originalCop = None

    actualValue = 0
    '''
        list of all values of RUN for each iteration
    '''
    averageValues = list()

    iterations = list()

    iterationsInstances = list()

    averageValuesInstances = list()

    relations = list()
    '''
	create directories
    '''
    if not os.path.exists("DFSParallelConditioning/"):
        os.makedirs("DFSParallelConditioning/")
    if not os.path.exists("DFSParallelConditioning/" + dire):
        os.makedirs("DFSParallelConditioning/" + dire)
    if not os.path.exists("DFSParallelConditioning/" + dire + "/Charts/"):
        os.makedirs("DFSParallelConditioning/" + dire + "/Charts/")
    if not os.path.exists("DFSParallelConditioning/" + dire + "/FactorGraph/"):
        os.makedirs("DFSParallelConditioning/" + dire + "/FactorGraph/")

    dir_charts = "DFSParallelConditioning/" + dire + "/Charts/"
    dir_factorgraph = "DFSParallelConditioning/" + dire + "/FactorGraph/"

    string = "Max Sum\t Average Conflicts\n"
    precop = loadDcopFromFile1(file)

    factorgraph = precop.getFactorGraph()

    nVariables = len(factorgraph.getNodeVariables())
    varSet = (0.1 * nVariables)

    choice = True

    for run in range(nIstances):

        print('\n\n###########################\n#\n#\tRUN ' + str(run) +
              '\n#\n###########################')

        averageValues = list()

        iterations = list()

        finalAssignaments = list()

        oldAssignaments = list()

        for i in range(nVariables):
            finalAssignaments.append(0)
            oldAssignaments.append(0)
        '''
                values of MaxSum for each iteration
            '''
        values = list()
        '''
                id for conditioning functions
            '''
        fId = 200
        '''
                create a new DCOP by visiting the initial graph
                save the factorgraph on file
            '''
        print('\ncreating dfs pseudo tree...')

        dfs_tree = dfs(factorgraph)

        dfs_tree.dfsVisit()  #actual visit

        domain = factorgraph.getNodeVariables()[0].size()
        relation = dfs_tree.getRelations()

        cop = dfs_tree.getDCopPseudoGraph(dir_factorgraph, run, domain)

        print('...created:\n')

        i = 0

        going = False

        functions = cop.getNodeFunctions()
        variables = cop.getNodeVariables()

        toRemove = list()
        toRemoveOld = list()

        iterations_bundling = int(nIterations)

        total_time = 0
        '''
                repeat the algorithm for 50 times
                every exec set the value of variable
            '''
        while ((len(variables) > 0) & (len(functions) > 0)):
            '''
                    if it isn't the first exec of MaxSum,
                    change the factor graph and repeat the algorithm
                '''
            if (going == True):
                '''
                        the agent of the cop
                    '''
                agent = (core.getCop().getAgents())[0]
                '''
                        the variables of the cop
                    '''
                variables = core.getCop().getNodeVariables()
                '''
                        the functions of the cop
                    '''
                functions = core.getCop().getNodeFunctions()

                if not toRemoveOld:
                    toRemove = dfs_tree.getInitToRemove(
                    )  #prende le teste degli alberi

                    graph = dict()

                    for variable in variables:
                        graph[variable] = list()

                        for f in variable.getNeighbour():
                            for v in f.getNeighbour():
                                if ((v.getId()) != (variable.getId())):
                                    graph[variable].append(v)

                    count = 0

                    while ((count < (50)) and ((len(variables) - count) > 0)
                           and (len(toRemove) < 10)):

                        v = None
                        maxGrade = float('-inf')

                        for var in graph.keys():
                            if (len(graph[var]) > maxGrade):
                                maxGrade = len(graph[var])
                                v = var

                        if (len(toRemove) == 0):
                            toRemove.append(v)
                        else:
                            n2 = set(v.getNeighbour())
                            for var in toRemove:
                                n1 = set(var.getNeighbour())
                                inter = set(n1).intersection(n2)
                                if (len(inter) == 0):
                                    if v not in toRemove:
                                        toRemove.append(v)
                        del graph[v]

                        count = count + 1

                    toRemoveOld = toRemove
                else:

                    toRemove = None
                    toRemove = list()

                    for node in toRemoveOld:
                        nodeId = node.getId()
                        for toAppend in relation[nodeId][1]:
                            toRemove.append(toAppend)

                    for rel in relation:
                        for toRem in toRemove:
                            if toRem in rel[1]:
                                rel[1].remove(toRem)

                    if len(toRemove) == 0:
                        if len(variables) < nVariables / 10:
                            for var in variables:
                                toRemove.append(var)
                        else:
                            numberOfFunctions = list()
                            for node_id in range(0, len(variables)):
                                numberOfFunctions.append(
                                    len(variables[node_id].
                                        getVariableNeighbour()))

                            while (numberOfFunctions.index(
                                    max(numberOfFunctions)) !=
                                   -1) and len(toRemove) < 5:
                                node_id = numberOfFunctions.index(
                                    max(numberOfFunctions))
                                toRemove.append(variables[node_id])

                                numberOfFunctions[numberOfFunctions.index(
                                    max(numberOfFunctions))] = -1

                    toRemove = list(toRemove)
                    toRemoveOld = list()
                    toRemoveOld = toRemove

                iterations_bundling = iterations_bundling - len(toRemove)

                state = 0

                for j in range(len(toRemove)):
                    '''
                            state of variable i
                        '''
                    state = toRemove[j].getStateArgument()

                    print('conditioning on:', toRemove[j].toString(),
                          state.getValue())

                    index = getIndex(originalCop, toRemove[j])
                    '''
                            save the value of the variable
                        '''
                    finalAssignaments[index] = state.getValue()

                    oldAssignaments[index] = finalAssignaments[index]

                if (len(toRemove) > 0):
                    for variableToRemove in toRemove:
                        for rel in relation:
                            if (variableToRemove in rel[1]):
                                rel[1].remove(variableToRemove)

                    for variableToRemove in toRemove:

                        functionsToRemove = variableToRemove.getNeighbour()

                        if variableToRemove in agent.getVariables():
                            agent.removeNodeVariable(variableToRemove)
                        if variableToRemove in variables:
                            variables.remove(variableToRemove)

                        for otherVar in variables:
                            n1 = set(functionsToRemove)
                            n2 = set(otherVar.getNeighbour())
                            inter = set(n1).intersection(n2)

                            while (len(inter) > 0):
                                argsOfFunction = list()
                                func = inter.pop()
                                argsOfFunction.append(otherVar)
                                if func in functions:
                                    functions.remove(func)
                                if func in agent.getFunctions():
                                    agent.removeNodeFunction(func)
                                otherVar.removeNeighbours(functionsToRemove)

                                nodefunction = NodeFunction(fId)
                                functionevaluator = TabularFunction()
                                nodefunction.setFunction(functionevaluator)
                                otherVar.addNeighbour(nodefunction)
                                nodefunction.addNeighbour(otherVar)
                                costTable = (func.getFunction()).getCostTable()
                                index = (func.getFunction(
                                )).getParameterPosition(variableToRemove)
                                state = (variableToRemove.getStateArgument()
                                         ).getValue()

                                for j in range(0, otherVar.size()):
                                    t = (j)
                                    if index == 0:
                                        cost = costTable[(state, j)]
                                    else:
                                        cost = costTable[(j, state)]
                                    nodefunction.getFunction(
                                    ).addParametersCost(t, cost)

                                nodefunction.getFunction().setParameters(
                                    argsOfFunction)

                                agent.addNodeFunction(nodefunction)
                                functions.append(nodefunction)

                                fId = fId + 1

                            otherVar.removeNeighbours(functionsToRemove)

                        for fictfun in functionsToRemove:
                            if fictfun.getId() >= 5000:
                                if fictfun in functions:
                                    functions.remove(fictfun)

                if ((len(variables) > 0) & (len(functions) > 0)):

                    agents = list()

                    agents.append(agent)

                    cop = COP_Instance(variables, functions, agents)

                    i = i + varSet

            if ((len(variables) > 0) & (len(functions) > 0)):
                '''
                        create new MaxSum instance (max/min)
                    '''

                core = MaxSum(cop, "min", run)
                '''
                        update only at end?
                    '''
                core.setUpdateOnlyAtEnd(False)

                core.setIterationsNumber(iterations_bundling)

                start_time = time.time()
                '''
                        invoke the method that executes the MaxSum algorithm
                    '''

                print('\n###running solve_complete()\n')

                core.solve_complete()

                values = core.getValues()

                elapse_time = time.time() - start_time
                print('MaxSum elapse_time:', elapse_time)

                total_time = total_time + elapse_time

                going = True

                if (i == 0):
                    '''
                             create a copy of cop
                        '''
                    originalCop = deepcopy(core.getCop())

                    oldVariables = originalCop.getNodeVariables()

                    for k in range(len(oldVariables)):
                        oldAssignaments[k] = oldVariables[k].getStateIndex()

                actualValue = calculateActualValue(originalCop,
                                                   oldAssignaments)
                averageValues.append(actualValue)

                iterations.append(len(values))

        if ((len(variables) > 0) & (len(functions) == 0)):
            '''
                    the variables of the cop
                '''

            variables = core.getCop().getNodeVariables()
            '''
                    remaining variables to set
                '''
            index = (nVariables - i) - 1

            k = 0

            j = 1

            while (j < ((index / varSet) + 1)):

                while (k < (varSet * j)):
                    '''
                            state of variable i
                        '''
                    state = (variables[k]).getStateArgument()
                    '''
                            save the value of the variable
                        '''
                    finalAssignaments[i] = state.getValue()

                    oldAssignaments[i] = finalAssignaments[i]

                    i = i + k

                    k = k + 1

                actualValue = calculateActualValue(originalCop,
                                                   oldAssignaments)

                averageValues.append(actualValue)

                iterations.append(len(values))

                j = j + 1

        for i in range(len(iterations)):
            if (i > 0):
                iterations[i] = iterations[i] + iterations[i - 1]

        averageValuesInstances.append(averageValues)
        iterationsInstances.append(iterations)

        # draw the chart
        # x axis: number of MaxSum exec
        # y axis: conflicts
        x = iterations
        '''
                x axis: number of MaxSum exec
            '''
        y = averageValues
        pl.title('Cost / Iterations chart')
        pl.xlabel('Iterations')
        pl.ylabel('Cost')
        pl.plot(x, y)
        pl.savefig(dir_charts + "Chart_RUN_" + str(run) + ".png")
        pl.close()

        print('total time for MaxSum ', total_time)

    sumIterations = [sum(x) for x in zip(*iterationsInstances)]
    sumValues = [sum(x) for x in zip(*averageValuesInstances)]

    stdIterations = [numpy.std(x) for x in zip(*iterationsInstances)]
    stdValues = [numpy.std(x) for x in zip(*averageValuesInstances)]

    for i in range(len(sumIterations)):
        sumIterations[i] = sumIterations[i] / nIstances

    for i in range(len(sumValues)):
        sumValues[i] = sumValues[i] / nIstances

    totalIterations = list(
        itertools.izip_longest(*iterationsInstances, fillvalue=0))
    totalConflicts = list(
        itertools.izip_longest(*averageValuesInstances, fillvalue=0))

    sumIterations_correct = [sum(x) / len_not_0(x) for x in totalIterations]
    sumValues_correct = [sum(x) / len_not_0(x) for x in totalConflicts]

    stdIterations = list()
    stdValues = list()

    for i in range(0, len(totalConflicts)):
        appoggio = list()
        if (len_not_0(totalConflicts[i]) < 50):
            for elem in totalConflicts[i]:
                if (int(elem) != 0):
                    appoggio.append(elem)

            stdValues.append(numpy.std(appoggio))
        else:
            stdValues.append(numpy.std(totalConflicts[i]))

    for i in range(0, len(totalIterations)):
        appoggio = list()
        if (len_not_0(totalConflicts[i]) < 50):
            for elem in totalConflicts[i]:
                if (int(elem) != 0):
                    appoggio.append(elem)
            stdIterations.append(numpy.std(appoggio))
        else:
            stdIterations.append(numpy.std(totalIterations[i]))

    median_iterations = list()
    median_conflicts = list()

    number_of_iterations = list(
    )  #each elements indicate how many runs are still active at that iteration number

    for x in totalIterations:
        number_of_iterations.append(len_not_0(x))

    finished_runs = list(
    )  #how many runs are terminated at that iteration number

    runs = nIstances

    for x in number_of_iterations:
        finished_runs.append(runs - int(x))

        runs = runs - (runs - int(x))

    runs = nIstances

    how_many_runs = 0

    for x in finished_runs:
        runs = runs - x
        if runs <= math.floor(nVariables / 2):
            how_many_runs = x
            break

    max_number_of_finished_runs = max(finished_runs)

    for i in range(0, finished_runs.index(how_many_runs)):
        median_iterations.append(sumIterations_correct[i])
        median_conflicts.append(sumValues_correct[i])

    # draw the chart
    # x axis: number of MaxSum exec
    # y axis: conflicts
    x = median_iterations
    '''
        x axis: number of MaxSum exec
    '''
    y = median_conflicts
    pl.title('Cost / Iterations chart')
    pl.xlabel('Iterations')
    pl.ylabel('Cost')
    pl.plot(x, y)
    pl.savefig(dir_charts + "/AverageAllInstances.png")
    pl.close()

    string = 'Iteration\tStdDevIter\t\t\tConflict\tStdDevConflicts\t\tHowManyStopped\n'

    for i in range(len(sumIterations_correct)):
        string = string + str(sumIterations_correct[i]) + '\t\t' + str(
            stdIterations[i]) + '\t\t' + str(
                sumValues_correct[i]) + '\t\t' + str(
                    stdValues[i]) + '\t\t' + str(
                        number_of_iterations[i]) + '\n'

    output_file = open(dir_factorgraph + "/reportIterations.txt", "w")
    output_file.write(string)
    output_file.write("\n")
    output_file.close()
Ejemplo n.º 14
0
def create_DCop():

    nodeVariables = list()
    nodeFunctions = list()
    agents = list()

    agent = Agent(0)

    nodeVariable1 = NodeVariable(1)
    nodeVariable2 = NodeVariable(2)

    nodeVariable1.addDomain([0, 1, 2])
    nodeVariable2.addDomain([0, 2, 3])

    nodefunction0 = NodeFunction(0)
    nodefunction1 = NodeFunction(1)
    nodefunction2 = NodeFunction(2)
    nodefunction3 = NodeFunction(3)

    nodefunction0.setFunction(TabularFunction())
    nodefunction1.setFunction(TabularFunction())
    nodefunction2.setFunction(TabularFunction())
    nodefunction3.setFunction(TabularFunction())

    nodeVariable1.addNeighbour(nodefunction1)
    nodeVariable1.addNeighbour(nodefunction2)
    nodeVariable2.addNeighbour(nodefunction2)
    nodeVariable2.addNeighbour(nodefunction3)

    nodefunction1.addNeighbour(nodeVariable1)
    nodefunction2.addNeighbour(nodeVariable1)
    nodefunction2.addNeighbour(nodeVariable2)
    nodefunction3.addNeighbour(nodeVariable2)

    nodefunction1.getFunction().addParametersCost([NodeArgument(0)], 0)
    nodefunction1.getFunction().addParametersCost([NodeArgument(1)], 10)
    nodefunction1.getFunction().addParametersCost([NodeArgument(2)], 0)

    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(0), NodeArgument(0)], 0)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(0), NodeArgument(3)], 0)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(1), NodeArgument(0)], 0)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(1), NodeArgument(3)], 0)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(0), NodeArgument(2)], 4)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(1), NodeArgument(2)], 4)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(2), NodeArgument(0)], 5)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(2), NodeArgument(3)], 5)
    nodefunction2.getFunction().addParametersCost(
        [NodeArgument(2), NodeArgument(2)], 17)

    nodefunction3.getFunction().addParametersCost([NodeArgument(0)], 0)
    nodefunction3.getFunction().addParametersCost([NodeArgument(2)], 0)
    nodefunction3.getFunction().addParametersCost([NodeArgument(3)], 8)

    nodeVariables.append(nodeVariable1)
    nodeVariables.append(nodeVariable2)
    nodeFunctions.append(nodefunction0)
    nodeFunctions.append(nodefunction1)
    nodeFunctions.append(nodefunction2)
    nodeFunctions.append(nodefunction3)

    agent.addNodeVariable(nodeVariable1)
    agent.addNodeVariable(nodeVariable2)
    agent.addNodeFunction(nodefunction0)
    agent.addNodeFunction(nodefunction1)
    agent.addNodeFunction(nodefunction2)
    agent.addNodeFunction(nodefunction3)
    agents.append(agent)

    cop = COP_Instance(nodeVariables, nodeFunctions, agents)

    return cop
Ejemplo n.º 15
0
def main():
    '''
        invoke the parser that takes parameters from the command line
    '''
    args = getParser()
    '''
        How many iterations?
    '''
    nIterations = args.iterations
    '''
        How many instances? 
    '''
    nIstances = args.instances
    '''
        number of variables in Dcop
    '''
    nVariables = args.variables
    '''
        max/min
    '''
    op = args.op
    '''
        location of MaxSum report
    '''
    reportMaxSum = args.reportMaxSum
    '''
        location of FactorGraph report
    '''
    infoGraphPathFile = args.reportFactorGraph
    '''
        location of Charts
    '''
    chartsFile = args.reportCharts
    '''
        Constraint Optimization Problem
    '''
    cop = None
    '''
        average of 50 instances of problem
    '''
    average = list()

    for i in range(nVariables + 1):
        average.append(0)

    state = 0

    variables = list()
    functions = list()
    agents = list()

    agent = None

    finalAssignaments = list()

    oldAssignaments = list()

    core = None

    originalCop = None

    actualValue = 0
    '''
        list of all values of RUN for each iteration
    '''
    averageValues = list()

    iterations = list()

    iterationsInstances = list()

    averageValuesInstances = list()

    maxGradeList = list()

    varSet = (0.1 * nVariables)
    '''
	create directories
    '''
    if not os.path.exists("MaxSumParallelHGMaxHop/"):
        os.makedirs("MaxSumParallelHGMaxHop/")
        if not os.path.exists("MaxSumParallelHGMaxHop/Charts/"):
            os.makedirs("MaxSumParallelHGMaxHop/Charts/")
        if not os.path.exists("MaxSumParallelHGMaxHop/FactorGraph/"):
            os.makedirs("MaxSumParallelHGMaxHop/FactorGraph/")

    string = "Max Sum\t Average Conflicts\n"

    for run in range(nIstances):

        averageValues = list()

        iterations = list()
        '''
                fileName of log (Iteration Conflicts AverageDifferenceLink)
                save on file Iteration Conflicts AverageDifferenceLink
            '''
        finalAssignaments = list()

        oldAssignaments = list()

        for i in range(nVariables):
            finalAssignaments.append(0)
            oldAssignaments.append(0)
        '''
                values of MaxSum for each iteration
            '''
        values = list()
        '''
                create a new COP with a colored Graph and 
                save the factorgraph on file
            '''
        cop = create_DCop(infoGraphPathFile, nVariables, run)

        i = 0

        going = False

        functions = cop.getNodeFunctions()
        variables = cop.getNodeVariables()
        '''
                repeat the algorithm for 50 times
                every exec set the value of variable
            '''
        while ((len(variables) > 0) & (len(functions) > 0)):
            '''
                    if it isn't the first exec of MaxSum,
                    change the factor graph and repeat the algorithm
                '''
            if (going == True):
                '''
                        the agent of the cop
                    '''
                agent = (core.getCop().getAgents())[0]
                '''
                        the variables of the cop
                    '''
                variables = core.getCop().getNodeVariables()
                '''
                        the functions of the cop
                    '''
                functions = core.getCop().getNodeFunctions()

                graph = dict()

                hop = dict()

                for variable in variables:
                    graph[variable] = list()
                    '''
                            for each node function
                        '''
                    for f in variable.getNeighbour():
                        for v in f.getNeighbour():
                            if ((v.getId()) != (variable.getId())):
                                graph[variable].append(v)
                                hop[(variable, v)] = float('-inf')

                for v in range(len(variables)):
                    for k in range(v + 1, len(variables)):
                        '''
                                if there is at least a neighbour
                             '''
                        if (len(graph[variable]) > 0):
                            '''
                                    bfs visit with shortest path
                                 '''
                            shortestPath = list(
                                bfs_shortest_path(graph, variables[v],
                                                  variables[k]))
                            '''
                                    if there is a path, update the number of hops
                                 '''
                            if (len(shortestPath) > 0):
                                hop[(variables[v],
                                     variables[k])] = len(shortestPath) - 1

                variablesToRemove = list()

                maxGrade = float('-inf')

                v = None
                '''
                        find the variable with max grade
                    '''
                for var in graph.keys():
                    if (len(graph[var]) > maxGrade):
                        maxGrade = len(graph[var])
                        v = var

                variablesToRemove.append(v)

                maxGrade = float('-inf')

                maxHop = float('-inf')

                v = None
                '''
                        find the variable with max distance from random variable
                        and with max grade
                    '''
                for tuple in hop.keys():
                    if ((tuple[0].getId()) == (variablesToRemove[0].getId())):
                        if ((hop[tuple] > maxHop) &
                            (len(graph[tuple[1]]) > maxGrade)):
                            maxHop = hop[tuple]
                            maxGrade = len(graph[tuple[1]])
                            '''
                                    far variable
                                '''
                            v = tuple[1]
                '''
                        there is a variable with max hop
                        and max grade
                    '''
                if (v != None):
                    '''
                           ad the variable more far
                        '''
                    variablesToRemove.append(v)

                    while ((len(variablesToRemove) < varSet) &
                           ((len(variables) - len(variablesToRemove)) > 0)):

                        inter = list()
                        '''
                                find the intersection
                            '''
                        for j in range(1, len(variablesToRemove)):
                            if (j == 1):
                                inter = list(
                                    set(graph[variablesToRemove[
                                        j - 1]]).intersection(
                                            set(graph[variablesToRemove[j]])))
                            else:
                                inter = list(
                                    set(inter).intersection(
                                        set(graph[variablesToRemove[j]])))

                        liste = list()

                        maxGradeList = list()

                        v = None

                        if (len(inter) > 0):

                            while ((len(maxGradeList) < varSet) &
                                   (len(inter) > 0)):

                                v = None

                                count = 0

                                maxGrade = float('-inf')

                                while (count < len(inter)):

                                    var = inter[count]

                                    if (len(graph[var]) > maxGrade):
                                        maxGrade = len(graph[var])
                                        v = var

                                    count = count + 1

                                maxGradeList.append(v)
                                '''
                                        remove the variable with highest grade
                                    '''
                                inter.remove(v)
                        '''
                                intersection not empty
                            '''
                        if (len(maxGradeList) > 0):

                            k = 0

                            while (k < len(variablesToRemove)):

                                list1 = list()

                                for n in maxGradeList:
                                    list1.append(hop[(variablesToRemove[k],
                                                      n)])

                                liste.append(list1)

                                k = k + 1
                            '''
                                    sum the distances between variables
                                '''
                            content = [sum(x) for x in zip(*liste)]

                            maxHopIndex = content.index(max(content))
                            '''
                                    add the variable more far
                                '''
                            variablesToRemove.append(maxGradeList[maxHopIndex])
                        else:
                            '''
                                    remaining variables to choose
                                '''
                            diff = list(
                                set(variables) - set(variablesToRemove))

                            while ((len(variablesToRemove) < varSet) &
                                   (len(diff) > 0)):
                                '''
                                         choose random variables
                                     '''
                                indexRemove = random.randint(0, len(diff) - 1)
                                '''
                                         add the random variable
                                     '''
                                variablesToRemove.append(diff[indexRemove])

                                diff.remove(diff[indexRemove])

                else:
                    '''
                            remaining variables to choose
                        '''
                    diff = list(set(variables) - set(variablesToRemove))

                    while (((len(variablesToRemove) < varSet) &
                            (len(diff) > 0))):
                        '''
                                    choose random variables
                                 '''
                        indexRemove = random.randint(0, len(diff) - 1)
                        '''
                                    add the random variable
                                 '''
                        variablesToRemove.append(diff[indexRemove])

                        diff.remove(diff[indexRemove])

                for j in range(len(variablesToRemove)):
                    '''
                            state of variable i
                        '''
                    state = variablesToRemove[j].getStateArgument()

                    print('state of variable:',
                          variablesToRemove[j].toString(), state.getValue())

                    index = getIndex(originalCop, variablesToRemove[j])
                    '''
                            save the value of the variable
                        '''
                    finalAssignaments[index] = state.getValue()

                    oldAssignaments[index] = finalAssignaments[index]

                for var in variablesToRemove:
                    '''
                            remove the variable on the agent
                        '''
                    agent.removeNodeVariable(var)

                for var in variablesToRemove:
                    '''
                            neighbours of variable  
                        '''
                    neighbours = var.getNeighbour()

                    for function in neighbours:
                        functions.remove(function)
                        agent.removeNodeFunction(function)
                    '''
                            remove the variable from the list
                        '''
                    variables.remove(var)

                    for variable in variables:

                        n1 = set(neighbours)
                        n2 = set(variable.getNeighbour())

                        if ((len(set(n1).intersection(n2))) > 0):
                            '''
                                    intersection of neighbours
                                '''
                            inter = (set(n1).intersection(n2))

                            while (len(inter) > 0):

                                func = inter.pop()
                                '''
                                        list of the arguments of the function
                                    '''
                                argumentsOfFunction = list()

                                funId = 0
                                '''
                                        there is at least a function
                                    '''
                                if ((len(functions)) > 0):
                                    funId = ((functions[len(functions) -
                                                        1]).getId()) + 1
                                else:
                                    funId = 0
                                '''
                                        creates an unary function linked to the variable
                                    '''
                                nodefunction = NodeFunction(funId)

                                functionevaluator = TabularFunction()
                                nodefunction.setFunction(functionevaluator)
                                '''
                                        add this nodefunction to the actual nodevariable's neighbour
                                    '''
                                variable.addNeighbour(nodefunction)
                                '''
                                        add this variable as nodefunction's neighbour
                                    '''
                                nodefunction.addNeighbour(variable)
                                '''
                                        add the variable as an argument of the function
                                    '''
                                argumentsOfFunction.append(variable)

                                costTable = (func.getFunction()).getCostTable()

                                cost = 0
                                '''
                                        state of variableToRemove
                                    '''
                                state = var.getStateArgument()

                                index = (func.getFunction()
                                         ).getParameterPosition(var)
                                '''
                                        create the unary function
                                    '''
                                for j in range(0, variable.size()):

                                    t = (j)

                                    if (index == 0):
                                        cost = costTable[(state.getValue(), j)]
                                    else:
                                        cost = costTable[(j,
                                                          (state.getValue()))]
                                    '''
                                            add to the cost function: [parameters -> cost]
                                        '''
                                    nodefunction.getFunction(
                                    ).addParametersCost(t, cost)
                                '''
                                        add the neighbors of the function node
                                    '''
                                nodefunction.getFunction().setParameters(
                                    argumentsOfFunction)
                                '''
                                        add the function node
                                    '''
                                functions.append(nodefunction)
                                '''
                                        add the function node to the agent
                                    '''
                                agent.addNodeFunction(nodefunction)

                            variable.removeNeighbours(neighbours)

                if ((len(variables) > 0) & (len(functions) > 0)):

                    agents = list()

                    agents.append(agent)

                    cop = COP_Instance(variables, functions, agents)

                    i = i + varSet

            if ((len(variables) > 0) & (len(functions) > 0)):
                '''
                        create new MaxSum instance (max/min)
                    '''
                core = MaxSum(cop, op)
                '''
                        update only at end?
                    '''
                core.setUpdateOnlyAtEnd(False)

                core.setIterationsNumber(nIterations)

                start_time = time.time()
                '''
                        invoke the method that executes the MaxSum algorithm
                    '''
                core.solve_complete()

                values = core.getValues()

                elapse_time = time.time() - start_time
                print('MaxSum elapse_time:', elapse_time)

                going = True

                if (i == 0):
                    '''
                             create a copy of cop
                        '''
                    originalCop = deepcopy(core.getCop())

                    oldVariables = originalCop.getNodeVariables()

                    for k in range(len(oldVariables)):
                        oldAssignaments[k] = oldVariables[k].getStateIndex()

                actualValue = calculateActualValue(originalCop,
                                                   oldAssignaments)

                averageValues.append(actualValue)

                iterations.append(len(values))

        if ((len(variables) > 0) & (len(functions) == 0)):
            '''
                    the variables of the cop
                '''
            variables = core.getCop().getNodeVariables()
            '''
                    remaining variables to set
                '''
            index = (nVariables - i) - 1

            k = 0

            j = 1

            while (j < ((index / varSet) + 1)):

                while (k < (varSet * j)):
                    '''
                            state of variable i
                        '''
                    state = (variables[k]).getStateArgument()
                    '''
                            save the value of the variable
                        '''
                    finalAssignaments[i] = state.getValue()

                    oldAssignaments[i] = finalAssignaments[i]

                    i = i + k

                    k = k + 1

                actualValue = calculateActualValue(originalCop,
                                                   oldAssignaments)

                averageValues.append(actualValue)

                iterations.append(len(values))

                j = j + 1

        for i in range(len(iterations)):
            if (i > 0):
                iterations[i] = iterations[i] + iterations[i - 1]

        averageValuesInstances.append(averageValues)
        iterationsInstances.append(iterations)

        # draw the chart
        # x axis: number of MaxSum exec
        # y axis: conflicts
        x = iterations
        '''
                x axis: number of MaxSum exec
            '''
        y = averageValues
        pl.title('Cost / Iterations chart')
        pl.xlabel('Iterations')
        pl.ylabel('Cost')
        pl.plot(x, y)
        #pl.show()
        pl.savefig(chartsFile + "MaxSumParallelHGMaxHop/Charts/Chart_RUN_" +
                   str(run) + ".png")
        pl.close()

    sumIterations = [sum(x) for x in zip(*iterationsInstances)]
    sumValues = [sum(x) for x in zip(*averageValuesInstances)]

    for i in range(len(sumIterations)):
        sumIterations[i] = sumIterations[i] / nIstances

    for i in range(len(sumValues)):
        sumValues[i] = sumValues[i] / nIstances

    # draw the chart
    # x axis: number of MaxSum exec
    # y axis: conflicts
    x = sumIterations
    '''
        x axis: number of MaxSum exec
    '''
    y = sumValues
    pl.title('Cost / Iterations chart')
    pl.xlabel('Iterations')
    pl.ylabel('Cost')
    pl.plot(x, y)
    pl.savefig(chartsFile +
               "MaxSumParallelHGMaxHop/Charts/AverageAllInstances.png")
    pl.close()

    string = 'Iteration\tConflict\n'

    for i in range(len(sumIterations)):
        string = string + str(sumIterations[i]) + '\t\t' + str(
            sumValues[i]) + '\n'

    output_file = open(
        infoGraphPathFile +
        "MaxSumParallelHGMaxHop/FactorGraph/reportIterations.txt", "w")
    output_file.write(string)
    output_file.write("\n")
    output_file.close()
Ejemplo n.º 16
0
def test():

    nodeVariable1 = NodeVariable(1)
    nodeVariable2 = NodeVariable(2)
    nodeVariable3 = NodeVariable(3)

    nodeVariable1.addDomain([1, -1])
    nodeVariable2.addDomain([1, -1])
    nodeVariable3.addDomain([1, 2, 3, 4, 5, -1, -2, -3, -4, -5])

    nodefunction1 = NodeFunction(1)
    nodefunction2 = NodeFunction(2)
    nodefunction3 = NodeFunction(3)
    nodefunction4 = NodeFunction(4)
    nodefunction5 = NodeFunction(5)

    nodefunction1.setFunction(TabularFunction())
    nodefunction2.setFunction(TabularFunction())
    nodefunction3.setFunction(TabularFunction())
    nodefunction4.setFunction(TabularFunction())
    nodefunction5.setFunction(TabularFunction())

    nodeVariable1.addNeighbour(nodefunction1)
    nodeVariable2.addNeighbour(nodefunction1)
    nodeVariable3.addNeighbour(nodefunction1)
    nodeVariable3.addNeighbour(nodefunction2)
    nodeVariable3.addNeighbour(nodefunction3)
    nodeVariable3.addNeighbour(nodefunction4)
    nodeVariable3.addNeighbour(nodefunction5)

    nodefunction1.addNeighbour(nodeVariable1)
    nodefunction1.addNeighbour(nodeVariable2)
    nodefunction1.addNeighbour(nodeVariable3)

    nodefunction2.addNeighbour(nodeVariable3)
    nodefunction3.addNeighbour(nodeVariable3)
    nodefunction4.addNeighbour(nodeVariable3)
    nodefunction5.addNeighbour(nodeVariable3)

    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(1), NodeArgument(1),
         NodeArgument(1)], 7)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(-1), NodeArgument(1),
         NodeArgument(1)], 8)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(1), NodeArgument(-1),
         NodeArgument(1)], 5)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(1), NodeArgument(1),
         NodeArgument(-1)], 10)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(-1), NodeArgument(-1),
         NodeArgument(1)], 4)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(-1), NodeArgument(1),
         NodeArgument(-1)], 6)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(1), NodeArgument(-1),
         NodeArgument(-1)], 4)
    nodefunction1.getFunction().addParametersCost(
        [NodeArgument(-1),
         NodeArgument(-1),
         NodeArgument(-1)], 0)

    mfactory = MessageFactory()
    #sum = Sum(mfactory)
    op = Max(mfactory)

    rmessege = op.Op(nodefunction1, nodeVariable3, nodefunction1.getFunction(),
                     [])

    print[rmessege.getValue(i) for i in range(rmessege.size())]

    return rmessege
Ejemplo n.º 17
0
    def toVisit(self, nodevariable, parent, stack):
        self.visitedNodes[nodevariable.getId()] = True
        self.nodeIsVisited(nodevariable)  # used to keep track of the result
        neighbours = nodevariable.getVariableNeighbour()

        if (parent != None):
            node_id1 = self.getDcopNodeById(int(parent.getId()))
            node_id2 = self.getDcopNodeById(int(nodevariable.getId()))

            self.relations[node_id1.getId()][1].append(node_id2)

            argsOfFunction = list()
            nodefunction = NodeFunction(self.function_id)
            functionevaluator = TabularFunction()
            nodefunction.setFunction(functionevaluator)

            node_id1.addNeighbour(nodefunction)
            nodefunction.addNeighbour(node_id1)
            argsOfFunction.append(node_id1)

            node_id2.addNeighbour(nodefunction)
            nodefunction.addNeighbour(node_id2)
            argsOfFunction.append(node_id2)

            nodefunction.getFunction().setParameters(argsOfFunction)

            for i in range(0, self.domain):
                for j in range(0, self.domain):
                    t = (i, j)
                    #print(t)
                    cost = random.randint(1, 10)

                    nodefunction.getFunction().addParametersCost(t, cost)
            self.nodeFunctions.append(nodefunction)

            self.function_id = self.function_id + 1

        be = self.backedges(
            stack, neighbours)  #calculate backedges from me to parents
        random.shuffle(neighbours)  #shuffle to perform a random visit

        for n in neighbours:
            '''
            if my neighbour is not visited
            '''
            if ((self.isVisited(n)) == False):
                '''
                add it to stack
                '''
                stack.append(n.getId())
                '''
                start visit it
                '''
                self.toVisit(n, nodevariable, stack)
                '''
                visit of neighbour n is finished so i remove it from stack and continue with other neighbours
                '''
                stack.remove(n.getId())  #fine visita
            elif (str(nodevariable.getId()) + ";" + str(n.getId()) in be):
                self.backedgesList.append(
                    str(nodevariable.getId()) + ";" + str(n.getId()))