Exemple #1
0
def compute_edge_ratio(mesh):
    """
    :param mesh: a mesh
    :return: minimum, maximum and average edge ratio of the mesh
    """

    p = mesh.get_nodes()
    t = mesh.get_faces()

    maximum = 0
    avg = 0

    #big number !
    minimum = 1e10

    for triangle in t:
        a, b, c = triangle
        pa, pb, pc = p[a], p[b], p[c]

        ab = length(pa - pb)
        ac = length(pa - pc)
        bc = length(pb - pc)

        local_min = min(min(ab, ac), bc)
        local_max = max(max(ab, ac), bc)

        edge_ratio = local_max / local_min

        minimum = minimum if minimum <= edge_ratio else edge_ratio
        maximum = maximum if maximum >= edge_ratio else edge_ratio

        avg += edge_ratio

    return minimum, maximum, avg / len(t)
    def __init__(self, point_item):
        self.vertices = set()
        if not point_item.is_bounded():
            return

        # Compute segments edges
        for other in point_item.others:
            v1, v2 = other.vertices()
            for v in [v1, v2]:
                EPSILON = 1e-4
                distances = list(utils.distance2(v, i) for i in self.vertices)
                if len(distances) == 0 or min(distances) > EPSILON:
                    self.vertices |= {v}

        # Sort vertices to make the shape convex
        self.vertices = list(self.vertices)
        OA = utils.vector(point_item.point, self.vertices[0])
        len_OA = utils.length(OA)
        t = {(self.vertices[0], 0)}
        for vertex in self.vertices[1:]:
            OB = utils.vector(point_item.point, vertex)
            len_OB = utils.length(OB)
            cos_angle = utils.dot(OA, OB) / (len_OA * len_OB)
            if cos_angle < -1:
                cos_angle = -1
            elif cos_angle > 1:
                cos_angle = 1

            angle = math.acos(cos_angle)
            if utils.cross(OA, OB) < 0:  # sign of sin
                angle = 2 * math.pi - angle
            t |= {(vertex, angle)}
        self.vertices = list(vertex
                             for vertex, _ in sorted(t, key=lambda x: x[1]))
 def scatter(self, r_in, rec, attenuation):
     refracted = np.zeros([3], dtype=np.float32)
     reflected = reflect(r_in.direction(), rec.normal)
     attenuation = np.array([1, 1, 1], dtype=np.float32)
     if np.dot(r_in.direction(), rec.normal) > 0:
         outward_normal = -rec.normal
         ni_over_nt = self.ref_idx
         cosine = self.ref_idx * np.dot(
             r_in.direction(), rec.normal) / length(r_in.direction())
         # cosine = np.dot(r_in.direction(), rec.normal) / length(r_in.direction())
         # print(1 - self.ref_idx * self.ref_idx * (1 - cosine ** 2), self.ref_idx, cosine)
         # cosine = math.sqrt(1 - self.ref_idx * self.ref_idx * (1 - cosine ** 2))
     else:
         outward_normal = rec.normal
         ni_over_nt = 1.0 / self.ref_idx
         cosine = (0 - np.dot(r_in.direction(), rec.normal)) / length(
             r_in.direction())
     boolean, refracted = refract(r_in.direction(), outward_normal,
                                  ni_over_nt, refracted)
     if boolean:
         reflect_prob = schlick(cosine, self.ref_idx)
     else:
         reflect_prob = 1.0
     if (random() < reflect_prob):
         scattered = ray(rec.p, reflected)
     else:
         scattered = ray(rec.p, refracted)
     return True, attenuation, scattered
Exemple #4
0
    def castRay(self, origin, direction):
        material, intersect = self.sceneIntersect(origin, direction)
        
        if material is None:
            return self.currentColor

        lightDir = norm(sub(self.light.position, intersect.point))
        lightDistance = length(sub(self.light.position, intersect.point))
        
        offsetNormal = mul(intersect.normal, 1.1)
        shadowOrigin = sub(intersect.point, offsetNormal) if dot(lightDir, intersect.normal) < 0 else sum(intersect.point, offsetNormal)
        shadowMaterial, shadowIntersect = self.sceneIntersect(shadowOrigin, lightDir)
        shadowIntensity = 0

        if shadowMaterial and length(sub(shadowIntersect.point, shadowOrigin)) < lightDistance:
            shadowIntensity = 0.9

        intensity = self.light.intensity * max(0, dot(lightDir, intersect.normal)) * (1 - shadowIntensity)

        reflection = reflect(lightDir, intersect.normal)
        specularIntensity = self.light.intensity * (
            max(0, -dot(reflection, direction)) ** material.spec
        )

        diffuse = material.diffuse * intensity * material.albedo[0]
        specular = Color(255, 255, 255) * specularIntensity * material.albedo[1]
        return diffuse + specular
