Ejemplo n.º 1
0
    def __init__(self, model):
        """Construtor do agente.
        @param model: Referência do ambiente onde o agente atuará."""
        self.model = model

        self.prob = Problem()
        # @TODO T_AAFP - criar crencas sobre as pareded do labirinto
        self.prob.createMaze(9, 9)
        self.prob.mazeBelief.putVerticalWall(0,1,0)
        # ...


        # Posiciona fisicamente o agente no estado inicial
        initial = self.positionSensor()
        self.prob.defInitialState(initial.row, initial.col)
        
        # Define o estado atual do agente = estado inicial
        self.currentState = self.prob.initialState

        # @TODO T_AAFP - defina estado objetivo
        # Define o estado objetivo
        # self.prob.defGoalState(?, ?)

        # o metodo abaixo serve apenas para a view desenhar a pos objetivo
        # self.model.setGoalPos(2,8)

        # Plano de busca - inicialmente vazio (equivale a solucao)
        self.plan = None
Ejemplo n.º 2
0
 def reinitialize(self, father=None):
     if father is None:
         father = self.father
     Problem.reinitialize(self)
     for vehicle in self.vehicles:
         init = vehicle.get_init_spline_value()
         father.set_variables(init, vehicle, 'splines0')
Ejemplo n.º 3
0
    def generate_fake(self, paper):
        for i in range(3000):
            model = Problem()
            model.id = i
            model.difficulty = random.random()

            if i < 1001:
                model.type = 1
                model.score = paper.each_type_score[model.type-1] / \
                    paper.each_type_count[model.type-1]

            if i > 1000 and i < 2001:
                model.type = 2
                model.score = paper.each_type_score[model.type-1] / \
                    paper.each_type_count[model.type-1]

            if i > 2000 and i < 3001:
                model.type = 3
                model.score = paper.each_type_score[model.type-1] / \
                    paper.each_type_count[model.type-1]

            points = []
            # count = random.randint(1, 2)
            count = 1
            for j in range(count):
                points.append(random.randint(1, 10))

            model.points = points
            self.problem_db.append(model)
Ejemplo n.º 4
0
def p_plan_problem(p):
    '''plan_problem : LPAREN DEFINE_KEY plan_problem_def domain_def objects_def init_def goal_def RPAREN
                    | LPAREN DEFINE_KEY plan_problem_def domain_def init_def goal_def RPAREN'''
    if len(p) == 9:
        p[0] = Problem(p[3], p[4], p[5], p[6], p[7])
    elif len(p) == 8:
        p[0] = Problem(p[3], p[4], {}, p[5], p[6])
Ejemplo n.º 5
0
 def __init__(self, tower_size=3, pruning=False):
     self.tower_size = tower_size
     Problem.__init__(self, [list(range(self.tower_size, 0, -1)), [], []])
     self.pruning = pruning
     self.other_pegs = [[1, 2], [0, 2], [
         0, 1
     ]]  #list of pegs a disk in a peg of given index can be moved in
Ejemplo n.º 6
0
    def __init__(self, model):
        """Construtor do agente.
        @param model: Referência do ambiente onde o agente atuará."""
        self.model = model

        self.prob = Problem()
        self.prob.createMaze(6, 6)

        self.prob.mazeBelief.putVerticalWall(2, 4, 3)
        self.prob.mazeBelief.putHorizontalWall(0, 1, 2)

        # Posiciona fisicamente o agente no estado inicial
        initial = self.positionSensor()
        self.prob.defInitialState(initial.row, initial.col, initial.boxes)

        # Define o estado atual do agente = estado inicial
        self.currentState = self.prob.initialState

        # Define o estado objetivo
        self.prob.defGoalState(0, 0, [(5, 1), (5, 4), (5, 5)])
        self.model.addGoalPos(5, 5)
        self.model.addGoalPos(5, 4)
        #self.model.addGoalPos(5,3)
        #self.model.addGoalPos(5,2)
        self.model.addGoalPos(5, 1)
        #self.model.addGoalPos(5,0)

        # Plano de busca
        self.plan = None
Ejemplo n.º 7
0
 def __init__(self,
              capacity,
              search_space,
              fitness_function,
              minimization=False):
     Problem.__init__(self, search_space, fitness_function, minimization)
     self.capacity = capacity
