def _time_step(time, output_ta_t, states):
        """Take a time step of the dynamic RNN.

    Args:
      time: int32 scalar Tensor.
      output_ta_t: List of `TensorArray`s that represent the output.
      state: nested tuple of vector tensors that represent the state.

    Returns:
      The tuple (time + 1, output_ta_t with updated flow, new_state).
    """
        if in_graph_mode:
            input_t = tuple(ta.read(time) for ta in input_ta)
            # Restore some shape information
            for input_, shape in zip(input_t, inputs_got_shape):
                input_.set_shape(shape[1:])
        else:
            input_t = tuple(ta[time.numpy()] for ta in input_ta)

        input_t = nest.pack_sequence_as(structure=inputs,
                                        flat_sequence=input_t)
        row_time = time % width
        states_1 = control_flow_ops.cond(math_ops.less(time, width),
                                         lambda: states.read(time_steps),
                                         lambda: states.read(time - width))
        states_2 = control_flow_ops.cond(math_ops.equal(row_time, 0),
                                         lambda: states.read(time_steps),
                                         lambda: states.read(time - 1))

        call_cell = lambda: cell(input_t, tuple((states_1, states_2)))
        if sequence_length is not None:
            (output,
             new_state) = _rnn_step(time=row_time,
                                    sequence_length=sequence_length,
                                    min_sequence_length=min_sequence_length,
                                    max_sequence_length=max_sequence_length,
                                    zero_output=zero_output,
                                    state=state,
                                    call_cell=call_cell,
                                    state_size=state_size,
                                    skip_conditionals=True)
        else:
            (output, new_state) = call_cell()

        # Pack state if using state tuples
        output = nest.flatten(output)
        if in_graph_mode:
            output_ta_t = tuple(
                ta.write(time, out) for ta, out in zip(output_ta_t, output))
            states = states.write(time, new_state)
        else:
            for ta, out in zip(output_ta_t, output):
                ta[time.numpy()] = out

        return (time + 1, output_ta_t, states)
Example #2
0
def visualize(time, true_y, pred_y, odefunc, itr, loss):

    if args.viz:



        ax_traj.cla()
        ax_traj.set_title('Trajectories')
        ax_traj.set_xlabel('t')
        ax_traj.set_ylabel('x')
        ax_traj.plot(time.numpy(), pred_y.numpy()[:, 0, 0], 'r--', time.numpy(), true_y.numpy()[:, 0, 0], 'k-')
        ax_traj.set_xlim(time.min(), time.max())
        ax_traj.plot(time.numpy(), pred_y.numpy()[:, 0, 1], 'r--', time.numpy(), true_y.numpy()[:, 0, 1], 'k-')
        ax_traj.legend()

        axy_phase.cla()
        axy_phase.set_title('Phase Portrait')
        axy_phase.set_xlabel('x')
        axy_phase.set_ylabel('y')
        axy_phase.plot(true_y.numpy()[:, 0, 0], true_y.numpy()[:, 0, 1], 'r--')
        axy_phase.plot(pred_y.numpy()[:, 0, 0], pred_y.numpy()[:, 0, 1], 'k-')
        if args.ode_nums == 3:
            ay_traj.cla()
            ay_traj.set_title('Trajectories')
            ay_traj.set_xlabel('t')
            ay_traj.set_ylabel('y')
            ay_traj.plot(time.numpy(), pred_y.numpy()[:, 0, 1], 'r--', time.numpy(), true_y.numpy()[:, 0, 1], 'k-')
            ay_traj.set_xlim(time.min(), time.max())
            # ax_traj.set_ylim(-2, 2)
            ay_traj.legend()
            az_traj.cla()
            az_traj.set_title('Trajectories')
            az_traj.set_xlabel('t')
            az_traj.set_ylabel('z')
            az_traj.plot(time.numpy(), pred_y.numpy()[:, 0, 2], 'r--', time.numpy(), true_y.numpy()[:, 0, 2], 'k-')
            az_traj.set_xlim(time.min(), time.max())
            # ax_traj.set_ylim(-2, 2)
            az_traj.legend()


            axz_phase.cla()
            axz_phase.set_title('Phase Portrait')
            axz_phase.set_xlabel('x')
            axz_phase.set_ylabel('z')
            axz_phase.plot(true_y.numpy()[:, 0, 0], true_y.numpy()[:, 0, 2], 'r--')
            axz_phase.plot(pred_y.numpy()[:, 0, 0], pred_y.numpy()[:, 0, 2], 'k-')

            ayz_phase.cla()
            ayz_phase.set_title('Phase Portrait')
            ayz_phase.set_xlabel('y')
            ayz_phase.set_ylabel('z')
            ayz_phase.plot(true_y.numpy()[:, 0, 1], true_y.numpy()[:, 0, 2], 'r--')
            ayz_phase.plot(pred_y.numpy()[:, 0, 1], pred_y.numpy()[:, 0, 2], 'k-')

        fig.tight_layout()
        plt.savefig('png{}/{}.jpg'.format(args.CASE,itr))