Exemple #5
0
    def castRay(self, origin, direction, recursion=0):
        material, intersect = self.sceneIntersect(origin, direction)

        if material is None or recursion >= MAX_RECURSION_DEPTH:
            return self.currentColor
            # Si el rayo no golpeo nada o si llego al limite de recursion

        lightDir = norm(sub(self.light.position, intersect.point))
        lightDistance = length(sub(self.light.position, intersect.point))

        offsetNormal = mul(intersect.normal, 1.1)
        shadowOrigin = sub(
            intersect.point,
            offsetNormal) if dot(lightDir, intersect.normal) < 0 else sum(
                intersect.point, offsetNormal)
        shadowMaterial, shadowIntersect = self.sceneIntersect(
            shadowOrigin, lightDir)
        shadowIntensity = 0

        if shadowMaterial and length(sub(shadowIntersect.point,
                                         shadowOrigin)) < lightDistance:
            shadowIntensity = 0.9

        intensity = self.light.intensity * max(
            0, dot(lightDir, intersect.normal)) * (1 - shadowIntensity)

        reflection = reflect(lightDir, intersect.normal)
        specularIntensity = self.light.intensity * (max(
            0, -dot(reflection, direction))**material.spec)

        if material.albedo[2] > 0:
            reflectDir = reflect(direction, intersect.normal)
            reflectOrigin = sub(intersect.point, offsetNormal) if dot(
                reflectDir, intersect.normal) < 0 else sum(
                    intersect.point, offsetNormal)
            reflectedColor = self.castRay(reflectOrigin, reflectDir,
                                          recursion + 1)
        else:
            reflectedColor = self.currentColor

        if material.albedo[3] > 0:
            refractDir = refract(direction, intersect.normal,
                                 material.refractionIndex)
            refractOrigin = sub(intersect.point, offsetNormal) if dot(
                refractDir, intersect.normal) < 0 else sum(
                    intersect.point, offsetNormal)
            refractedColor = self.castRay(refractOrigin, refractDir,
                                          recursion + 1)
        else:
            refractedColor = self.currentColor

        diffuse = material.diffuse * intensity * material.albedo[0]
        specular = Color(255, 255,
                         255) * specularIntensity * material.albedo[1]
        reflected = reflectedColor * material.albedo[2]
        refracted = refractedColor * material.albedo[3]

        return diffuse + specular + reflected + refracted
Exemple #6
0
 def calcEndDist(self):
     # Return the new tour distance if 2opt swap is performed at start, end.
     # In the new tour, the previous point will connect to the end and the start will
     # connect to the next point.
     endDist = self.parent.getEndDist()
     oldStartEdgeLen = utils.length(self.points[self.tour[self.parent.mapIndex(self.start - 1)]], self.points[self.tour[self.parent.mapIndex(self.start)]])
     oldEndEdgeLen = utils.length(self.points[self.tour[self.parent.mapIndex(self.end)]], self.points[self.tour[self.parent.mapIndex((self.end + 1) % len(self.tour))]])
     newStartEdgeLen = utils.length(self.points[self.tour[self.parent.mapIndex(self.start - 1)]], self.points[self.tour[self.parent.mapIndex(self.end)]])
     newEndEdgeLen = utils.length(self.points[self.tour[self.parent.mapIndex(self.start)]], self.points[self.tour[self.parent.mapIndex((self.end + 1) % len(self.tour))]])
     return endDist + (newStartEdgeLen - oldStartEdgeLen) + (newEndEdgeLen - oldEndEdgeLen)
Exemple #7
0
def generate_connective_cylinders(points, radius, ndiv):
    """ Generate mesh of cylinders of given radius along the segments
    connecting given sequence of points. Each cylinder is generated by
    dividing cylinder side into ndiv rectangular strips.
    """
    # Use template to reduce overhead of mesh generation.
    template_mesh = make_cylinder_mesh(ndiv)
    template_mesh.vertices[:, 0] *= radius
    template_mesh.vertices[:, 1] *= radius

    meshes = []
    for point_1, point_2 in zip(points[:-1], points[1:]):
        # Compute orthonormal frame whose z-axis is given by the tangent
        # vector of the segment connecting two points. Then we will map the
        # template cylinder mesh along the z-axis.
        segment = point_2 - point_1
        tangent = normalize(segment)
        try:
            normal = find_any_normal(tangent)
        except:
            normal = [1, 0, 0]
        binormal = np.cross(tangent, normal)
        frame = np.row_stack((normal, binormal, tangent))

        # Map template mesh on the segment.
        stretch = length(segment)
        mesh = template_mesh.copy()
        mesh.vertices[:, 2] *= stretch
        mesh.vertices = np.dot(mesh.vertices, frame) + point_1
        mesh.normals = np.dot(mesh.normals, frame)
        meshes.append(mesh)

    return meshes
Exemple #8
0
def p_nickname(w, y, x, nickname, selected):
    nick = nickname.encode('utf-8')
    nicklen = utils.length(nick)
    try:
        w.addstr(y, x+(10-nicklen), nick, curses.A_UNDERLINE|curses.color_pair(1)|selected)
    except:
        pass