def arithmetic_arranger(problems, solve=False):
    if len(problems) > 5:
        return "Error: Too many problems."

    formattedProblems = []
    for problem in problems:
        p = Problem(problem)
        returnString = p.parseProblemString()
        if returnString:
            return returnString
        p.formatProblem(solve)
        formattedProblems.append(p)

    numProblems = len(formattedProblems)
    numLines = len(p.formattedLines)
    finalStrings = []
    for i in range(numLines):
        for j in range(numProblems):
            finalStrings.append(formattedProblems[j].formattedLines[i])
            if j != (numProblems - 1):
                finalStrings.append(' ' * 4)
            else:
                if i != (numLines - 1):
                    finalStrings.append('\n')

    final = ''.join(finalStrings)
    print(finalStrings)
    print(final)
    return final

    return None
Ejemplo n.º 9
0
    def PlanAhead(self):
        """
        Generate the reward vector for the LP formulation of planning and solve.
        """
        problem = Problem(self.num_rows_, self.num_cols_, self.num_sources_,
                          self.num_steps_, self.angular_step_, self.sensor_params_,
                          self.num_samples_, self.map_)

        # Generate LP parameters at the current pose.
        (pzx, hzm, trajectory_ids) = problem.GenerateConditionals(self.pose_)
        pzx = np.asmatrix(pzx)
        hzm = np.asmatrix(hzm).T
        num_trajectories = pzx.shape[1]

        # Set up LP.
        result = linprog(np.asarray((pzx.T * hzm)).ravel(),
                         A_eq=np.ones((1, num_trajectories)),
                         b_eq=np.ones((1, 1)),
                         method='simplex')

        if (not result.success):
            print "Could not find a feasible solution to the LP."
            return []

        # Decode solution into trajectory.
        print "Found information-optimal trajectory."
        trajectory_id = trajectory_ids[np.argmax(result.x)]

        delta_xs = [-1, 0, 1]
        delta_ys = [-1, 0, 1]
        delta_as = [-self.angular_step_, 0.0, self.angular_step_]
        trajectory = DecodeTrajectory(delta_xs, delta_ys, delta_as,
                                      trajectory_id, self.pose_, self.num_steps_)

        return trajectory
Ejemplo n.º 10
0
def dist_sampler(sampler: _sampler, problem: Problem, num_samples: int, *args,
                 **kwargs) -> pd.DataFrame:
    """uses the sampling function provided to generate `num_samples` sets of values
    These values will be valid for the corresponding inputs

    :param problem: Problem that the inputs should apply to
    :param sampler: a function that is used to produce the distribution of samples
    :param num_samples: number of samples to take

    :param args: Arguments passed to the sampling function
    :param kwargs: Arguments passed to the sampling function
    :return: pandas DataFrame with one column per parameter, and `num_samples` rows

    """
    samples = sampler(num_samples, problem.num_inputs, *args, **kwargs)
    data = {
        name: _sample_param(param, samples[:, i])
        for i, (
            name,
            param) in enumerate(zip(problem.names('inputs'), problem.inputs))
    }
    df = pd.DataFrame(data)
    # enforce the correct order in case it was lost by the dictionary
    df = df[problem.names('inputs')]
    return df
Ejemplo n.º 11
0
    def __init__(self):
        self.__problem = Problem()
        self.__controller = Controller(self.__problem)
        super().__init__()
        #self.validation()

        self.initUI()
Ejemplo n.º 12
0
 def testProblemStiffness(self):
     width = 3
     height = 3
     [nodes, boundary_nodes, tris] = generateRectangularMesh((width, height), (0,0), (1,1))
     p = Problem(nodes, boundary_nodes, tris)
     stiffness = p.getStiffnessMatrix(lambda x,y: x*y).toarray()
     self.assertEqual(stiffness[0,0], 34.0/9.0)
Ejemplo n.º 13
0
def test_init_invalid_name():
    invalid = ['', 'a', 'a-', '-a', '!', 'ab!c']
    for i in invalid:
        with pytest.raises(ValueError, match=r'invalid name ".*"'):
            args = Problem.default_args()
            args.name = i
            p = Problem(args)
