示例#1
0
    def get_loss(self):
        """ Attach the relevant loss depending on the type of loss selected """

        if F.loss_type == "cosine":
            self.losscos = r2d * tf.acos(1 - tf.losses.cosine_distance(
                tf.nn.l2_normalize(self.labels, 1),
                tf.nn.l2_normalize(self.out, 1),
                dim=1))
            self.loss = tf.losses.cosine_distance(
                tf.nn.l2_normalize(self.labels, 1),
                tf.nn.l2_normalize(self.out, 1),
                dim=1)
        elif F.loss_type == "mse2d":
            xl, yl, zl = tf.split(self.labels, 3, axis=1)
            xo, yo, zo = tf.split(self.out, 3, axis=1)
            thetal, thetao = tf.asin(-yl), tf.asin(-yo)
            phil, phio = tf.atan2(-zl, -xl), tf.atan2(-zo, -xo)
            self.lb = tf.concat([thetal, phil], axis=1)
            self.ob = tf.concat([thetao, phio], axis=1)
            self.loss = tf.scalar_mul(
                tf.constant(r2d),
                tf.losses.mean_squared_error(self.lb, self.ob, 2))
        elif F.loss_type == "mse3d":
            self.loss = tf.losses.mean_squared_error(
                tf.nn.l2_normalize(self.labels, 0),
                tf.nn.l2_normalize(self.out, 0))
示例#2
0
def g(rho, mu1, mu2):
    one_plus_sqrt_one_minus_rho_sqr = (1.0 + tf.sqrt(1.0 - rho * rho))
    a = tf.asin(rho) - rho / one_plus_sqrt_one_minus_rho_sqr
    safe_a = tf.abs(a) + HALF_EPSILON
    safe_rho = tf.abs(rho) + EPSILON

    A = a / twopi
    sxx = safe_a * one_plus_sqrt_one_minus_rho_sqr / safe_rho
    one_ovr_sxy = (tf.asin(rho) - rho) / (safe_a * safe_rho)

    return A * tf.exp(-(mu1 * mu1 + mu2 * mu2) /
                      (2.0 * sxx) + one_ovr_sxy * mu1 * mu2)
示例#3
0
def Gabor_filter(Theta, Lambda, Fai, Sigma, Gamma, size, in_channel,
                 out_channel):

    Theta_num = tf.shape(Theta)[0]
    Lambda_num = tf.shape(Lambda)[0]
    print Theta_num

    coordinate_begin = -(size - 1) / 2.0
    coordinate_end = -coordinate_begin
    tmp = tf.linspace(coordinate_begin, coordinate_end, size)
    tmp = Expand_dim_down(tmp, 3)
    x = tf.tile(tmp, [size, 1, in_channel, out_channel])
    x = tf.reshape(x, [size, size, in_channel, out_channel])
    y = tf.tile(tmp, [1, size, in_channel, out_channel])

    Theta = tf.reshape(tf.tile(tf.expand_dims(Theta, 0), [Lambda_num, 1]),
                       [-1])
    Lambda = tf.reshape(tf.tile(tf.expand_dims(Lambda, 1), [1, Theta_num]),
                        [-1])

    Theta = tf.tile(Expand_dim_up(Theta, 3), [size, size, in_channel, 1])
    Lambda = tf.tile(Expand_dim_up(Lambda, 3), [size, size, in_channel, 1])

    Sigma = tf.multiply(0.56, Lambda)

    x_ = tf.add(tf.multiply(x, tf.cos(Theta)), tf.multiply(y, tf.sin(Theta)))
    y_ = tf.add(-tf.multiply(x, tf.sin(Theta)), tf.multiply(y, tf.cos(Theta)))
    pi = tf.asin(1.0) * 2

    res = tf.multiply(
        tf.exp(-tf.div(tf.add(tf.square(x_), tf.square(y_)),
                       tf.multiply(2.0, tf.square(Sigma)))),
        tf.cos(2.0 * pi * x_ / Lambda))
    print tf.shape(res).eval()
    return res
示例#4
0
def haversine_dist(X, X2, sparse=False):
    pi = np.pi / 180
    if sparse:
        row_i = np.array([], dtype=int)
        col_i = np.array([], dtype=int)
        data = np.array([])
        for i in range(X.shape[0]):
            loc = np.argwhere(((X[i, 0] - X2[:, 0])**2 +
                               (X[i, 1] - X2[:, 1])**2) < 5)[:, 0]
            d = np.sin(X2[loc, 1] * pi - X[i, 1] * pi)**2
            d += np.cos(X[i, 1] * pi) * np.cos(
                X2[loc, 1] * pi) * np.sin(X2[loc, 0] * pi - X[loc, 0] * pi)**2
            d = 2 * 6371 * np.arcsin(np.sqrt(d))
            row_i = np.append(row_i, i + 0 * loc)
            col_i = np.append(col_i, loc)
            data = np.append(data, d)
        return (data, row_i, col_i)
    else:
        f = tf.expand_dims(X * pi, -2)  # ... x N x 1 x D
        f2 = tf.expand_dims(X2 * pi, -3)  # ... x 1 x M x D
        d = tf.sin((f - f2) / 2)**2
        lat1, lat2 = tf.expand_dims(X[:, 0] * pi, -1), \
                    tf.expand_dims(X2[:, 0] * pi, -2)
        cos_prod = tf.cos(lat2) * tf.cos(lat1)
        a = d[:, :, 0] + cos_prod * d[:, :, 1]
        c = tf.asin(tf.sqrt(a)) * 6371 * 2
        return c