Exemple #9
0
def compute_gravity_resistance(contacts,
                               normals,
                               num_facets,
                               mu,
                               gamma,
                               object_mass,
                               c_of_mass_height=0):
    """ Gravity produces some wrench on your object.  Computes whether the grasp can produce and equal and opposite wrench

    Parameters
    ----------
    contacts : :obj:`numpy.ndarray`
        obj mesh vertices on which the fingers will be placed
    normals : :obj:`numpy.ndarray`
        obj mesh normals at the contact points
    num_facets : int
        number of vectors to use to approximate the friction cone.  these vectors will be along the friction cone boundary
    mu : float 
        coefficient of friction
    gamma : float
        torsional friction coefficient
    object_mass : float
        mass of the object

    Returns
    -------
    float : quality of the grasp
    """
    # YOUR CODE HERE (contact forces exist may be useful here)
    # grasp_map = get_grasp_map(contacts, normals, num_facets, mu, gamma)

    #Linear Force due to gravity
    f = np.array([0, 0, -object_mass * 9.8])

    #Torque due to gravity
    l = normalize(contacts[1] - contacts[0])
    up = np.cross(contacts[0] - np.array([0, 0, c_of_mass_height]), l)
    r_length = length(up)
    r = normalize(np.cross(l, up)) * r_length
    torque = np.cross(r, f)

    #Total Wrench due to gravity
    Fe = np.append(f, torque).T

    #Get the least square soln
    fc, residual = contact_forces_exist(contacts, normals, num_facets, mu,
                                        gamma, -Fe)

    #Check contacts if torque inside friction cone
    if fc is not None:
        f0 = 0
        f1 = 0
        for i in range(32):
            f0 = f0 + fc[i]
            f1 = f1 + fc[33 + i]

        if fc[32] > gamma * f0 or fc[65] > gamma * f1:
            return float('inf')

    return residual
Exemple #10
0
def random_scene(n=500):
    list = []
    list.append(
        sphere(vec3(0, -1000, 0), 1000, lambertian(vec3(0.5, 0.5, 0.5))))
    for a in range(-11, 11):
        for b in range(-11, 11):
            choose_mat = random()
            center = vec3(a + 0.9 * random(), 0.2, b + 0.9 * random())
            if length(center - vec3(4, 0.2, 0)) > 0.9:
                if choose_mat < 0.8:
                    list.append(
                        sphere(
                            center, 0.2,
                            lambertian(
                                vec3(random() * random(),
                                     random() * random(),
                                     random() * random()))))
                elif choose_mat < 0.95:
                    list.append(
                        sphere(
                            center, 0.2,
                            metal(
                                vec3(0.5 * (1 + random()),
                                     0.5 * (1 + random()),
                                     0.5 * (1 + random())), 0.5 * random())))
                else:
                    list.append(sphere(center, 0.2, dielectric(1.5)))
    list.append(sphere(vec3(0, 1, 0), 1.0, dielectric(1.5)))
    list.append(sphere(vec3(-4, 1, 0), 1.0, lambertian(vec3(0.4, 0.2, 0.1))))
    list.append(sphere(vec3(4, 1, 0), 1.0, metal(vec3(0.7, 0.6, 0.5), 0.0)))
    return list
Exemple #11
0
def compute_aspect_ratio(mesh):
    """
    :param mesh: a mesh
    :return: minimum, maximum and average aspect ratio of the mesh
    """

    p = mesh.get_nodes()
    t = mesh.get_faces()

    maximum = 0
    avg = 0

    #big number !
    minimum = 1e10

    for triangle in t:
        a, b, c = triangle
        pa, pb, pc = p[a], p[b], p[c]

        ab = length(pa - pb)
        ac = length(pa - pc)
        bc = length(pb - pc)

        half_circumference = (ab + ac + bc) / 2.
        area = math.sqrt(half_circumference * (half_circumference - ab) *
                         (half_circumference - ac) * (half_circumference - bc))

        if area == 0:
            print pa, pb, pc, triangle

        inradius = area / half_circumference

        local_max = max(max(ab, ac), bc)

        if inradius == 0:
            inradius = 1e-12

        aspect_ratio = local_max / (2 * math.sqrt(3) * inradius)

        minimum = minimum if minimum <= aspect_ratio else aspect_ratio
        maximum = maximum if maximum >= aspect_ratio else aspect_ratio

        avg += aspect_ratio

    return minimum, maximum, avg / len(t)