Ejemplo n.º 14
0
 def testKnownProblem(self):
     def f(x,y):
         return -2*x*y*(2*exp(2*x)*(x**2+y**2)+2*exp(2*x)*x)-(1+x**2*y)*(4*exp(2*x)*(x**2+y**2)+8*exp(2*x)*x+2*exp(2*x))-2*x**2*exp(2*x)*y-2*(1+x**2*y)*exp(2*x)
     
     def k(x,y):
         return 1+x**2*y
     
     def u(x,y):
         return exp(2*x)*(x**2+y**2)
     
     def ux(x,y):
         return 2*exp(2*x)*(x**2+y**2)+2*exp(2*x)*x
     
     def uy(x,y):
         return 2*exp(2*x)*y
         
     ewidth = 30
     eheight = 30
     xwidth = 2.
     ywidth = 2.
     ll = (-1.,-1.)
     
     [nodes, boundary_nodes, tris] = generateRectangularMesh((ewidth, eheight), ll, (xwidth/(ewidth-1),ywidth/(eheight-1)))
     p = Problem(nodes, boundary_nodes, tris)
     # U, g = p.solve(lambda x,y: cos(x*y*pi) - 0.5, lambda x,y: 1, lambda x,y: 0, ux)
     Uest, g = p.solve(f, k, u, ux)
     Utrue = [u(n.pos[0],n.pos[1]) for n in p.free_nodes] 
     # view_rectangular_grid_solution((ewidth, eheight), p, Uest, g)
     # view_rectangular_grid_solution((ewidth, eheight), p, Utrue, g)
     error = np.sqrt(np.sum((Utrue - Uest) ** 2))
     print error
     self.assertTrue(error < 0.5)
Ejemplo n.º 15
0
def build_problem(name, get_pfront=False):
    '''
    Build optimization problem
    Input:
        name: problem name
        get_pfront: if return predefined true Pareto front of the problem
    Output:
        problem: the optimization problem
        pareto_front: the true Pareto front of the problem (if defined, otherwise None)
    '''
    problem = None

    # build problem
    python_problems, yaml_problems = find_all_problems()
    if name in python_problems:
        problem = python_problems[name]()
    elif name in yaml_problems:
        full_prob_cfg = load_config(yaml_problems[name])
        problem = Problem(config=full_prob_cfg)
    else:
        raise Exception(f'Problem {name} not found')

    # get true pareto front
    if get_pfront:
        try:
            pareto_front = problem.pareto_front()
        except:
            pareto_front = None
        return problem, pareto_front
    else:
        return problem
Ejemplo n.º 16
0
def initData():
   """Load data and mappings from Raw data files and mapping files"""
   Patient.load()
   Med.load()
   Problem.load()
   Lab.load()
   Refill.load()
Ejemplo n.º 17
0
def test_init_happy_path():
    args = Problem.default_args()
    args.name = '3sum'
    p = Problem(args)

    # misc attributes
    assert (p._verbose == False)

    # leetcode attributes
    assert (p._name == args.name)
    assert (p._url == problem.LEETCODE_URL_BASE + '/' + args.name)

    # github attributes
    assert (p._issue == -1)

    # problem attributes
    #assert(p._leetcode_number == -1)
    assert (p._problem_template == '')

    assert (p._difficulty == Difficulty.INVALID)

    assert (p._time == -1)
    assert (p._time_rank == -1)
    assert (p._time_complexity == '')

    assert (p._space == -1)
    assert (p._space_rank == -1)
    assert (p._space_complexity == '')
Ejemplo n.º 18
0
def initData():
   """Load data and mappings from Raw data files and mapping files"""
   Patient.load()
   Med.load()
   Problem.load()
   Lab.load()
   Refill.load()
Ejemplo n.º 19
0
    def solve(self, expr: str = ""):
        """solve cryptarithm problem"""
        print("Problem: {}".format(expr))

        p = Parser(tokenize(expr))
        pr = Problem(p.parse())
        print(pr.search_all_solution())
Ejemplo n.º 20
0
def program(app):
    while True:
        print()
        print('Please select an operation.')
        print()
        print('1. Add')
        print('2. Subtract')
        print('3. Multiply')
        print('4. Divide')

        option = get_integer_from_user('> ')
        operation = OPERATIONS.get(option, None)

        if operation:
            left = get_operand()
            right = get_operand()

            problem = Problem(operation(), left, right)

            result = str.format('{} = ?', problem.displayWithoutAnswer())
            print('Problem:', result)

            if app:
                app.memoryBank.add(problem)
        else:
            print('Please select a valid option.')

        if not get_should_continue('Do you wish to continue? [Y]es/[N]o: '):
            break