def quat_to_euler(q):  #tf array [qw,qx,qy,qz] as the data is in this format
    shape = q.get_shape()
    bs = int(shape[0])
    w = q[:, 0]
    x = q[:, 1]
    y = q[:, 2]
    z = q[:, 3]
    ysqr = y * y
    # roll (x-axis rotation)
    t0 = +2.0 * (w * x + y * z)
    t1 = +1.0 - 2.0 * (x * x + ysqr)
    roll = tf.reshape(tf.atan(t0 / t1),
                      [bs, 1])  #atan2 to atan to get angles in +/-pi

    # pitch (y-axis rotation)
    t2 = +2.0 * (w * y - z * x)
    t2 = tf.where(tf.greater(t2, 1), tf.zeros_like(t2) + 1, t2)
    t2 = tf.where(tf.less(t2, -1), tf.zeros_like(t2) - 1, t2)
    pitch = tf.reshape(tf.asin(t2), [bs, 1])
    # yaw (z-axis rotation)
    t3 = +2.0 * (w * z + x * y)
    t4 = +1.0 - 2.0 * (ysqr + z * z)
    yaw = tf.reshape(tf.atan(t3 / t4),
                     [bs, 1])  #atan2 to atan to get angles in +/-pi
    return (roll, pitch, yaw)
示例#6
0
def get_unary_op(x, option):
    unary_ops = {
        'log': tf.log(x),
        'exp': tf.exp(x),
        'neg': tf.negative(x),
        'ceil': tf.ceil(x),
        'floor': tf.floor(x),
        'log1p': tf.log1p(x),
        'sqrt': tf.sqrt(x),
        'square': tf.square(x),
        'abs': tf.abs(x),
        'relu': tf.nn.relu(x),
        'elu': tf.nn.elu(x),
        'selu': tf.nn.selu(x),
        'leakyRelu': tf.nn.leaky_relu(x),
        'sigmoid': tf.sigmoid(x),
        'sin': tf.sin(x),
        'cos': tf.cos(x),
        'tan': tf.tan(x),
        'asin': tf.asin(x),
        'acos': tf.acos(x),
        'atan': tf.atan(x),
        'sinh': tf.sinh(x),
        'cosh': tf.cosh(x),
        'tanh': tf.tanh(x),
    }

    assert option in unary_ops, 'Unary option not found: ' + option
    return unary_ops[option]
def create_spiral(phi, jitter, coils, rotation, n=100):
    """
    Samples equidistant points from a 2D spiral with gaussian noise
    :param n: number of sample points
    :param coils: parameter to adjust number of coils
    :param phi: angular velocity
    :param jitter: standard deviation of gaussian noise
    :param rotation: rotation of the spiral
    :return: the generated spiral
    """
    # adjust start sample for arcsin (which is defined on [-1, 1])
    roll = tf.range(coils**2, n + coils**2, dtype=tf.float64)
    roll = tf.sqrt(roll)
    angles = tf.cumsum(tf.asin(coils / roll)) + rotation
    roll = tf.stack([
        -tf.cos(phi * angles) * roll + 0.5,
        tf.sin(phi * angles) * roll + 0.5
    ],
                    axis=-1)
    roll += tf.random.normal(shape=roll.shape,
                             mean=0,
                             stddev=jitter,
                             dtype=tf.float64)

    return roll