Exemple #12
0
def compute_aspect_ratio(mesh):
    """
    :param mesh: a mesh
    :return: minimum, maximum and average aspect ratio of the mesh
    """

    p = mesh.get_nodes()
    t = mesh.get_faces()

    maximum = 0
    avg = 0

    #big number !
    minimum = 1e10

    for triangle in t:
        a, b, c = triangle
        pa, pb, pc = p[a], p[b], p[c]

        ab = length(pa-pb)
        ac = length(pa-pc)
        bc = length(pb-pc)


        half_circumference = (ab+ac+bc)/2.
        area = math.sqrt(half_circumference*(half_circumference-ab)*(half_circumference-ac)*(half_circumference-bc))

        if area == 0:
            print pa, pb, pc, triangle

        inradius = area/half_circumference

        local_max = max(max(ab,ac), bc)

        if inradius == 0:
            inradius = 1e-12

        aspect_ratio = local_max/(2*math.sqrt(3)*inradius)

        minimum = minimum if minimum <= aspect_ratio else aspect_ratio
        maximum = maximum if maximum >= aspect_ratio else aspect_ratio

        avg += aspect_ratio

    return minimum, maximum, avg/len(t)
 def updateKnownRobots(self):
     '''update robots in the communicate limits after changing its position'''
     knownRobots=[]
     robotList=self._world.getRobotList()
     for robot in robotList:
         x,y = robot.xy()
         if self.getId()!=robot.getId() and utils.length(self._x,self._y,x,y) <= self._rc:
             knownRobots.append(robot)
     self._knownRobots=knownRobots
Exemple #14
0
def calculate_array2D_cost(points, ants, cities):
    cost = np.empty((ants, cities))
    for row in range(ants):
        for column in range(cities):
            if row != column:
                cost[row][column] = length(points[row], points[column])
            else:
                cost[row][column] = -1
    return cost
Exemple #15
0
def compute_skewness(mesh):
    """
    :param mesh: a mesh
    :return: minimum, maximum and average skewness of the mesh
    """

    p = mesh.get_nodes()
    t = mesh.get_faces()

    maximum = 0
    avg = 0

    minimum = 1e10


    for i, triangle in enumerate(t):
        a, b, c = triangle
        pa, pb, pc = p[a], p[b], p[c]

        ab = length(pa-pb)
        ac = length(pa-pc)
        bc = length(pb-pc)

        half_circumference = (ab+ac+bc)/2.
        area = math.sqrt(half_circumference*(half_circumference-ab)*(half_circumference-ac)*(half_circumference-bc))

        if area==0:
            area= 1e-12

        circumscribed_circle_r = ab*ac*bc/(4.*area)


        a = math.sqrt(3)*circumscribed_circle_r
        optimal_area = math.sqrt(3)/4. * a*a

        skewness = (optimal_area-area)/optimal_area


        minimum = minimum if minimum <= skewness else skewness
        maximum = maximum if maximum >= skewness else skewness

        avg += skewness

    return minimum, maximum, avg/len(t)
Exemple #16
0
def sorted_contacts(vertices, normals, T_ar_object):
    """ takes mesh and returns pairs of contacts and the quality of grasp between the contacts, sorted by quality
    
    Parameters
    ----------
    vertices : :obj:`numpy.ndarray`
        nx3 mesh vertices
    normals : :obj:`numpy.ndarray`
        nx3 mesh normals
    T_ar_object : :obj:`autolab_core.RigidTransform`
        transform from the AR tag on the paper to the object

    Returns
    -------
    :obj:`list` of :obj:`numpy.ndarray`
        grasp_indices[i][0] and grasp_indices[i][1] are the indices of a pair of vertices.  These are randomly 
        sampled and their quality is saved in best_metric_indices
    :obj:`list` of int
        best_metric_indices is the indices of grasp_indices in order of grasp quality
    """
    N = 1000
    # prune vertices that are too close to the table so you dont smack into the table
    # you may want to change this line, to be how you see fit
    possible_indices = np.r_[:len(vertices)][vertices[:, 2] +
                                             T_ar_object[2, 3] >= 0.03]
    np.random.shuffle(possible_indices)

    # Finding grasp via vertex sampling.  make sure to not consider grasps where the
    # vertices are too big for the gripper

    # possible metrics: compute_force_closure, compute_gravity_resistance, compute_custom_metric
    metric = compute_custom_metric
    grasp_indices = list()
    metric_scores = list()
    for i in range(N):
        candidate_indices = np.random.choice(possible_indices,
                                             2,
                                             replace=False)
        point_dist = utils.length(vertices[candidate_indices[0]] -
                                  vertices[candidate_indices[1]])
        grasp_indices.append(candidate_indices)
        # assign lowest possible scores to impossible grasps
        if point_dist < MIN_HAND_DISTANCE or point_dist > MAX_HAND_DISTANCE:
            metric_scores.append(-sys.maxint - 1)
        else:
            contacts = vertices[candidate_indices]
            contact_normals = normals[candidate_indices]
            score = metric(contacts, contact_normals, CONTACT_MU,
                           CONTACT_GAMMA, OBJECT_MASS)
            metric_scores.append(score)

    # sort metrics and return the sorted order
    best_metric_indices = sorted(list(range(N)),
                                 key=lambda i: metric_scores[i],
                                 reverse=True)
    return grasp_indices, best_metric_indices