Ejemplo n.º 21
0
def main(params):
    conf = ModelConf('predict', params.conf_path, version, params, mode=params.mode)
    problem = Problem('predict', conf.problem_type, conf.input_types, None,
        with_bos_eos=conf.add_start_end_for_seq, tagging_scheme=conf.tagging_scheme, tokenizer=conf.tokenizer,
        remove_stopwords=conf.remove_stopwords, DBC2SBC=conf.DBC2SBC, unicode_fix=conf.unicode_fix)
        
    if os.path.isfile(conf.saved_problem_path):
        problem.load_problem(conf.saved_problem_path)
        logging.info("Problem loaded!")
        logging.debug("Problem loaded from %s" % conf.saved_problem_path)
    else:
        raise Exception("Problem does not exist!")

    if len(conf.predict_fields_post_check) > 0:
        for field_to_chk in conf.predict_fields_post_check:
            field, target = field_to_chk.split('@')
            if not problem.output_dict.has_cell(target):
                raise Exception("The target %s of %s does not exist in the training data." % (target, field_to_chk))

    lm = LearningMachine('predict', conf, problem, vocab_info=None, initialize=False, use_gpu=conf.use_gpu)
    lm.load_model(conf.previous_model_path)

    logging.info('Predicting %s with the model saved at %s' % (conf.predict_data_path, conf.previous_model_path))
    lm.predict(conf.predict_data_path, conf.predict_output_path, conf.predict_file_columns, conf.predict_fields)
    logging.info("Predict done! The predict result: %s" % conf.predict_output_path)
    def HillClimbing(self, n):
        p = Problem(n)
        queue = p.getMatrix()
        listOfPermutations = p.getListOfPermutations()
        print("I am going to print the best solution found: ")

        possible_solution = []
        row = 1
        while queue:
            row_state = queue.pop()

            next_state, listOfPermutations = p.expand(row_state,
                                                      listOfPermutations, row)
            possible_solution.append(next_state)

            print(possible_solution)
            time.sleep(0.5)

            row += 1

        fitnessOptim = p.fitness(possible_solution, n)
        p = PrettyTable()
        for row in possible_solution:
            p.add_row(row)
        pretty = p.get_string(header=False, border=False)

        return pretty, fitnessOptim
Ejemplo n.º 23
0
    def __init__(self, fleet, environment, global_planner=None, options=None, **kwargs):
        Problem.__init__(self, fleet, environment, options, label='schedulerproblem')
        self.curr_state = self.vehicles[0].prediction['state'] # initial vehicle position
        self.goal_state = self.vehicles[0].poseT # overall goal
        self.problem_options = options  # e.g. selection of problem type (freeT, fixedT)
        if not 'freeT' in options:
            # select default type
            self.problem_options['freeT'] = True
        self.start_time = 0.
        self.update_times=[]

        # save vehicle dimension, determines how close waypoints can be to the border
        shape = self.vehicles[0].shapes[0]
        if isinstance(shape, Circle):
            self.veh_size = shape.radius
            # used to check if vehicle fits completely in a cell
            # radius is only half the vehicle size
            size_to_check = self.veh_size*2
        elif isinstance(shape, Rectangle):
            self.veh_size = max(shape.width, shape.height)
            # veh_size is complete width or height for rectangular shape
            size_to_check = self.veh_size
        # margin, applied to vehicle size to avoid goal positions very close to the border
        self.margin = 1.1

        # assign global planner
        if global_planner is not None:
            # save the provided planner
            self.global_planner = global_planner
        else:
            # make a default global planner
            self.global_planner = AStarPlanner(environment, [20, 20], self.curr_state, self.goal_state)

        # frame settings
        self.frames = []
        self.cnt = 1  # frame counter
        self.n_frames = options['n_frames'] if 'n_frames' in options else 1  # amount of frames to combine

        if (self.n_frames > 1 and not self.problem_options['freeT']):
            raise ValueError('Fixed time problems are only supported for n_frames = 1')
        self._n_frames = self.n_frames  # save original value
        self.frame_type = options['frame_type'] if 'frame_type' in options else 'shift'
        # set frame size for frame_type shift
        if self.frame_type is 'shift':
            # by default frame size is set to 1/5 of total environment width
            self.frame_size = options['frame_size'] if 'frame_size' in options else environment.room[0]['shape'].width*0.2
            # by default move limit is set to 1/4 of frame size
            self.move_limit = options['move_limit'] if 'move_limit' in options else self.frame_size*0.25
        if self.frame_type is 'corridor':
            # scale up frame with small steps or not
            self.scale_up_fine = options['scale_up_fine'] if 'scale_up_fine' in options else True
            self.l_shape = options['l_shape'] if 'l_shape' in options else False
        # check if vehicle size is larger than the cell size
        n_cells = self.global_planner.grid.n_cells
        if (size_to_check >= (min(environment.room[0]['shape'].width/float(n_cells[0]), \
                                  environment.room[0]['shape'].height/float(n_cells[1])))
           and self.frame_type == 'corridor'):
            warnings.warn('Vehicle is bigger than one cell, this may cause problems' +
                          ' when switching frames. Consider reducing the amount of cells or reducing' +
                          ' the size of the vehicle')