Example #3
0
    def ILP_R_stat(self, head, relation, tail, time, Type):
        head_embedding = self.Transmit.entity_embeddings(torch.tensor([head]))
        relation_embedding = self.Transmit.relation_embeddings(
            torch.tensor([relation]))
        tail_embedding = self.Transmit.entity_embeddings(torch.tensor([tail]))

        target_loss = torch.norm(
            head_embedding + relation_embedding - tail_embedding,
            self.norm).repeat(self.numOfRelation, 1)
        C_1 = self.overlap_constrain(head, relation, tail, time.numpy())
        C_2_pre = self.order_constrain(head, relation, tail, time.numpy(),
                                       "pre")
        C_2_aft = self.order_constrain(head, relation, tail, time.numpy(),
                                       "aft")

        if C_1 * C_2_pre * C_2_aft == 0 or (float(target_loss[0])) > 11:
            target_loss = torch.FloatTensor([1000
                                             ]).repeat(self.numOfRelation, 1)
        head_embedding = head_embedding.repeat(self.numOfRelation, 1)
        tail_embedding = tail_embedding.repeat(self.numOfRelation, 1)

        tmpRelationLoss = torch.norm(
            head_embedding + self.Transmit.relation_embeddings.weight.data -
            tail_embedding, self.norm, 1).view(-1, 1)
        ILP_list_r = list()

        for j in range(self.numOfRelation):

            C_1 = self.overlap_constrain(head, int(j), tail, time.numpy())
            C_2_pre = self.order_constrain(head, int(j), tail, time.numpy(),
                                           "pre")
            C_2_aft = self.order_constrain(head, int(j), tail, time.numpy(),
                                           "aft")

            if C_1 * C_2_pre * C_2_aft == 0 or (float(
                    tmpRelationLoss[j])) > 11:
                ILP_list_r.append([10000])
            else:
                ILP_list_r.append([0])

        ILP_tensor_r = torch.FloatTensor(ILP_list_r)
        tmpRelationLoss = tmpRelationLoss + ILP_tensor_r

        wrongRelation = torch.nonzero(
            nn.functional.relu(target_loss - tmpRelationLoss))

        print(wrongRelation.size()[0])
        for tmp in wrongRelation:
            print(tmp[0])