Exemple #17
0
def draw_login_window(parent):
    global login_window
    global logo_window

    if login_window:
        login_window.erase()
        login_window.refresh()
        del login_window
    if logo_window:
        logo_window.erase()
        logo_window.refresh()
        del logo_window

    parent.erase()
    me2terminal.paint_background(parent)
    parent.refresh()

    LINES = parent.getmaxyx()[0]
    COLS = parent.getmaxyx()[1]

    # logo window
    logo_y = (LINES-LOGO_H) / 2 - 4
    logo_window = curses.newwin(LOGO_H, LOGO_W, logo_y, (COLS-LOGO_W)/2)
    line = 1
    for logo_line in LOGO:
        logo_window.addstr(line, 1, logo_line)
        line += 1
    logo_window.refresh()

    # login window
    login_width, login_height = (42, 7)
    login_window = curses.newwin(
        login_height, login_width, 
        logo_y + LOGO_H + 1,
        (COLS-login_width)/2)
    login_window.border()
    login_window.addstr(1, 1, 
        expand_to(title, login_width-2), 
        curses.A_REVERSE | curses.A_BOLD)
    login_window.addstr(3, 4, label_id)
    login_window.addstr(' ' * (login_width-2-length(label_id)-8), curses.A_UNDERLINE)
    login_window.addstr(5, login_width-2-length("[Enter]"), "[Enter]")
    login_window.refresh()
Exemple #18
0
def compute_skewness(mesh):
    """
    :param mesh: a mesh
    :return: minimum, maximum and average skewness of the mesh
    """

    p = mesh.get_nodes()
    t = mesh.get_faces()

    maximum = 0
    avg = 0

    minimum = 1e10

    for i, triangle in enumerate(t):
        a, b, c = triangle
        pa, pb, pc = p[a], p[b], p[c]

        ab = length(pa - pb)
        ac = length(pa - pc)
        bc = length(pb - pc)

        half_circumference = (ab + ac + bc) / 2.
        area = math.sqrt(half_circumference * (half_circumference - ab) *
                         (half_circumference - ac) * (half_circumference - bc))

        if area == 0:
            area = 1e-12

        circumscribed_circle_r = ab * ac * bc / (4. * area)

        a = math.sqrt(3) * circumscribed_circle_r
        optimal_area = math.sqrt(3) / 4. * a * a

        skewness = (optimal_area - area) / optimal_area

        minimum = minimum if minimum <= skewness else skewness
        maximum = maximum if maximum >= skewness else skewness

        avg += skewness

    return minimum, maximum, avg / len(t)
Exemple #19
0
def findNearestPoint(points, used, src):
    # If no nearest point, return max.
    dest = src
    minDist = sys.float_info.max
    i = (src + 1) % len(points)
    for j in range(len(points) - 1):
        if not used[i]:
            dist = utils.length(points[src], points[i]) 
            if dist < minDist:
                dest = i
                minDist = dist 
        i = (i + 1) % len(points)
    return dest, minDist
Exemple #20
0
def solve(points):
    tour = [0 for i in range(len(points))]
    used = [False for i in range(len(points))]
    totalDist = 0.0
    used[0] = True
    src = 0
    for i in range(1, len(points)):
        dest, minDist = findNearestPoint(points, used, src)
        tour[i] = dest
        used[dest] = True
        src = dest
        totalDist += minDist
    return 0, totalDist + utils.length(points[tour[-1]], points[tour[0]]), tour
Exemple #21
0
def find_any_normal(vec):
    """ Return a unit vector perpendicular to the given nonzero vector.
    """
    x, y, z = vec
    candidates = [(y + z, -x, -x), (-y, z + x, -y), (-z, -z, x + y),
                  (y - z, -x, x), (y, z - x, -y), (-z, z, x - y)]

    for n in candidates:
        norm = length(n)
        if norm > 0:
            return as_float_array(n) / norm

    raise Exception('cannot find a normal')
Exemple #22
0
    def init_context_embedding(self, embedded_terms):
        assert (isinstance(self.cfg, RCNNConfig))
        text_length = utils.length(self.x)

        with tf.name_scope("bi-rnn"):
            fw_cell = RNN.get_cell(
                self.cfg.SurroundingOneSideContextEmbeddingSize,
                self.cfg.CellType)
            fw_cell = tf.nn.rnn_cell.DropoutWrapper(
                fw_cell, output_keep_prob=self.dropout_keep_prob)
            bw_cell = RNN.get_cell(
                self.cfg.SurroundingOneSideContextEmbeddingSize,
                self.cfg.CellType)
            bw_cell = tf.nn.rnn_cell.DropoutWrapper(
                bw_cell, output_keep_prob=self.dropout_keep_prob)
            (self.output_fw,
             self.output_bw), states = tf.nn.bidirectional_dynamic_rnn(
                 cell_fw=fw_cell,
                 cell_bw=bw_cell,
                 inputs=embedded_terms,
                 sequence_length=text_length,
                 dtype=tf.float32)

        with tf.name_scope("context"):
            shape = [
                tf.shape(self.output_fw)[0], 1,
                tf.shape(self.output_fw)[2]
            ]
            c_left = tf.concat([tf.zeros(shape), self.output_fw[:, :-1]],
                               axis=1,
                               name="context_left")
            c_right = tf.concat(
                [self.output_bw[:, 1:], tf.zeros(shape)],
                axis=1,
                name="context_right")

        with tf.name_scope("word-representation"):
            merged = tf.concat([c_left, embedded_terms, c_right],
                               axis=2,
                               name="merged")

        with tf.name_scope("text-representation"):
            y2 = tf.tanh(tf.einsum('aij,jk->aik', merged, self.W1) + self.b1)

        with tf.name_scope("max-pooling"):
            y3 = tf.reduce_max(y2, axis=1)

        if self.cfg.UseAttention:
            y3 = tf.concat([y3, self.init_attention_embedding()], axis=-1)

        return y3