Ejemplo n.º 24
0
 def reinitialize(self, father=None):
     if father is None:
         father = self.father
     Problem.reinitialize(self)
     for vehicle in self.vehicles:
         init = vehicle.get_init_spline_value()
         for k in range(vehicle.n_seg):
             father.set_variables(init[k], vehicle, 'splines_seg'+str(k))
Ejemplo n.º 25
0
 def reinitialize(self, father=None):
     if father is None:
         father = self.father
     Problem.reinitialize(self)
     for vehicle in self.vehicles:
         init = vehicle.get_init_spline_value()
         for k in range(vehicle.n_seg):
             father.set_variables(init[k], vehicle, 'splines_seg' + str(k))
Ejemplo n.º 26
0
def test_solver():
    alls = all_blocks()

    board = Board.random_board(2, 2, 4, 16)
    board.print()
    blocks = alls.get_blocklist().sublist(["BV", "BV", "BP", "BP"])
    problem = Problem(blocks, board)
    problem.print_ans()
Ejemplo n.º 27
0
def main():
    args = argparse().parse_args()

    p = Problem(args.input.read(), args.brain)
    p.solve()
    args.output.write(str(p) + "\n")

    exit(0)
Ejemplo n.º 28
0
def test_init_invalid_verbose():
    invalid = [None, 42, 'Foo']
    for i in invalid:
        with pytest.raises(ValueError, match=r'invalid verbosity ".*"'):
            args = Problem.default_args()
            args.name = 'abc'
            args.verbose = i
            p = Problem(args)
Ejemplo n.º 29
0
 def read(self):
     n, m, l, h = map(int, input().split())
     p = Problem(n, m, l, h)
     for i in range(n):
         row = input()
         for j in range(m):
             p.field[i][j] = row[j]
     return p
Ejemplo n.º 30
0
def getSolution(s):
    #s=getWords(s)
    brain_path = r"E://Reddit Data//Zoidberg-master//Zoidberg-master//.zoidberg.brain.json"
    #nltk.download()
    p = Problem(s, brain_path)
    solution = p.solve()
    d = {"solution": solution}
    return d
Ejemplo n.º 31
0
    def greedyBFSBattle(self, currentState, player):
        problemObj = Problem(currentState, self.boardValue, player)
        possibleStates = problemObj.possibleStates(currentState, player)
        stateCost = []
        for state in possibleStates:
            stateCost.append(problemObj.pathCost(state))

        nextState = possibleStates[stateCost.index(max(stateCost))]
        return nextState
def test():
    problem = Problem(id='6nXC7iyndcldO1dvKHbBmDHv',
                      size=6,
                      operators=frozenset(['not', 'shr4', 'shr16', 'shr1']))
    problem.solution = '(lambda (x_5171) (shr4 (shr16 (shr1 (not x_5171)))))'

    server = Server([problem])

    solve(problem, server)
def test():
    problem = Problem(
        id='6nXC7iyndcldO1dvKHbBmDHv',
        size=6, operators=frozenset(['not', 'shr4', 'shr16', 'shr1']))
    problem.solution = '(lambda (x_5171) (shr4 (shr16 (shr1 (not x_5171)))))'

    server = Server([problem])

    solve(problem, server)
Ejemplo n.º 34
0
 def test_greedy(self):
     # choose best path not first path
     p = Problem('greedy', 5, 10, 10, [('+', 1), ('+', 5)])
     r = (10, 1)
     TestGreedy._test_greedy(self, p, r)
     # choose a path that works
     p1 = Problem('greedy', 5, 10, 10, [('+', 1), ('*', 3)])
     r1 = (10, 5)
     TestGreedy._test_greedy(self, p1, r1)
Ejemplo n.º 35
0
 def greedyBFS(self):
     problemObj = Problem(self.initialState, self.boardValue, self.player)
     possibleStates = problemObj.possibleStates(self.initialState, self.player)
     stateCost = []
     for state in possibleStates:
         stateCost.append(problemObj.pathCost(state))
     nextState = possibleStates[stateCost.index(max(stateCost))]
     # self.printState(nextState)
     self.outputState(nextState)  # save output to a file.
Ejemplo n.º 36
0
 def testProblemGetDirichlet(self):
     width = 3
     height = 3
     [nodes, boundary_nodes, tris] = generateRectangularMesh((width, height), (0,0), (1,1))
     p = Problem(nodes, boundary_nodes, tris)
     data = p.getDirichletData(lambda x,y: x*y)
     self.assertEqual(data[0], 0)
     self.assertEqual(4 in data, True)
     self.assertEqual(2 in data, True)