Example #4
0
def visualize(vt, true_y, pred_y, odefunc, itr, loss):

    if args.viz:

        ax_traj.cla()
        ax_traj.set_title('Trajectories')
        ax_traj.set_xlabel('t')
        ax_traj.set_ylabel('x')
        for i in range(len(indexv)):
            if i == 0:
                ax_traj.plot(vt[i].numpy(),
                             pred_y.numpy()[:indexv[i] + 1, 0, 0], 'r--',
                             vt[i].numpy(),
                             true_y.numpy()[:indexv[i] + 1, 0, 0], 'k-')
            else:
                ax_traj.plot(
                    vt[i].numpy(),
                    pred_y.numpy()[indexv[i - 1] + 1:indexv[i] + 1, 0,
                                   0], 'r--', vt[i].numpy(),
                    true_y.numpy()[indexv[i - 1] + 1:indexv[i] + 1, 0, 0],
                    'k-')
        ax_traj.legend()

        ay_traj.cla()
        ay_traj.set_title('Trajectories')
        ay_traj.set_xlabel('t')
        ay_traj.set_ylabel('y')
        for i in range(len(indexv)):
            if i == 0:
                ay_traj.plot(vt[i].numpy(),
                             pred_y.numpy()[:indexv[i] + 1, 0, 1], 'r--',
                             vt[i].numpy(),
                             true_y.numpy()[:indexv[i] + 1, 0, 1], 'k-')
            else:
                ay_traj.plot(
                    vt[i].numpy(),
                    pred_y.numpy()[indexv[i - 1] + 1:indexv[i] + 1, 0,
                                   1], 'r--', vt[i].numpy(),
                    true_y.numpy()[indexv[i - 1] + 1:indexv[i] + 1, 0, 1],
                    'k-')
        ay_traj.legend()

        if args.variable_nums == 3:
            ay_traj.cla()
            ay_traj.set_title('Trajectories')
            ay_traj.set_xlabel('t')
            ay_traj.set_ylabel('y')
            ay_traj.plot(time.numpy(),
                         pred_y.numpy()[:, 0, 1], 'r--', time.numpy(),
                         true_y.numpy()[:, 0, 1], 'k-')
            ay_traj.set_xlim(time.min(), time.max())
            # ax_traj.set_ylim(-2, 2)
            ay_traj.legend()
            az_traj.cla()
            az_traj.set_title('Trajectories')
            az_traj.set_xlabel('t')
            az_traj.set_ylabel('z')
            az_traj.plot(time.numpy(),
                         pred_y.numpy()[:, 0, 2], 'r--', time.numpy(),
                         true_y.numpy()[:, 0, 2], 'k-')
            az_traj.set_xlim(time.min(), time.max())
            # ax_traj.set_ylim(-2, 2)
            az_traj.legend()

            axz_phase.cla()
            axz_phase.set_title('Phase Portrait')
            axz_phase.set_xlabel('x')
            axz_phase.set_ylabel('z')
            axz_phase.plot(true_y.numpy()[:, 0, 0],
                           true_y.numpy()[:, 0, 2], 'r--')
            axz_phase.plot(pred_y.numpy()[:, 0, 0],
                           pred_y.numpy()[:, 0, 2], 'k-')

            ayz_phase.cla()
            ayz_phase.set_title('Phase Portrait')
            ayz_phase.set_xlabel('y')
            ayz_phase.set_ylabel('z')
            ayz_phase.plot(true_y.numpy()[:, 0, 1],
                           true_y.numpy()[:, 0, 2], 'r--')
            ayz_phase.plot(pred_y.numpy()[:, 0, 1],
                           pred_y.numpy()[:, 0, 2], 'k-')

        fig.tight_layout()
        plt.savefig('png{}/{}.jpg'.format(args.CASE, itr))
Example #5
0
    def sample(self, sim, indices=None, samples=1000):
        if sim.N_real < 4:
            raise AttributeError(
                "SPOCK Error: SPOCK only works for systems with 3 or more planets"
            )
        if indices:
            if len(indices) != 3:
                raise AttributeError(
                    "SPOCK Error: indices must be a list of 3 particle indices"
                )
            trios = [indices]  # always make it into a list of trios to test
        else:
            trios = [[i, i + 1, i + 2] for i in range(1, sim.N_real - 2)
                     ]  # list of adjacent trios

        ic(trios)
        kwargs = OrderedDict()
        kwargs['Norbits'] = int(1e4)
        kwargs['Nout'] = 1000
        kwargs['trios'] = trios
        args = list(kwargs.values())
        # These are the .npy.
        # In the other file, we concatenate (restseries, orbtseries, mass_array)
        tseries, stable = get_extended_tseries(sim, args)

        if not stable:
            return None

        tseries = np.array(tseries)
        simt = sim.copy()
        alltime = []
        for i, trio in enumerate(trios):
            sim = simt.copy()
            # These are the .npy.
            # In the other file, we concatenate (restseries, orbtseries, mass_array)
            cur_tseries = tseries[None, i, ::10]
            mass_array = np.array(
                [sim.particles[j].m / sim.particles[0].m for j in trio])
            X = data_setup_kernel(mass_array, cur_tseries)
            X = self.ssX.transform(X.reshape(-1, X.shape[-1])).reshape(X.shape)
            X = torch.tensor(X).float()
            if self.cuda:
                X = X.cuda()

            time = torch.cat(
                [self.sample_full_swag(X)[None] for _ in range(samples)],
                dim=0).detach()

            if self.cuda:
                time = time.cpu()

            time = time.numpy()
            alltime.append(time)

        out = np.array(alltime)[..., 0, :]
        mu = out[..., 0]
        std = out[..., 1]

        #Old:
        # a = (4 - mu)/std
        # b = np.inf
        # try:
        # samples = truncnorm.rvs(a, b)*std + mu
        # except ValueError:
        # return None
        # first_inst = np.min(samples, 0)
        # return first_inst

        #HACK - should this be inf at the top?
        # a, b = (4 - out[..., 0]) / out[..., 1], np.inf #(12 - out[..., 0]) / out[..., 1]
        # try:
        # samples = truncnorm.rvs(a, b, loc=out[..., 0], scale=out[..., 1])
        # except ValueError:
        # return None
        # return np.min(samples, 0)

        return mu, std