def cal_lola(X):
    x_head, x_eye = X
    head_lo = x_head[:, 0]
    head_la = x_head[:, 1]
    eye_lo = x_eye[:, 0]
    eye_la = x_eye[:, 1]
    cA = K.cos(head_lo / 180 * np.pi)
    sA = K.sin(head_lo / 180 * np.pi)
    cB = K.cos(head_la / 180 * np.pi)
    sB = K.sin(head_la / 180 * np.pi)
    cC = K.cos(eye_lo / 180 * np.pi)
    sC = K.sin(eye_lo / 180 * np.pi)
    cD = K.cos(eye_la / 180 * np.pi)
    sD = K.sin(eye_la / 180 * np.pi)
    g_x = -cA * sC * cD + sA * sB * sD - sA * cB * cC * cD
    g_y = cB * sD + sB * cC * cD
    g_z = sA * sC * cD + cA * sB * sD - cA * cB * cC * cD
    gaze_lo = tf.atan2(-g_x, -g_z) * 180.0 / np.pi
    gaze_la = -tf.asin(g_y) * 180.0 / np.pi
    gaze_la = tf.expand_dims(gaze_la, dim=1)
    gaze_lo = tf.expand_dims(gaze_lo, dim=1)
    #gaze_lo = gaze_lo.unsqueeze(1)
    #gaze_la = gaze_la.unsqueeze(1)
    gaze_lola = tf.concat((gaze_lo, gaze_la), 1)
    return gaze_lola
 def streetview_pixel_to_world_coordinates(self, lat1, lng1, yaw,
                                           image_width, image_height, x, y):
     camera_height = self.GOOGLE_CAR_CAMERA_HEIGHT  # ballpark estimate of the number of meters that camera is off the ground
     pitch = float(0)
     look_at_angle = x * (2 * math.pi) / image_width
     height = 0
     tilt_angle = (image_height / 2 - y) * math.pi / image_height + pitch
     tilt_angle = tf.cast(tilt_angle, tf.float32)
     z_ = K.minimum(np.float32(-1e-2), tilt_angle)
     z = (-camera_height) / tf.tan(z_)
     dx = tf.sin(look_at_angle - math.pi + yaw) * z / self.EARTH_RADIUS
     dy = tf.cos(look_at_angle - math.pi + yaw) * z / self.EARTH_RADIUS
     lat = lat1 + tf.asin(dy) * (180 / self.MATH_PI)
     lng = lng1 + tf.asin(
         dx / tf.cos(lat1 * (self.MATH_PI / 180))) * (180 / self.MATH_PI)
     return lat, lng
示例#10
0
def Gabor_filter(Theta, Lambda, size, in_channel, out_channel):
    # TODO use tf.meshgird instead of code as followed
    coordinate_begin = - (size - 1) / 2.0
    coordinate_end = - coordinate_begin
    tmp = tf.linspace(coordinate_begin, coordinate_end, size)
    tmp = Expand_dim_down(tmp, 3)

    # why i can't just use in_channel as tensor and size as np.int?
    # that is stupid error!
    # and the error information is very confusing!
    # i just do nothing for a day
    # 2018.4.8
    x = tf.tile(tmp, [size, 1, in_channel, out_channel])
    x = tf.reshape(x, [size, size, in_channel, out_channel])
    y = tf.tile(tmp, [1, size, in_channel, out_channel])

    Theta = tf.reshape(tf.tile(tf.expand_dims(Theta, 0), [4, 1]), [-1])
    Lambda = tf.reshape(tf.tile(tf.expand_dims(Lambda, 1), [1, 4]), [-1])

    Theta = tf.tile(Expand_dim_up(Theta, 3), [size, size, in_channel, 1])
    Lambda = tf.tile(Expand_dim_up(Lambda, 3), [size, size, in_channel, 1])

    Sigma = tf.multiply(0.56, Lambda)

    x_ = tf.add(tf.multiply(x, tf.cos(Theta)), tf.multiply(y, tf.sin(Theta)))
    y_ = tf.add(-tf.multiply(x, tf.sin(Theta)), tf.multiply(y, tf.cos(Theta)))
    pi = tf.asin(1.0) * 2

    res = tf.multiply(tf.exp(-tf.div(tf.add(tf.square(x_), tf.square(y_)), tf.multiply(2.0, tf.square(Sigma)))),
                      tf.cos(2.0 * pi * x_ / Lambda))
    # print tf.shape(res).eval()
    return res
示例#11
0
def RandomLambertianSource(
    center,
    normal,
    count,
    allowedWavelengths,
    sourceWidth=0.0,
    rayLength=1.0,
    cutoff=PI / 2.0,
):
    # Generates random rays that follow a lambertian distribution.
    # center: A 2-tuple, the midpoint of the line from which all rays will originate.
    # normal: The direction where the distribution maximum will point.
    # count: The number of rays to return.
    # allowedWavelengths: Either a float or a list of floats, the valid wavelengths to use.  An element from this
    #   list will be selected randomly for each ray.
    # sourceWidth: Rays can originate along a line of this length, which is centered on center and perpendicular to
    #   normal.
    # rayLength: The generated rays will have this length.
    # cutoff: No rays that have an angle greater than this value relative to the norm will be returned.

    # Pick wavelengths for each ray
    try:
        wavelengthIndices = tf.random.uniform((count, ),
                                              minval=0,
                                              maxval=len(allowedWavelengths),
                                              dtype=tf.int64)
        wavelengths = tf.gather(allowedWavelengths, wavelengthIndices)
    except (TypeError):
        wavelengths = tf.ones(count) * allowedWavelengths

    # Cast some of the parameters to float64
    wavelengths = tf.cast(wavelengths, tf.float64)
    normal = tf.cast(normal, tf.float64)

    # Generate the starting points of each ray
    startParameter = tf.random_uniform((count, ),
                                       minval=-1.0,
                                       maxval=1.0,
                                       dtype=tf.float64)
    startX = center[0] + startParameter * sourceWidth / 2.0 * tf.sin(normal)
    startY = center[1] - startParameter * sourceWidth / 2.0 * tf.cos(normal)

    # Generate the angle of each ray
    cutoff = math.sin(cutoff)
    angle = tf.random.uniform((count, ),
                              minval=-cutoff,
                              maxval=cutoff,
                              dtype=tf.float64)
    angle = tf.asin(angle) + normal

    return tf.stack(
        [
            startX,
            startY,
            startX + rayLength * tf.cos(angle),
            startY + rayLength * tf.sin(angle),
            wavelengths,
        ],
        axis=1,
    )
