Ejemplo n.º 1
0
    def mse_(self,x,y):

        X=matrix(x)
        y=matrix(y)

        sum1=0
        for n,i in enumerate(y.m_sub(X.m_mult(self.beta_vector))):
            sum1+=i[0]**2
        
        return sum1/n+1
Ejemplo n.º 2
0
    def fit(self,x,y):

        X=matrix(x)
        y=matrix(y)

        Xt=X.transpose()

        p1=Xt.m_mult(X).gauss_inv()
        p2=Xt.m_mult(X)
        print(p1,p2)

        self.alpha=p1.m_sub(p2)
Ejemplo n.º 3
0
    def mae_(self,x,y):


        X=matrix(x)
        y=matrix(y)

        sum1=0
        for n,i in enumerate(y.m_sub(X.m_mult(self.beta_vector))):
            if i[0]<0:
                i[0]=i[0]*(-1)
                sum1+=i[0]
            else:
                sum1+=i[0]
        
        return sum1/n+1
Ejemplo n.º 4
0
    def __init__(self, T, dyn, lanes=[], fences=[], roads=[], ncars=1):
        self.lanes = lanes
        self.fences = fences
        self.roads = roads
        self.robots = [Trajectory(T, dyn) for _ in range(ncars)]
        self.x0 = vector(4)
        self.human = {
            'A': Trajectory(T, dyn, self.x0),
            'B': Trajectory(T, dyn, self.x0)
        }

        self.bounds = {}
        uB = [(-2., 2.), (-1., 1.)]
        xB = [(-0.15, 0.15), (-0.1, 0.2), (math.pi * 0.4, math.pi * 0.6),
              (0., 1.)]
        for robot in self.robots:
            for u in robot.u:
                self.bounds[u] = uB
            self.bounds[robot.x[0]] = xB
        for human in self.human.values():
            for u in human.u:
                self.bounds[u] = uB
            self.bounds[human.x[0]] = xB

        self.w = vector(len(features))
        self.samples = matrix(0, len(features))
Ejemplo n.º 5
0
    def fit(self,x,y,use_constant=False):

        
        X=matrix(x)

        if use_constant==True:
            X=X.add_constant()


        Xt=X.transpose()
        y=matrix(y)
        
        self.beta_vector=Xt.m_mult(X).gauss_inv().m_mult(Xt).m_mult(y)
        
        self.constant=self.beta_vector[0][0]
        self.coefficients=matrix(self.beta_vector[1:])
Ejemplo n.º 6
0
    def post(self, request, *args, **kwargs):
        context = {}
        ports = [port.name for port in Port.objects.all()]
        self.start = request.POST['start']
        self.finish = request.POST['finish']
        self.medium = request.POST.getlist('medium', [])
        self.medium.extend([self.start, self.finish])
        self.ship = request.POST.get('ships')

        context['start'] = self.start
        context['finish'] = self.finish
        count_ports = len(ports)

        self.compress_data(ports)
        self.graph = matrix(count_ports, count_ports, self.MAX_INT)
        self.add_graph = matrix(count_ports, count_ports)
        self.f = matrix(2 ** count_ports, count_ports)

        edges = Edge.objects.all()
        for edge in edges:
            x = self.name_to_int(edge.from_port.name)
            y = self.name_to_int(edge.to_port.name)

            self.graph[x][y] = self.graph[y][x] = edge.dist
            self.add_graph[x][y] = self.add_graph[y][x] = {'dist': edge.dist, 'way': []}

        for x in range(count_ports):
            for y in range(count_ports):
                if x == y:
                    continue

                way, best_dist = dijkstra(self.graph, x, y, count_ports)
                self.add_graph[x][y] = {'dist': best_dist, 'way': way[::-1]}
                self.add_graph[y][x] = {'dist': best_dist, 'way': way}

        for x in range(count_ports):
            for y in range(count_ports):
                if x != y and self.add_graph[x][y]['way']:
                    self.graph[x][y] = self.add_graph[x][y]['dist']
                    self.graph[y][x] = self.add_graph[y][x]['dist']

        import time

        start_time = time.time()
        self.dfs(mask=2 ** self.name_to_int(self.start),
                 node=self.name_to_int(self.start),
                 dist=0)
        context['time_of_execution'] = round(time.time() - start_time, 3)

        finish = self.name_to_int(self.finish)
        mask, context['total_dist'] = self.get_min_dist(count_ports, finish)

        if mask == 0:
            return JsonResponse({'status': 'error', 'msg': u'Невозможно построить заданный путь'})

        context['way'] = self.recovery_way(mask, finish)
        if self.ship:
            context['ship_speed'] = self.get_ship_speed(self.ship)
            context['img_name'] = self.get_img_name()
        print self.get_img_name()

        return JsonResponse({'status': 'ok',
                             'data': context})