Exemple #23
0
def compute_edge_ratio(mesh):
    """
    :param mesh: a mesh
    :return: minimum, maximum and average edge ratio of the mesh
    """

    p = mesh.get_nodes()
    t = mesh.get_faces()

    maximum = 0
    avg = 0

    #big number !
    minimum = 1e10

    for triangle in t:
        a, b, c = triangle
        pa, pb, pc = p[a], p[b], p[c]

        ab = length(pa-pb)
        ac = length(pa-pc)
        bc = length(pb-pc)


        local_min = min(min(ab,ac), bc)
        local_max = max(max(ab,ac), bc)


        edge_ratio = local_max/local_min

        minimum = minimum if minimum <= edge_ratio else edge_ratio
        maximum = maximum if maximum >= edge_ratio else edge_ratio

        avg += edge_ratio

    return minimum, maximum, avg/len(t)
Exemple #24
0
    def init_context_embedding(self, embedded_terms):
        assert (isinstance(self.cfg, RNNConfig))

        with tf.name_scope("rnn"):
            length = tf.cast(utils.length(self.x), tf.int32)
            cell = self.get_cell(self.cfg.HiddenSize, self.cfg.CellType)
            cell = tf.nn.rnn_cell.DropoutWrapper(
                cell, output_keep_prob=self.dropout_keep_prob)
            all_outputs, _ = tf.nn.dynamic_rnn(cell=cell,
                                               inputs=embedded_terms,
                                               sequence_length=length,
                                               dtype=tf.float32)
            h_outputs = self.last_relevant(all_outputs, length)

        return h_outputs
Exemple #25
0
 def ray_intersect(self, orig, direction):
     L = sub(self.center, orig)
     tca = dot(L, direction)
     l = length(L)
     d2 = l**2 - tca**2
     if d2 > self.radius**2:
         return False
     thc = (self.radius**2 - d2)**1 / 2
     t0 = tca - thc
     t1 = tca + thc
     if t0 < 0:
         t0 = t1
     if t0 < 0:
         return False
     return True
Exemple #26
0
 def stat(self, path, name, timestamp):
     if name.endswith('.md') and (not name.__contains__('README')):
         file = open(path, 'r', encoding='utf-8')
         type = 'unfinished'
         num = 0
         info = ''
         for i in file.readlines():
             num += length(i.strip())
             if i.__contains__('END'):
                 type = 'fin'
         file.close()
         info = '|[' + name[0:-3] + '](' + name + ')|'
         info += str(num) + '|'
         if self.sort == 'time':
             info += changeTime(timestamp) + '|'
         self.write(info, type)
Exemple #27
0
    def __init__(self, vertices, faces, normals=None, colors=None):
        # Infer the direction of vertex normal as that of vector pointing
        # the vertex from the centroid of the vertices. This should give
        # fairly good normals for convex objects.
        if normals is None:
            center = np.mean(vertices, axis=0)
            normals = np.array(vertices) - center
            normals /= length(normals)[:, None]
        # Default color is white.
        if colors is None:
            colors = np.ones((len(vertices), 3))

        self.vertices = vertices
        self.faces = faces
        self.normals = normals
        self.colors = colors
Exemple #28
0
 def stat(self, path, name):
     if name.endswith('.md') and (not name.__contains__('README')):
         file = open(path, 'r', encoding='utf-8')
         num = 0
         for i in file.readlines():
             num += length(i.strip())
         file.close()
         before = 0
         if name in self.history.keys():
             before = self.history[name]
         if before != num:
             self.log.append('|' + name.replace('.md', '') + '|' +
                             str(before) + '|' + str(num) + '|' +
                             str(num - before) + '|')
         self.history[name] = num
         self.exist[name] = True
Exemple #29
0
    def rayIntersect(self, origin, direction):
        L = sub(self.center, origin)
        tca = dot(L, direction)
        l = length(L)
        # distancia al cuadrado
        dc = l**2 - tca**2

        if dc > self.radius**2:
            return False

        thc = (self.radius**2 - dc)**0.5
        t0 = tca - thc
        t1 = tca + thc

        if t0 < 0:
            t0 = t1
        if t0 < 0:
            return False
        return True