示例#12
0
 def K(self, cov, var1, var2=None):
     if var2 is None:
         t1 = t2 = 1 + 2 * var1
     else:
         t1, t2 = 1 + 2 * var1, 1 + 2 * var2
     vs = tf.reshape(t1[:, None, ...] * t2, tf.shape(cov))
     sin_theta = 2 * cov / tf.sqrt(vs)
     return (2 / np.pi) * tf.asin(sin_theta)
def inverse_euler(angles):
    """Returns the euler angles that are the inverse of the input.

  Args:
    angles: a tf.Tensor of shape [..., 3]

  Returns:
    A tensor of the same shape, representing the inverse rotation.
  """
    sin_angles = tf.sin(angles)
    cos_angles = tf.cos(angles)
    sz, sy, sx = tf.unstack(-sin_angles, axis=-1)
    cz, _, cx = tf.unstack(cos_angles, axis=-1)
    y = tf.asin((cx * sy * cz) + (sx * sz))
    x = -tf.asin((sx * sy * cz) - (cx * sz)) / tf.cos(y)
    z = -tf.asin((cx * sy * sz) - (sx * cz)) / tf.cos(y)
    return tf.stack([x, y, z], axis=-1)
 def moderate_corr(h=h, k=k, hk=hk, bvn=bvn):
     hs = 0.5 * (h * h + k * k)
     asr = 0.5 * tf.asin(r)
     sn = tf.sin(asr * x)
     bvn = tf.reduce_sum(w * tf.exp((sn * hk - hs) / (1.0 - sn**2)),
                         axis=-1)
     bvn = bvn * asr / tp + phid(-h) * phid(-k)
     return bvn
        def tf_map(stacked_points, stacked_normals, labels, obj_inds,
                   stack_lengths):
            """
            From the input point cloud, this function compute all the point clouds at each layer, the neighbors
            indices, the pooling indices and other useful variables.
            :param stacked_points: Tensor with size [None, 3] where None is the total number of points
            :param labels: Tensor with size [None] where None is the number of batch
            :param stack_lengths: Tensor with size [None] where None is the number of batch
            """

            # Get batch indice for each point
            batch_inds = self.tf_get_batch_inds(stack_lengths)

            # Augment input points
            if augment:
                stacked_points, scales, rots = self.tf_augment_input(
                    stacked_points, batch_inds)
            else:
                num_batches = batch_inds[-1] + 1
                scales = tf.ones(shape=(num_batches, 3))
                rots = tf.eye(3, batch_shape=(num_batches, ))

            # First add a column of 1 as feature for the network to be able to learn 3D shapes
            stacked_features = tf.ones((tf.shape(stacked_points)[0], 1),
                                       dtype=tf.float32)

            # Then use positions or not
            if self.in_features_dim == 1:
                pass
            elif self.in_features_dim == 3:
                stacked_features = tf.concat(
                    (stacked_features, stacked_points), axis=1)
            elif self.in_features_dim == 4:
                stacked_features = tf.concat(
                    (stacked_features, stacked_normals), axis=1)
            elif self.in_features_dim == 5:
                angles = tf.asin(tf.abs(stacked_normals)) * (2 / np.pi)
                stacked_features = tf.concat((stacked_features, angles),
                                             axis=1)
            elif self.in_features_dim == 7:
                stacked_features = tf.concat(
                    (stacked_features, stacked_points, stacked_normals),
                    axis=1)
            else:
                raise ValueError(
                    'Only accepted input dimensions are 1, 4 and 7 (without and with XYZ)'
                )

            # Get the whole input list
            input_list = self.tf_classification_inputs(
                self.downsample_times, self.first_subsampling_dl,
                self.density_parameter, stacked_points, stacked_features,
                labels, stack_lengths, batch_inds)

            # Add scale and rotation for testing
            input_list += [scales, rots, obj_inds]

            return input_list
示例#16
0
文件: euler.py 项目: zhou745/graphics
 def general_case(r00, r10, r21, r22, r20, eps_addition):
     """Handles the general case."""
     theta_y = -tf.asin(r20)
     sign_cos_theta_y = safe_ops.nonzero_sign(tf.cos(theta_y))
     r00 = safe_ops.nonzero_sign(r00) * eps_addition + r00
     r22 = safe_ops.nonzero_sign(r22) * eps_addition + r22
     theta_z = tf.atan2(r10 * sign_cos_theta_y, r00 * sign_cos_theta_y)
     theta_x = tf.atan2(r21 * sign_cos_theta_y, r22 * sign_cos_theta_y)
     return tf.stack((theta_x, theta_y, theta_z), axis=-1)