Ejemplo n.º 7
0
    def __init__(
        self,
        dom: domain.Domain,
        num_queries: int,
        query_length: int,
        num_expectation_samples: int,
        include_previous_query: bool,
        generate_scenario: bool,
        objective_fn: ObjectiveFunctionType,
        beta_pref: float,
    ) -> None:
        assert num_queries >= 1, \
            "QueryGenerator.__init__: num_queries must be at least 1"
        assert query_length >= 1, \
            "QueryGenerator.__init__: query_length must be at least 1"
        assert num_expectation_samples >= 1, \
            "QueryGenerator.__init__: num_expectation_samples must be \
                at least 1"

        self.domain = dom
        self.num_queries = num_queries
        self.query_length = query_length
        self.num_expectation_samples = num_expectation_samples
        self.include_previous_query = include_previous_query
        self.generate_scenario = generate_scenario
        self.objective_fn = objective_fn
        self.beta_pref = beta_pref

        # Variable to store the built computation graph. Set in self.optimizer.
        self._optimizer = None
        # List of variables to optimize.
        self._variables: typing.List[tt.TensorVariable] = []
        # List of bounds for variables.
        self._bounds: typing.Dict[tt.TensorVariable, domain.BoundsType] = {}

        self.num_generated_queries = self.num_queries
        if self.include_previous_query:
            self.num_generated_queries = self.num_queries - 1

        # xs[<query>][<time>][<agent>]
        self.xs: typing.List[typing.List[typing.List[tt.TensorVariable]]] = []
        # us[<query>][<time>][<agent>]
        self.us: typing.List[typing.List[typing.List[tt.TensorVariable]]] = []
        if self.include_previous_query:
            # previous_x0s[<agent>]
            self.previous_x0s: typing.List[tt.TensorVariable] = \
                [utils.vector(self.domain.state_size,
                              name="previous_x0s[%d]" % (i))
                 for i in range(self.domain.num_agents)]

            # previous_us[<time>][<agent>]
            self.previous_us: typing.List[typing.List[tt.TensorVariable]] = \
                [[utils.vector(self.domain.control_size,
                               name="previous_us[%d][%d]" % (t, i))
                  for i in range(self.domain.num_agents)]
                 for t in range(self.query_length)]

            # previous_xs[<time>][<agent>]
            self.previous_xs: typing.List[tt.TensorVariable] = \
                [self.previous_x0s]

            for t in range(1, self.query_length):
                xs = self.previous_xs[t - 1]
                us = self.previous_us[t - 1]
                f = self.domain.dynamics_function
                self.previous_xs.append(
                    [f(xs[i], us[i]) for i in range(self.domain.num_agents)])

            self.us.append(self.previous_us)
            self.xs.append(self.previous_xs)

        # x0s[<agent>]
        self.x0s = [
            utils.vector(self.domain.state_size, name="x0s[%d]" % (i))
            for i in range(self.domain.num_agents)
        ]
        # other_us[<time>][<agent>]
        self.other_us = [[
            utils.vector(self.domain.control_size,
                         name="other_us[t=%d][agent=%d]" % (t, i))
            for i in range(self.domain.num_others)
        ] for t in range(self.query_length)]
        # query_us[<query>][<time>]
        self.query_us = [[
            utils.vector(self.domain.control_size,
                         name="query_us[query=%d][t=%d]" % (i, t))
            for t in range(self.query_length)
        ] for i in range(self.num_generated_queries)]

        if self.generate_scenario:
            for i in range(self.domain.num_agents):
                v = self.x0s[i]
                self._variables.append(v)
                self._bounds[v] = self.domain.state_bounds

        for t in range(self.query_length):
            for i in range(self.domain.num_others):
                v = self.other_us[t][i]
                self._variables.append(v)
                self._bounds[v] = self.domain.control_bounds

        for i in range(self.num_generated_queries):
            for t in range(self.query_length):
                v = self.query_us[i][t]
                self._variables.append(v)
                self._bounds[v] = self.domain.control_bounds

        for i in range(self.num_generated_queries):
            # merged_us[time][agent]
            merged_us = []
            for t in range(self.query_length):
                us_t = [self.query_us[i][t]]
                for j in range(self.domain.num_others):
                    us_t.append(self.other_us[t][j])
                merged_us.append(us_t)

            self.us.append(merged_us)

            query_xs = [self.x0s]
            for t in range(1, self.query_length):
                xs = query_xs[t - 1]
                us = merged_us[t - 1]
                f = self.domain.dynamics_function
                query_xs.append(
                    [f(xs[i], us[i]) for i in range(self.domain.num_agents)])

            self.xs.append(query_xs)

        # The features summed over the trajectory.
        self.traj_features_list = [
            sum_trajectory_features(
                self.domain, self.query_length,
                [self.xs[i][t][0] for t in range(self.query_length)],
                [self.xs[i][t][1:] for t in range(self.query_length)])
            for i in range(self.num_queries)
        ]
        # traj_features is dimension num_queries by num_features
        self.traj_features = tt.stack(self.traj_features_list)

        # The samples of the weight vector, used to approximate
        # the expectation in our objective.
        self.w_samples = utils.matrix(self.num_expectation_samples,
                                      self.domain.feature_size,
                                      name="w_samples")

        self._objective = self.objective_fn(self.num_queries,
                                            self.num_expectation_samples,
                                            self.w_samples, self.traj_features,
                                            self.beta_pref)

        print("Compiling Optimizer")
        self.optimizer()
        print("Finished Compiling Optimizer")
 N = int(opts.get('-n', 200))
 S = int(opts.get('-s', 2000))
 P = float(opts.get('-p', 1.))
 method = int(opts.get('-m', 0))
 if method == 4:
     world.avg_case = True
 phis = []
 '''db['W'] = W
 db['N'] = N
 db['S'] = S
 db['P'] = P
 db['method'] = method'''
 if method == 2:
     f = vector(len(W))
     phi = f / tt.maximum(1., f.norm(2))
     A = matrix(0, len(W))
     y = tt.dot(A, phi)
     p = tt.sum(tt.switch(y < 0, 1., 0.))
     q = tt.sum(tt.switch(y > 0, 1., 0.))
     #obj = tt.minimum(tt.sum(1.-tt.exp(-tn.relu(y))), tt.sum(1.-tt.exp(-tn.relu(-y))))
     obj = p * tt.sum(1. - tt.exp(-tn.relu(y))) + q * tt.sum(
         1. - tt.exp(-tn.relu(-y)))
     optimizer = Maximizer(obj, [f])
 if method == 5:
     cand_phis = []
     for i in range(50):
         x = np.random.normal(size=len(W))
         cand_phis.append(x / np.linalg.norm(x))
 if method == 6:
     cand_phis = []
     for i in range(50):
Ejemplo n.º 9
0
 def predict(self,x):
     
     X=matrix(x)
     return X.m_mult(self.beta_vector)
Ejemplo n.º 10
0
 def __init__(self, D):
     self.D = D
     self.Avar = matrix(0, self.D)
     x = tt.vector()
     self.f = th.function([x], -tt.sum(tn.relu(tt.dot(self.Avar, x))))
Ejemplo n.º 11
0
 def __init__(self, D):
     self.D = D
     self.Avar = matrix(0, self.D)
     self.yvar = matrix(0, 1)
     x = tt.vector()
     self.f = th.function([x], -tt.sum(tn.relu(tt.dot(-tt.tile(self.yvar,[1,D])*self.Avar, x))))