Ejemplo n.º 37
0
    def greedyBFSBattle(self, currentState, player):
        problemObj = Problem(currentState, self.boardValue, player)
        possibleStates = problemObj.possibleStates(currentState, player)
        stateCost = []
        for state in possibleStates:
            stateCost.append(problemObj.pathCost(state))

        nextState = possibleStates[stateCost.index(max(stateCost))]
        return nextState
Ejemplo n.º 38
0
def main():
    problem = Problem("in.txt")
    algorithm = Algorithm(problem)
    stats, stddev = algorithm.run()
    survivors = [ x.fitness() for x in algorithm.getIndividuals() ]
    x = [x for x in range(0, problem.getItCount())]
    pyplot.plot(stats)
    pyplot.plot(stddev)
    pylab.show()
Ejemplo n.º 39
0
 async def addprob(self, ctx, problem_name):
     """Adds a problem. Only available to the bot owner."""
     if problem_name in problems:
         await ctx.send('Problem ' + problem_name + ' already exists.')
         return
     problems[problem_name] = Problem()
     problems[problem_name].cases = {}
     await ctx.send('Problem ' + problem_name + ' successfully added.')
     await write_problems()
Ejemplo n.º 40
0
 def __init__(self, fleet, environment, n_frames, options=None):
     Problem.__init__(self, fleet, environment, options, label='multiframeproblem')
     self.n_frames = n_frames
     if self.n_frames > len(self.environment.room):
         raise RuntimeError('Number of frames you want to consider at once is larger' +
                            'than the amount of rooms provided in environment')
     self.init_time = None
     self.start_time = 0.
     self.objective = 0.
Ejemplo n.º 41
0
def initls(coursesToTake,
           coursesTaken,
           electiveList,
           softconstraints,
           campus="Miagao"):
    variables = variableCourses(coursesToTake)
    domain = {}
    ############################################
    classOfferingList = classes.createClassesList("csv\\data.csv")
    # classOfferingList = classes.createClassesList("../csv/data.csv")
    ############################################
    semester = coursesToTake[0].semester
    classOfferingList = [
        classoffering for classoffering in classOfferingList if
        (classoffering.semester == semester and classoffering.campus == campus)
    ]

    for var in variables:
        domain[var] = sectioning.findSections(var, classOfferingList,
                                              electiveList, coursesTaken,
                                              campus)
    constraints = []
    c = NoConflictsConstraint(variables)
    c.name = 'No Conflicts'
    c.penalty = float('inf')
    constraints.append(c)

    constraints = constraints + softConstraintList(softconstraints, variables,
                                                   domain)
    problem = Problem(variables, domain, constraints, electiveList)
    problem.name = 'Local Search - Timetabling'
    problem.solution_format = solution_format

    config = common_config()
    config.objective_fn = count_penalty
    config.best_fn = min
    config.best_possible_score = 0
    config.initial_solution = 'random'
    config.respawn_solution = 'random'
    config.neighborhood_fn = change_upto_two_values
    ############################################
    config.explain = False
    # config.explain = True
    ############################################
    reverse = True
    hill_climbing_config(config, reverse)
    while True:
        solver = LocalSearchSolver(problem, config)
        solver.solve()
        if solver.solutions[0].score != float('inf'):
            break
    ############################################
    # display_solutions(problem, solver)
    ############################################

    return solver.solutions[0].solution, problem
Ejemplo n.º 42
0
 def construct(self):
     self.T, self.t = self.define_parameter('T'), self.define_parameter('t')
     self.t0 = self.t/self.T
     Problem.construct(self)
     for vehicle in self.vehicles:
         splines = vehicle.define_splines(n_seg=1)
         vehicle.define_trajectory_constraints(splines[0], self.T)
         self.environment.define_collision_constraints(vehicle, splines, self.T)
     if len(self.vehicles) > 1 and self.options['inter_vehicle_avoidance']:
         self.environment.define_intervehicle_collision_constraints(self.vehicles, self.T)
Ejemplo n.º 43
0
 def simulate(self, current_time, simulation_time, sample_time):
     horizon_time = self.options['horizon_time']
     if self.init_time is None:
         rel_current_time = np.round(current_time-self.start_time, 6) % self.knot_time
     else:
         rel_current_time = self.init_time
     if horizon_time - rel_current_time < simulation_time:
         simulation_time = horizon_time - rel_current_time
     self.compute_partial_objective(current_time, simulation_time)
     Problem.simulate(self, current_time, simulation_time, sample_time)
Ejemplo n.º 44
0
 def __init__(self, index, vehicle, problem, environment, distr_problem,
              options={}):
     Problem.__init__(self, vehicle, environment, options, label='admm')
     self.problem = problem
     self.distr_problem = distr_problem
     self.vehicle = vehicle
     self.environment = environment
     self.group = {child.label: child for child in ([
         vehicle, problem, environment, self] + environment.obstacles)}
     for child in self.group.values():
         child._index = index