示例#17
0
def create_ec(point_cloud, mask):
    '''


    :param point_cloud: B N C
    :return:
    B N C/4*8 (x y z r1 r2 mol arcsin(z/mol) arctan(y/x))

    '''
    batch_size = point_cloud.get_shape()[0].value
    point_num = point_cloud.get_shape()[1].value
    neighbor_num = mask.get_shape()[2].value
    point_dimension = point_cloud.get_shape()[2].value / neighbor_num  # 4 or 3
    point_cloud = tf.reshape(
        point_cloud, [batch_size, point_num, neighbor_num, point_dimension])
    # compute xyzr
    ec_xyzr = point_cloud

    # get r1,r2
    ec_r2 = point_cloud[:, :, :, 3]

    center_r1 = point_cloud[:, :, 0, 3]  # B N
    center_r1_expand = tf.expand_dims(center_r1, axis=2)  # B N 1
    ec_r1 = center_r1_expand

    center_ma_0 = tf.expand_dims(point_cloud[:, :, 0, :], axis=2)  # B N 1 4or3
    center_ma = center_ma_0

    for i in range(neighbor_num - 1):
        ec_r1 = tf.concat([ec_r1, center_r1_expand],
                          axis=2)  # B N neighbor_num
        center_ma = tf.concat([center_ma, center_ma_0],
                              axis=2)  # B N neighbor_num 4

    ec_r12 = tf.concat(
        [tf.expand_dims(ec_r1, axis=3),
         tf.expand_dims(ec_r2, axis=3)], axis=3)  # B N Neighbor_num 2

    ec_xyzr_sub = center_ma - point_cloud  # B N neighbor_num 4
    ec_xyz = ec_xyzr_sub[:, :, :, 0:3]  # B N neighbor_num 3

    ec_mol = tf.sqrt(
        tf.pow(ec_xyz[:, :, :, 0], 2) + tf.pow(ec_xyz[:, :, :, 1], 2) +
        tf.pow(ec_xyz[:, :, :, 2], 2))  # B N Neighbor_num
    ec_mol = tf.expand_dims(ec_mol, axis=-1)  # B N Neighbor_num 1

    ec_asin = tf.asin(ec_xyz[:, :, :, 2] / (ec_mol[:, :, :, 0]))
    ec_asin = tf.expand_dims(ec_asin, axis=3)
    ec_atan = tf.atan(ec_xyz[:, :, :, 1] / (ec_xyz[:, :, :, 0] + 0.000000001))
    ec_atan = tf.expand_dims(ec_atan, axis=3)
    ec = tf.concat([ec_xyzr_sub, ec_r12], axis=3)
    ec = tf.concat([ec, ec_mol], axis=3)
    ec = tf.concat([ec, ec_asin], axis=3)
    ec = tf.concat([ec, ec_atan], axis=3)
    a = 1
    return ec
示例#18
0
  def euler(self, angles, order="yzx"):
    q = self.normalized(angles)
    q0 = q[..., 0]
    q1 = q[..., 1]
    q2 = q[..., 2]
    q3 = q[..., 3]

    if order == "xyz":
      ex = atan2(2 * (q0 * q1 + q2 * q3), 1 - 2 * (q1 * q1 + q2 * q2))
      ey = asin(tf.clip_by_value(2 * (q0 * q2 - q3 * q1), -1, 1))
      ez = atan2(2 * (q0 * q3 + q1 * q2), 1 - 2 * (q2 * q2 + q3 * q3))
      return tf.stack(values=[ex, ez], axis=-1)[:,:,1:]
    elif order == "yzx":
      ex = atan2(2 * (q1 * q0 - q2 * q3), -q1 * q1 + q2 * q2-q3 * q3 + q0 * q0)
      ey = atan2(2 * (q2 * q0 - q1 * q3), q1 * q1 - q2 * q2 - q3 * q3 + q0 * q0)
      ez = asin(tf.clip_by_value(2 * (q1 * q2 + q3 * q0), -1, 1))
      return ey[:,:,1:]
    else:
      raise Exception("Unknown Euler order!")