Exemple #30
0
def get_userid(parent):
    global logo_window
    global login_window

    draw_login_window(parent)

    user_id = _input(parent, login_window, 3, 4+length(label_id))
    # It's show time! Let's move both windows to the right corner.
    if len(user_id) > 2:
        ly, lx = logo_window.getbegyx()
        y, x = login_window.getbegyx()
        for i in range(1, 1): 
            newy = y+i*1
            newly = ly-i*1
            try:
                if newly <= 1: newly = 1
                logo_window.mvwin(newly, lx)
                if newy >= parent.getmaxyx()[0]-8: newy = parent.getmaxyx()[0]-8
                login_window.mvwin(newy, x)
            except:
                break

            me2terminal.paint_background(parent)
            parent.refresh()
            login_window.refresh()
            logo_window.refresh()

            time.sleep(0.09)
    else: 
        return ''

    logo_window.erase()
    login_window.erase()
    logo_window.refresh()
    login_window.refresh()

    me2terminal.paint_background(parent)
    parent.refresh()

    del logo_window
    del login_window

    return user_id
Exemple #31
0
def create_scene(args):
    modellers = load_chain_modellers(args.scheme)
    center = (0, 0, 0)
    scene_radius = 0.0
    shaders = []

    records = parse_input(args.coords)

    def extract_group_tag(record):
        return record[0]

    for tag, subrecords in itertools.groupby(records, key=extract_group_tag):
        # Interpret a part of the tag as the name of the modelling scheme to
        # use for this subrecords.
        modeller_name = tag.split(':')[0]
        if modeller_name not in modellers:
            raise Exception('unknown modelling scheme: ' + modeller_name)
        modeller = modellers[modeller_name]

        points = []
        values = []
        for _, x, y, z, value in subrecords:
            points.append((x, y, z))
            values.append(value)
        points = as_float_array(points)
        shaders.append(modeller.make_shader(points, values))
        scene_radius = max(scene_radius, length(points - center).max())

    # Add wireframe spherical wall.
    if args.wall_radius > 0:
        color, opacity = args.wall_color.split(',', 1)
        color = vispy.color.Color(color).rgb
        opacity = float(opacity)

        wall = make_sphere_mesh(ndiv=WALL_SPHERE_NDIV)
        wall.vertices *= args.wall_radius
        wall.colors[:] = color
        shaders.append(WireframeShader(wall, opacity))

        scene_radius = max(scene_radius, args.wall_radius)

    return TranslucentScene(shaders, args.bgcolor), scene_radius
    def _check_overlap(self, word, orientation, x, y):
        i, j = x, y
        next_pos = calculate_next_pos[orientation](i, j,
                                                   length(word, self.lang))
        for a in get_letters(word, self.lang):
            try:
                (i, j) = next(next_pos)
                print("i={} j={}".format(i, j))
            except StopIteration as e:
                print("stop iteration received after will fit word={} i, j={}".
                      format(word, (i, j)))

            if self.puzzle_matrix[i][j] != " ":
                if self.puzzle_matrix[i][j] == a:
                    continue
                else:
                    print("Overlap of letter {} with {} at {}".format(
                        a, self.puzzle_matrix[i][j], (i, j)))
                    return True
        return False
Exemple #33
0
 def rayIntersect(self, origin, direction):
   L = sub(self.center, origin)
   tca = dot(L, direction)
   l = length(L)
   d2 = l ** 2 - tca ** 2
   if d2 > self.radius ** 2:
       return None
   thc = (self.radius ** 2 - d2) ** 0.5
   t0 = tca - thc
   t1 = tca + thc
   if t0 < 0:
       t0 = t1
   if t0 < 0:
       return None
   hit = sum(origin, mul(direction, t0))
   normal = norm(sub(hit, self.center))
   return Intersect(
       distance=t0,
       point=hit,
       normal=normal
   )
def Greedy(customers, facilities):
    solution = [-1]*len(customers)
    capacity_remaining = [f.capacity for f in facilities]

    facility_index = 0
    for customer in customers:
        if capacity_remaining[facility_index] >= customer.demand:
            solution[customer.index] = facility_index
            capacity_remaining[facility_index] -= customer.demand
        else:
            facility_index += 1
            assert capacity_remaining[facility_index] >= customer.demand
            solution[customer.index] = facility_index
            capacity_remaining[facility_index] -= customer.demand

    used = [0]*len(facilities)
    for facility_index in solution:
        used[facility_index] = 1

    # calculate the cost of the solution
    obj = sum([f.setup_cost*used[f.index] for f in facilities])
    for customer in customers:
        obj += length(customer.location, facilities[solution[customer.index]].location)
    return obj, solution
Exemple #35
0
def main():
    # print get_divisors(28)
    # print zip(iter_triangle_numbers(), range(7))[-1]
    first = (x for x in iter_triangle_numbers() if length(get_divisors(x)) > 500).next()
    print get_divisors(first)
    print first
def primitive(name, value, vs, arity, k):
    if arity == length(vs):
        return k.resume(value(vs))
    else:
        raise TypeError("incorrect arity {} {}".format(name, vs))
 def invoke(self, vs, r, k):
     if length(vs) == 1:
         return self.resume(vs.car)
     else:
         raise TypeError(
             "Continuations expect one argument {} {} {}".format(vs, r, k))