def simulationLipton(sample_size,n,m,culture,verbose=False):
    d = fairnessDashboard()    
        
    for xp in range(sample_size):
        p = Problem(n,m,culture,centralized=True)
        protocols.lipton(p,verbose)
        if verbose:
            print(p)
            print (p.printAllocation()) # print the final allocation
        d.update(p)
    print(d)
    return
Ejemplo n.º 46
0
 def __init__(self, index, vehicle, problem, environment, distr_problem,
              label, options=None):
     Problem.__init__(self, vehicle, environment, options, label=label)
     self.problem = problem
     self.distr_problem = distr_problem
     self.vehicle = vehicle
     self.environment = environment
     self.group = col.OrderedDict()
     for child in ([vehicle, problem, environment, self] + environment.obstacles):
         self.group[child.label] = child
     for child in self.group.values():
         child._index = index
Ejemplo n.º 47
0
def initData():
   """Load data and mappings from Raw data files and mapping files"""
   Patient.load()
   Med.load()
   Problem.load()
   Lab.load()
   Refill.load()
   VitalSigns.load()
   Immunization.load()
   Procedure.load()
   SocialHistory.load()
   FamilyHistory.load()
   Allergy.load()
Ejemplo n.º 48
0
 def testProblemStiffness2(self):
     width = 4
     height = 4
     [nodes, boundary_nodes, tris] = generateRectangularMesh((width, height), (0,0), (1,1))
     p = Problem(nodes, boundary_nodes, tris)
     K = p.getStiffnessMatrix(lambda x,y: x*y)
     self.assertTrue((sparse.triu(K, 1).T.toarray() == sparse.tril(K,-1).toarray()).all())
     width = 5
     height = 5
     [nodes, boundary_nodes, tris] = generateRectangularMesh((width, height), (0,0), (1,1))
     p = Problem(nodes, boundary_nodes, tris)
     K = p.getStiffnessMatrix(lambda x,y: x*y)
     self.assertTrue((sparse.triu(K, 1).T.toarray() == sparse.tril(K,-1).toarray()).all())
Ejemplo n.º 49
0
    def __init__(self, fleet, environment, n_segments, options=None, **kwargs):
        Problem.__init__(self, fleet, environment, options, label='gcodeproblem')
        self.n_segments = n_segments  # amount of GCode commands to connect
        if self.n_segments > len(self.environment.room):
            raise RuntimeError('Number of segments to combine is larger than the amount of ' +
                               'GCode segments/rooms provided')
        self.init_time = None
        self.start_time = 0.
        self.objective = 0.

        # an initial guess for the motion time may be passed by the scheduler during problem creation
        if 'motion_time_guess' in kwargs:
            self.motion_time_guess = kwargs['motion_time_guess']
Ejemplo n.º 50
0
 def simulate(self, current_time, simulation_time, sample_time):
     horizon_time = self.father.get_variables(self, 'T')[0][0]
     if self.init_time is None:
         rel_current_time = 0.0
     else:
         rel_current_time = self.init_time
     if horizon_time < sample_time: # otherwise interp1d() crashes
         return
     if horizon_time < simulation_time:
         simulation_time = horizon_time
     if horizon_time - rel_current_time < simulation_time:
         simulation_time = horizon_time - rel_current_time
     self.compute_partial_objective(current_time+simulation_time-self.start_time)
     Problem.simulate(self, current_time, simulation_time, sample_time)
Ejemplo n.º 51
0
 def reinitialize(self, father=None):
     if father is None:
         father = self.father
     Problem.reinitialize(self)
     for vehicle in self.vehicles:
         # compute initial guess for all spline values
         subgoals = []
         for k in range(self.n_frames-1):
             room1 = self.environment.room[k]
             room2 = self.environment.room[k+1]
             # subgoals is given as initial position, center of overlap of regions and overall goal
             # compute center of overlap region of rooms
             subgoals.append(compute_rectangle_overlap_center(room1['shape'], room1['position'], room2['shape'], room2['position']))
         init = vehicle.get_init_spline_value(subgoals = subgoals)
         for k in range(self.n_frames):
             father.set_variables(init[k], vehicle, 'splines_seg'+str(k))