示例#19
0
    def __call__(self, x):

        x = tf.cast(x, tf.float32)
        batch_size = tf.shape(x)[0]
        ref_conf = tf.gather(x, self.ref_index, axis=1)
        mob_conf = tf.gather(x, self.mob_index, axis=1)
        ref_T = calcTransformMatrix_tf(self.ini_ref_conf, ref_conf,
                                       self.ref_weights)  # shape (B, 4, 4)

        ini_mob_conf = tf.gather(tf.reshape(
            applyTransformMatrix_tf(ref_T, self.ini_conf), [batch_size, -1]),
                                 self.mob_index,
                                 axis=1)
        com1 = calcCOM_tf(ini_mob_conf, self.mob_weights)  # shape (B, 1, 3)
        com2 = calcCOM_tf(mob_conf, self.mob_weights)  # shape (B, 1, 3)
        pl = (com2 - com1) / tf.linalg.norm(com2 - com1, axis=2,
                                            keepdims=True)  # shape (B, 1, 3)

        mob_T = calcTransformMatrix_tf(ini_mob_conf, mob_conf,
                                       self.mob_weights)  # shape (B, 4, 4)
        t21 = tf.reshape(tf.tile(tf.eye(3), [batch_size, 1]),
                         [batch_size, 3, 3])
        t21 = tf.concat([t21, tf.reshape(com1 - com2, [batch_size, 3, 1])],
                        axis=2)
        t21 = tf.concat([
            t21,
            tf.tile(tf.constant([[[0., 0., 0., 1.]]]), [batch_size, 1, 1])
        ],
                        axis=1)
        rot2 = tf.matmul(mob_T, t21)

        p1 = applyTransformMatrix_tf(rot2, com1)  # shape (B, 1, 3)
        p2 = applyTransformMatrix_tf(rot2, p1)  # shape (B, 1, 3)
        rideal = tf.cross((com1 - p2), (com1 - p1))
        rideal = rideal / tf.linalg.norm(rideal, axis=2,
                                         keepdims=True)  # shape (B, 1, 3)
        new = com2 - tf.matmul(rideal, tf.transpose(
            com2 - com1, [0, 2, 1])) * rideal  # shape (B, 1, 3)

        cosine = tf.matmul(
            (new - com1) / tf.linalg.norm(new - com1, axis=2, keepdims=True),
            tf.transpose(
                (new - p1) / tf.linalg.norm(new - p1, axis=2, keepdims=True),
                [0, 2, 1]))
        angl = tf.acos(cosine)

        perp = tf.matmul(rideal, tf.transpose(pl,
                                              [0, 2, 1]))  # shape (B, 1, 1)
        angp = tf.abs(tf.asin(perp))  # shape (B, 1, 1)
        pro = rideal - perp * pl  # shape (B, 1, 3)

        tang = tf.cos(angp) * tf.tan(0.5 * angl)  # shape (B, 1, 1)
        angle = tf.reshape(2.0 * tf.atan(tang),
                           [-1]) * 180.0 / np.pi  # 度数に変換している
        return angle
示例#20
0
 def haversine_dist(self, X, X2):
     pi = np.pi / 180
     f = tf.expand_dims(X * pi, -2)  # ... x N x 1 x D
     f2 = tf.expand_dims(X2 * pi, -3)  # ... x 1 x M x D
     d = tf.sin((f - f2) / 2)**2
     lat1, lat2 = tf.expand_dims(X[:, 0] * pi, -1), \
                 tf.expand_dims(X2[:, 0] * pi, -2)
     cos_prod = tf.cos(lat2) * tf.cos(lat1)
     a = d[:, :, 0] + cos_prod * d[:, :, 1]
     c = tf.asin(tf.sqrt(a)) * 6371 * 2
     return c
示例#21
0
def _loss_tensor(y_true, y_pred):
    split0, split1 = tf.split(y_pred, num_or_size_splits=2, axis=-1)
    split3, split4 = tf.split(y_true, num_or_size_splits=2, axis=-1)
    out = 2 * 6371. * tf.asin(
        tf.sqrt(
            K.sin((split1 - split4) /
                  (180 * math.pi))**2 + K.cos(split1 / (180 * math.pi)) *
            K.cos(split4 / (180 * math.pi)) * K.sin((split3 - split0) * 0.5 /
                                                    (180 * math.pi))**2))
    out2 = -1e4 * bimix_gauss.prob(y_pred)
    return K.mean(out, axis=-1) + K.mean(out2, axis=-1)
示例#22
0
def heavy_g(rho, mu1, mu2):
    sqrt_one_minus_rho_sqr = tf.sqrt(1.0 - rho * rho)
    a = tf.asin(rho)
    safe_a = tf.abs(a) + HALF_EPSILON
    safe_rho = tf.abs(rho) + EPSILON

    A = a / twopi
    sxx = safe_a * sqrt_one_minus_rho_sqr / safe_rho
    sxy = safe_a * sqrt_one_minus_rho_sqr * (1 + sqrt_one_minus_rho_sqr) / (
        rho * rho)
    return A * tf.exp(-(mu1 * mu1 + mu2 * mu2) / (2.0 * sxx) + mu1 * mu2 / sxy)
示例#23
0
def pan_error(y_true, y_pred):
    y_true = y_true[:, :4]
    delta_quaternion = quat.compute_delta_quaternion(y_true, y_pred)
    q0, q1, q2, q3 = tf.split(delta_quaternion, [1, 1, 1, 1], axis=1)
    t0 = 2. * (q0 * q2 + q3 * q1)
    t0 = tf.clip_by_value(t0,
                          clip_value_min=-0.999999999,
                          clip_value_max=0.999999999)
    pan_deg = tf.asin(t0) * (180. / math.pi)
    pan_deg = tf.abs(pan_deg)
    return tf.reduce_mean(pan_deg)