defprimitive('null?', lambda args: is_null(args.car), 1)
defprimitive('cons', lambda args: cons(args.car, args.cadr), 2)
defprimitive('car', lambda args: args.caar, 1)
defprimitive('cdr', lambda args: args.cdar, 1)
defprimitive('+', lambda args: args.car + args.cadr, 2)
defprimitive('-', lambda args: args.car - args.cadr, 2)
defprimitive('*', lambda args: args.car * args.cadr, 2)
defprimitive('/', lambda args: args.car / args.cadr, 2)
definitial('println', Primitive('println', lambda args, r, k: k.resume(
    print() if is_null(args) else print(str(args)[1:-1]))))

definitial(
    'call/cc',
    Primitive(
        'call/cc',
        lambda vs, r, k: vs.car.invoke(cons(k, Nil), r, k) if length(
            vs) == 1 else wrong(
            TypeError("incorrect arity {} {}".format('call/cc', vs)))))


def wrong(e):
    raise e


class BottomCont(Continuation):
    def __init__(self, f):
        super().__init__(None)
        self.f = f

    def resume(self, v):
        return self.f(v)
Exemple #39
0
 def focal_distance(self):
     return utils.length(utils.sub(self.look_at, self.look_from))
Exemple #40
0
from utils import vecadd, length
from math import sin, cos, degrees, radians, acos

a = [2, 3]
b = [4 * cos(radians(65)), 4 * sin(radians(65))]
c = [-4, -6]
d = [5 * cos(radians(-235)), 5 * sin(radians(-235))]

apbpcpd = vecadd(vecadd(a, b), vecadd(c, d))
apbpcpd_mag = length(apbpcpd)
costheta = apbpcpd[0] / apbpcpd_mag
theta = acos(costheta)

if __name__ == "__main__":
    print("a ", apbpcpd)
    print("b ", apbpcpd_mag)
    print("c ", degrees(theta))
Exemple #41
0
def show_posts(state):
    offset = state.offset
    cur_post = state.cur_post
    cur_idx = state.cur_idx
    posts = state.posts
    post_window = state.post_window
    loc_map = state.loc_map

    post_window.erase()
    limit_y = post_window.getmaxyx()[0] - 1
    printed_line = 0
    y = 0
    selected = 0 # curses attributes for highlighted item.

    for post in posts:
        if y > limit_y: 
            break
        # 아이디 출력        
        x = 2 
        nick = post.author.nickname.encode('utf-8')
        nicklen = utils.length(nick)

        if cur_post==post.id and cur_idx==0: selected = curses.A_REVERSE
        else: selected = 0
        p_nickname(post_window, y, x, post.author.nickname, selected)

        # 내용
        x += 10 + 2
        content_w = post_window.getmaxyx()[1]-x-10
        body = post.body
        post_window.move(y, x)
        content_lines = p_wrap(post_window, y, x, body, limit_y, x+content_w)

        # 날짜 (UTC 문제 해결할 것)
        if y+1 > limit_y: 
            break
        post_window.move(y+1, x-10-1)
        post_window.addstr("%2d일%02d:%02d" % (post.date.day, post.date.hour, post.date.minute), curses.A_NORMAL | curses.color_pair(3)) 
        
        # 태그 
        if len(post.tags)>0:
            if y+content_lines > limit_y:
                break
            post_window.move(y+content_lines, x)
            tags = "# %s" % (' '.join(post.tags))
            for tag_ch in tags:
                post_window.addstr(tag_ch.encode('utf-8'), curses.A_DIM | curses.color_pair(5))
                if post_window.getyx()[1]+2 >= x+content_w:
                    break # 긴 태그는 가볍게 무시
            content_lines += 1

        # 미투수 출력, 미투하기 링크 출력
        x += content_w
        post_window.move(y, x)

        loc_map[post.id] = (post_window.getbegyx()[0]+y, x)

        if cur_post==post.id and cur_idx==1: selected = curses.A_REVERSE
        else: selected = 0
        post_window.addstr("metoo",     
            curses.A_NORMAL | curses.color_pair(2) | selected)
        if cur_post==post.id and cur_idx==2: selected = curses.A_REVERSE
        else: selected = 0
        post_window.addstr(" ")
        post_window.addstr("%2d" % (post.metoo_count), 
            curses.A_NORMAL | curses.color_pair(6) | selected)
        if y+1 > limit_y:
            break
        post_window.move(y+1, x+1)
        post_window.addstr( "댓글 ", curses.A_NORMAL)
        if cur_post==post.id and cur_idx==3: selected = curses.A_REVERSE
        else: selected = 0
        post_window.addstr("%2d" % (post.comment_count), 
            curses.A_UNDERLINE | curses.color_pair(6) | selected)

        # metoo, comment 출력을 위해 최소 라인을 2줄로 맞춤.
        if content_lines==1:    
            content_lines = 2
        y += content_lines 
        printed_line += 1

    post_window.refresh()
    state.printed_line = printed_line
 def distance(self, element1, element2 ):
     from utils import length
     return length( self.displacement( element1, element2 ))