Ejemplo n.º 52
0
def main():
    parser = argparse.ArgumentParser()
    #parser.add_argument('-i','--input', help='help', default = 'cake.strips')
    parser.add_argument('-f','--input', help='help', default = 'domains/Blocks-Ground/')
    args = parser.parse_args()
    files_input = open(args.input+'files_input').read().split('\n')
    files_input = files_input[:len(files_input)-1]
    output_lines = []
    #print [file_name for file_name in files_input]
    for file_name in files_input:
        initial_time = clock()
        problem = Problem.read_strips(args.input+file_name)
        #problem = Problem.read_strips(args.input)
        time = 0
        while(True):
            time = time + 1
            variables, clauses = clauses_extractor(time, problem)
            export_cnf(variables, clauses)
            run_solver()
            if is_solution():
                plan = extract_plan(variables, problem.action_fluents)
                break
        output_line = [file_name] + [len(variables)] + [len(clauses)] + [len(plan)] + [clock()-initial_time] + [plan]
        output_list(output_line)
        output_lattex(output_line)
Ejemplo n.º 53
0
 def set_parameters(self, current_time):
     parameters = Problem.set_parameters(self, current_time)
     # current time is always 0 for FreeT problem, time axis always resets
     if self.init_time is None:
         parameters[self]['t'] = 0
     else:
         parameters[self]['t'] = self.init_time
     return parameters
Ejemplo n.º 54
0
	def load(self, puzzle_data):
		'''
		Check how the DataManager loads puzzle data if there is an issue here.
		'''
		self.puzzle_id = puzzle_data[0]
		self.name = puzzle_data[1]
		self.instructions = puzzle_data[2]
		self.app_path = puzzle_data[3]
		self.state = puzzle_data[4]

		# Load problems
		problems_data = self.data_mgr.get_problems_data(self.puzzle_id)
		for problem_data in problems_data:
			problem = Problem(self.data_mgr)
			problem.load(problem_data)
			
			self.problems.append(problem)
def simulationPickingSequences(sample_size,n,m,sequence,culture,verbose=False):
    '''
    for a given sequence, runs several simulations
    @sample_size: number of xps for each parameter configuration
    @n: nb of agents
    @m: nb of resources
    '''
    d = fairnessDashboard()    
    
    for xp in range(sample_size):
        p = Problem(n,m,culture,centralized=True)
        protocols.pickingSequence(p,sequence,verbose)
        if verbose:
            print(p)
            print (p.printAllocation())
        d.update(p)
    print(d)
    return
Ejemplo n.º 56
0
    def simulate(self, current_time, simulation_time, sample_time):
        # save global path and frame border
        # store trajectories
        if not hasattr(self, 'frame_storage'):
            self.frame_storage = []
            self.global_path_storage = []
        if simulation_time == np.inf:
            # using simulator.run_once()
            simulation_time = sum(self.motion_times)
        repeat = int(simulation_time/sample_time)
        # copy frames, to avoid problems when removing elements from self.frames
        frames_to_save = self.frames[:]
        for k in range(repeat):
            self._add_to_memory(self.frame_storage, frames_to_save)
        self._add_to_memory(self.global_path_storage, self.global_path, repeat)

        # simulate the multiframe problem
        Problem.simulate(self, current_time, simulation_time, sample_time)
Ejemplo n.º 57
0
class TestProblem(unittest.TestCase):
    def setUp(self):
        self.problem = Problem()
        self.candidate_solution = None

    def test_assess(self):
        try:
            self.problem.assess(self.candidate_solution)
        except UndefinedError:
            pass
        else:
            self.fail('Did not see UndefinedError')

    def test_is_optimal(self):
        try:
            self.problem.is_optimal(self.candidate_solution)
        except UndefinedError:
            pass
        else:
            self.fail('Did not see UndefinedError')
Ejemplo n.º 58
0
    def generate(self, rows, cols, seed=None):
        npr.seed(seed)

        problem = Problem()
        problem.dual = False
        problem.A = self.__getMatrixA(rows, cols)
        problem.b = self.__getVectorB(rows)
        problem.c = self.__getVectorC(cols)
        problem.base = range(cols, rows + cols)
        problem.nonBase = range(0, cols)
        problem.decVarCount = cols

        return problem
Ejemplo n.º 59
0
 def __init__(self, problem_id, src, mode="inline"):
     problems = Problem.load_problemset()
     self.src = src
     self.problem = None
     for problem in problems:
         if problem._id == problem_id:
             self.problem = problem
     self.error = None
     if mode=="inline":
         self.executor = self.inline_execute
     else: # mode == "thread"
         self.executor = self.thread_execute
Ejemplo n.º 60
0
    def _parseProblem(self, data):
        problem = Problem()
        problem.id = data[0]
        problem.title = data[1]
        problem.accepted = data[2]
        problem.submitted = data[3]
        problem.ratio = data[4]
        problem.source = data[5]

        return problem