示例#24
0
def react(reactedRays, norm, n_in, n_out):
    with tf.name_scope("ray_reactions") as scope:

        with tf.name_scope("rayStart") as scope:
            xstart = reactedRays[:, 2]
            ystart = reactedRays[:, 3]

        with tf.name_scope("theta1") as scope:
            theta1 = tf.atan2(
                reactedRays[:, 1] - reactedRays[:, 3],
                reactedRays[:, 0] - reactedRays[:, 2],
                name="theta1",
            )
            theta1 = norm - theta1

            # basically just theta1 % 2PI, make sure that we measured the correct angle between the two directions
            with tf.name_scope("mod_2PI") as scope:
                theta1 = tf.where(theta1 > PI, theta1 - (2 * PI), theta1)
                theta1 = tf.where(theta1 < -PI, theta1 + (2 * PI), theta1)

        # distinguish internal/external refractions
        internalMask = tf.greater_equal(
            tf.abs(theta1), PI / 2, name="internalRefractionsMask"
        )
        n = tf.where(internalMask, n_in / n_out, n_out / n_in, name="n")
        # these wheres selects between internal and external refraction
        norm = tf.where(internalMask, norm, norm + PI, "normInternal_ExternalSelector")
        theta1 = tf.where(
            internalMask, theta1 + PI, theta1, "theta1Internal_ExternalSelector"
        )

        theta2 = tf.multiply(tf.sin(theta1), n, name="theta2")

        # the where selects between TIR and internal refraction
        theta2 = tf.where(
            tf.less_equal(tf.abs(theta2), 1.0),
            norm - tf.asin(theta2),
            norm + theta1 + PI,
            name="TIR_selector",
        )

        with tf.name_scope("rayEnd") as scope:
            xend = xstart + tf.cos(theta2)
            yend = ystart + tf.sin(theta2)

        # xend = xstart + tf.cos(norm)
        # yend = ystart + tf.sin(norm)

        return tf.stack(
            [xstart, ystart, xend, yend, reactedRays[:, 4], reactedRays[:, 5]],
            axis=1,
            name="activeRays",
        )
 def streetview_pixel_to_world_coordinates(lat1, lng1, yaw, image_width,
                                           image_height, x, y):
     EARTH_RADIUS = tf.cast(6371000,
                            tf.float32)  # Radius in meters of Earth
     GOOGLE_CAR_CAMERA_HEIGHT = tf.cast(
         3, tf.float32
     )  # ballpark estimate of the number of meters that camera is off the ground
     MATH_PI = tf.cast(math.pi, tf.float32)
     pitch = float(0)
     look_at_angle = x * (2 * math.pi) / image_width
     height = 0
     tilt_angle = (image_height / 2 - y) * math.pi / image_height + pitch
     tilt_angle = tf.cast(tilt_angle, tf.float32)
     z_ = K.minimum(np.float32(-1e-2), tilt_angle)
     z = tf.divide((-GOOGLE_CAR_CAMERA_HEIGHT), tf.tan(z_))
     dx = tf.sin(look_at_angle - MATH_PI + yaw) * z / EARTH_RADIUS
     dy = tf.cos(look_at_angle - MATH_PI + yaw) * z / EARTH_RADIUS
     lat = lat1 + tf.asin(dy) * (180 / MATH_PI)
     lng = lng1 + tf.asin(dx / tf.cos(lat1 *
                                      (MATH_PI / 180))) * (180 / MATH_PI)
     return lat, lng
示例#26
0
    def raytrace(self):
        '''
        Given the set of lens model parameters fed to the likelihood function object, 
        calculate the raytraced pixels in the source plane.  For now, we assume 
        an SIE for the lens model.  
        '''

        q = 1 - tf.sqrt(tf.add(tf.square(self.ex), tf.square(self.ey)))
        qp = tf.sqrt(1 - tf.square(q))
        angle = atan2(self.ey, self.ex)
        shear = tf.sqrt(tf.square(self.gx) + tf.square(self.gy))
        shearang = tf.subtract(atan2(self.gy, self.gx), angle)
        g1 = tf.multiply(shear, -tf.cos(tf.scalar_mul(2, shearang)))
        g2 = tf.multiply(shear, -tf.sin(tf.scalar_mul(2, shearang)))
        g3 = tf.multiply(shear, -tf.sin(tf.scalar_mul(2, shearang)))
        g4 = tf.multiply(shear, tf.cos(tf.scalar_mul(2, shearang)))

        xgrid = tf.slice(self.grid, [0, 0], [-1, 1])
        ygrid = tf.slice(self.grid, [0, 1], [-1, 1])

        xgrid = tf.subtract(xgrid, self.xl)
        ygrid = tf.subtract(ygrid, self.yl)

        rad, th = cart2pol(ygrid, xgrid)
        xgrid, ygrid = pol2cart(rad, tf.subtract(th, angle))

        par = atan2(ygrid, xgrid)

        xsrc = tf.subtract(
            xgrid,
            tf.multiply(
                self.te,
                tf.multiply(tf.divide(tf.sqrt(q), qp),
                            asinh(tf.divide(tf.multiply(qp, tf.cos(par)),
                                            q)))))
        ysrc = tf.subtract(
            ygrid,
            tf.multiply(
                self.te,
                tf.multiply(tf.divide(tf.sqrt(q), qp),
                            tf.asin(tf.multiply(qp, tf.sin(par))))))
        xsrc = tf.subtract(
            xsrc, tf.add(tf.multiply(g1, xgrid), tf.multiply(g2, ygrid)))
        ysrc = tf.subtract(
            ysrc, tf.add(tf.multiply(g3, xgrid), tf.multiply(g4, ygrid)))

        rad, th = cart2pol(ysrc, xsrc)
        xsrc, ysrc = pol2cart(rad, tf.add(th, angle))
        xsrc = tf.add(xsrc, self.xl)
        ysrc = tf.add(ysrc, self.yl)

        return tf.transpose(xsrc), tf.transpose(ysrc)
示例#27
0
def compute_vertex_normal(vertices, indices):
    def dot(v1, v2):
        return tf.math.reduce_sum(v1 * v2, axis=1)
    def squared_length(v):
        return tf.math.reduce_sum(v * v, axis=1)
    def length(v):
        return tf.sqrt(squared_length(v))
    # Nelson Max, "Weights for Computing Vertex Normals from Facet Vectors", 1999
    normals = tf.zeros(vertices.shape, dtype = tf.float32)

    # NOTE: Try tf.TensorArray()
    v = [tf.gather(vertices, indices[:,0]),
         tf.gather(vertices, indices[:,1]),
         tf.gather(vertices, indices[:,2])]

    for i in range(3):
        v0 = v[i]
        v1 = v[(i + 1) % 3]
        v2 = v[(i + 2) % 3]
        e1 = v1 - v0
        e2 = v2 - v0
        e1_len = length(e1)
        e2_len = length(e2)
        side_a = e1 / tf.reshape(e1_len, [-1, 1])
        side_b = e2 / tf.reshape(e2_len, [-1, 1])
        if i == 0:
            n = tf.linalg.cross(side_a, side_b)
            n = n / tf.reshape(length(n), [-1, 1])
        angle = tf.where(dot(side_a, side_b) < 0, 
            math.pi - 2.0 * tf.asin(0.5 * length(side_a + side_b)),
            2.0 * tf.asin(0.5 * length(side_b - side_a)))
        sin_angle = tf.sin(angle)
        
        contrib = tf.reshape((sin_angle / (e1_len * e2_len)), (-1, 1))
        contrib = n * tf.broadcast_to(contrib, [tf.shape(contrib)[0],3]) # In torch, `expand(-1, 3)`
        normals += tf.scatter_nd(tf.reshape(indices[:, i], [-1, 1]), contrib, shape = tf.shape(normals))

    normals = normals / tf.reshape(length(normals), [-1, 1])
    return normals
示例#28
0
def cal_d_gc(lon1, lon2, lat1, lat2):
    
                  
    d_lon = tf.abs(tf.subtract(lon1, lon2))                  
    d_lat = tf.abs(tf.subtract(lat1, lat2))
                                        
    term1 = tf.pow(tf.sin(d_lat/2), 2.)
    term2 = tf.multiply(tf.multiply(tf.cos(lat1), tf.cos(lat2)), tf.pow(tf.sin(d_lon/2.),2))
    
    f = tf.sqrt(tf.add(term1,term2))
                
    dist_gc = 2 * tf.asin(f) 
                     
    return dist_gc
示例#29
0
 def haversine_dist(self, X, X2):
     pi = np.pi / 180
     f = tf.expand_dims(X * pi, -2)  # ... x N x 1 x D
     f2 = tf.expand_dims(X2 * pi, -3)  # ... x 1 x M x D
     d = tf.sin((f - f2) / 2)**2
     
     # this should be latitude, so second column if lon/lat/time
     lat1, lat2 = tf.expand_dims(X[:, 1] * pi, -1), tf.expand_dims(X2[:, 1] * pi, -2)
     cos_prod = tf.cos(lat2) * tf.cos(lat1)
     
     # here d[:,:,0] = lon, d[:,:,1] = lat
     a = d[:, :, 1] + cos_prod * d[:, :, 0]
     c = tf.asin(tf.sqrt(a)) * 6371 * 2
     return c
示例#30
0
def matrix_sin():
    isess = tf.InteractiveSession()
    W = tf.Variable(tf.random_normal(shape=(3, 3)))

    W.initializer.run()
    logger.info("W\n%s" % W.eval())

    logger.info("tf.cos(W)\n%s" % tf.cos(W).eval())
    logger.info("tf.sin(W)\n%s" % tf.sin(W).eval())
    logger.info("tf.tan(W)\n%s" % tf.tan(W).eval())
    logger.info("tf.acos(W)\n%s" % tf.acos(W).eval())
    logger.info("tf.asin(W)\n%s" % tf.asin(W).eval())
    logger.info("tf.atan(W)\n%s" % tf.atan(W).eval())
    isess.close()
def periodic_triangle_waveform(z, p):
    return 2.0 / np.pi * tf.asin(tf.sin(2*np.pi*z/p))