Exemplo n.º 1
0
    def generate(self, cm_pos=np.array([0, 0, 0])):
        seqs = [[base.base_to_number[x] for x in s] for s in TetramerGenerator.seqs]

        strands = [base.Strand() for i in range(4)]

        half_strand_len = base.BASE_BASE * 21.;
        sqrt1_3 = 1 / np.sqrt(3.)
        sqrt1_2 = 1 / np.sqrt(2.)
        cube_side = half_strand_len  * sqrt1_3;
        rb = cm_pos + np.array([cube_side, -cube_side, -cube_side])
        # this initial direction will give us a 0, -1, +1 direction in the center
        a1 = np.array([-0.438110, -0.815750, 0.377640])
        a1 /= np.sqrt(np.dot(a1, a1))
        a3 = np.array([-sqrt1_3, sqrt1_3, sqrt1_3])

        a3s = [[-sqrt1_3, sqrt1_3, -sqrt1_3],
               [sqrt1_3, sqrt1_3, sqrt1_3],
               [-sqrt1_3, -sqrt1_3, sqrt1_3],
               [sqrt1_3, -sqrt1_3, -sqrt1_3]]

        a1s = [[0, sqrt1_2, sqrt1_2],
               [0, -sqrt1_2, sqrt1_2],
               [0, -sqrt1_2, -sqrt1_2],
               [0, sqrt1_2, -sqrt1_2]]

        R = utils.get_rotation_matrix(a3, np.pi/180*(35.9))

        for s in range(4):
            for i in range(49):
                strands[s].add_nucleotide(base.Nucleotide(rb - base.CM_CENTER_DS*a1, a1, a3, seqs[s][i]))
                if i == 21:
                    a1old = a1
                    a1 = np.array(a1s[s])
                    rback = rb - (base.CM_CENTER_DS - base.POS_BACK) * a1old
                    rback -= (a1 + a1old) * base.BASE_BASE
                    a3 = np.array(a3s[s])
                    rb = rback + (base.CM_CENTER_DS - base.POS_BACK) * a1
                    R = utils.get_rotation_matrix(a3, np.pi/180*(35.9))
                else:
                    a1 = np.dot(R, a1)
                    rb += a3 * base.BASE_BASE

                # the next strand will begin from this base
                if i == 40:
                    na1 = -a1
                    na3 = -a3
                    nrb = np.copy(rb)

            a1 = na1
            a3 = na3
            R = utils.get_rotation_matrix(a3, np.pi/180*(35.9))
            rb = nrb

        return strands
def align(full_base, ox_base):
    theta = utils.get_angle(full_base.a3, ox_base._a3)
    axis = np.cross(full_base.a3, ox_base._a3)
    axis /= sqrt(np.dot(axis, axis))

    R = utils.get_rotation_matrix(axis, theta)
    full_base.rotate(R)

    theta = utils.get_angle(full_base.a1, ox_base._a1)
    axis = np.cross(full_base.a1, ox_base._a1)
    axis /= sqrt(np.dot(axis, axis))
    R = utils.get_rotation_matrix(axis, theta)
    full_base.rotate(R)
    old_a1 = np.array(full_base.a1)
Exemplo n.º 3
0
def go_to_closest_neighbor(agent_state, internal_agent_state, observation):
    """
    Given state of an agent and his observation return the action which directs him to his
    closest neighbor which has the same state.
    :param agent_state:
    :param internal_agent_state Internal state of the agent: Healthy or Contaminated.
    :param observation: List of all the agents that the given agent can see.
    :return:
    """

    # If there are no observations return a random action.
    if len(observation) == 0:
        return np.random.randn(1, 2)

    min_dist = float('inf')
    closest_agent = None
    for idx, agent_obs in enumerate(observation):
        if agent_obs.dist < min_dist and agent_obs.state.value == internal_agent_state:
            min_dist = agent_obs.dist
            closest_agent = idx
    # If there is no close agent of our type wander.
    if closest_agent is None:
        return np.array([1, 1])

    orientation_diff = observation[
        closest_agent].bearing + 2 * np.pi - agent_state[2]
    rotation_matrix = U.get_rotation_matrix(orientation_diff)
    return np.dot(rotation_matrix, np.array([1, 0]))
def align_faces(faces, image, predictor, required_size=(160, 160)):
    # Récupération de la taille de l'image
    (s_height, s_width) = image.shape[:2]

    aligned_faces = []

    # Boucler sur les visages détecté
    for i, det in enumerate(faces):

        # Récupérer les traits du visage
        shape = predictor(image, det)

        # Récupérer les coordonnées des yeux grâce au traits du visages
        left_eye = extract_left_eye_center(shape)
        right_eye = extract_right_eye_center(shape)

        # Récupérer la matice de rotation du visage grace à la position des yeux
        M = get_rotation_matrix(left_eye, right_eye)

        # Appliquer une rotation à l'image afin d'avoir le ième visage aligné
        rotated = cv2.warpAffine(
            image, M, (s_width, s_height), flags=cv2.INTER_CUBIC)

        # Rogner l'image afin de garder uniquement le ième visage
        cropped = crop_image(rotated, det)

        cropped = cv2.resize(cropped, required_size)

        # Ajouter le visage rogné à la liste
        aligned_faces.append(cropped)

    return asarray(aligned_faces)
        def crop_from_detected(det):
            shape = self.predictor(img, det)
            left_eye = extract_left_eye_center(shape)
            right_eye = extract_right_eye_center(shape)

            M = get_rotation_matrix(left_eye, right_eye)
            rotated = cv2.warpAffine(img,
                                     M, (s_width, s_height),
                                     flags=cv2.INTER_CUBIC)

            cropped = crop_image(rotated, det)
            return cropped
Exemplo n.º 6
0
    def rotate(self, theta=30, axis=0):
        rx, ry, rz = get_rotation_matrix(theta)
        if axis == 0:
            rm = rx
        elif axis == 1:
            rm = ry
        elif axis == 2:
            rm = rz
        else:
            raise ValueError("Invalid axis")

        for i, (x, y, z) in enumerate(self._pc):
            self._pc[i] = np.matmul(rm, np.array([x, y, z]).T)
Exemplo n.º 7
0
def detectar(img): 
    detecs = detector(img, 1) # Vetor de detecção de rostos
    rostos = []
    s_height, s_width = img.shape[:2]

    for i, det in enumerate(detecs):
        shape = predictor(img, det)
        left_eye = extract_left_eye_center(shape)
        right_eye = extract_right_eye_center(shape)
        M = get_rotation_matrix(left_eye, right_eye)
        rotated = cv2.warpAffine(img, M, (s_height, s_width), flags=cv2.INTER_CUBIC)
        cropped = crop_image(rotated, det)
        squared = resizeAndPad(cropped, (img_h,img_w), 127)
        rostos.append(squared)

    return detecs, rostos        
Exemplo n.º 8
0
    def numpy(self):
        radius = self.radius
        sphere = np.zeros((2 * 180 * radius * 360, 3))
        circle = np.zeros((2 * 180 * radius, 3))
        circle[:, 0] = self.x + np.sin(
            np.radians([x for x in range(0, 2 * 180 * radius)]))
        circle[:, 1] = self.y + np.cos(
            np.radians([x for x in range(0, 2 * 180 * radius)]))
        circle[:, 2] = self.z

        for z_theta in range(360):
            rx, _, _ = get_rotation_matrix(z_theta)
            for i, (x, y, z) in enumerate(circle):
                sphere[i + z_theta * 360] = np.matmul(rx,
                                                      np.array([x, y, z]).T)

        return sphere
Exemplo n.º 9
0
    def tick(self, angle=0):
        if angle < -self.max_turn:
            angle = -self.max_turn
        if angle > self.max_turn:
            angle = self.max_turn
        rotation_matrix = utils.get_rotation_matrix(angle)
        self.direction = rotation_matrix @ self.direction

        # Normalize to fix exploding direction vector over time
        self.direction = self.step * (self.direction /
                                      np.linalg.norm(self.direction))

        pos = self.head_position + self.direction
        self.body.appendleft(pos)
        if self.to_grow:
            self.to_grow -= 1
        else:
            self.body.pop()
Exemplo n.º 10
0
def prepare(raw_coll, dest_dir):
    for filename in raw_coll: 
        img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
        s_height, s_width = img.shape[:2]
        dets = detector(img, 1)
        print('Processing ' + filename)
        for i, det in enumerate(dets):
            if i > 0: 
                print("Mais de um rosto detectado!!!!!")
                break
            shape = predictor(img, det)
            left_eye = extract_left_eye_center(shape)
            right_eye = extract_right_eye_center(shape)
            M = get_rotation_matrix(left_eye, right_eye)
            rotated = cv2.warpAffine(img, M, (s_height, s_width), flags=cv2.INTER_CUBIC)
            cropped = crop_image(rotated, det)
            squared = resizeAndPad(cropped, (img_h,img_w), 127)
            output_image_path = dest_dir + os.path.basename(filename)
            cv2.imwrite(output_image_path, squared)        
Exemplo n.º 11
0
    def init(self):
        transform = utils.get_rotation_matrix(self.orientation_)

        right = np.array([1.0, 0.0, 0.0])
        right = utils.transform_dir(right, transform)

        up = np.array([0.0, 0.0, 1.0])
        up = utils.transform_dir(up, transform)

        forward = np.cross(up, right)
        forward = forward / np.linalg.norm(forward)

        self.up_ = up
        self.right_ = right
        self.forward_ = forward

        ratio = self.fov_[1] / self.fov_[0]
        self.width_ = 2 * self.near_clip_ * math.tan(math.radians(
            self.fov_[0]))
        self.height_ = ratio * self.width_
Exemplo n.º 12
0
    def process_image(self, input_image, output_image, scale=2):

        img = cv2.imread(input_image)

        # cv2.imshow('image', img)
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()

        height, width = img.shape[:2]
        s_height, s_width = height // scale, width // scale
        img = cv2.resize(img, (s_width, s_height))

        dets = self.detector(img, 1)

        for i, det in enumerate(dets):
            shape = self.predictor(img, det)
            left_eye = extract_left_eye_center(shape)
            right_eye = extract_right_eye_center(shape)

            M = get_rotation_matrix(left_eye, right_eye)
            rotated = cv2.warpAffine(img,
                                     M, (s_width, s_height),
                                     flags=cv2.INTER_CUBIC)

            cropped = crop_image(rotated, det)

            # cv2.imshow('image', cropped)
            # cv2.waitKey(0)
            # cv2.destroyAllWindows()

            # if output_image.endswith('.jpg'):
            #     output_image_path = output_image.replace('.jpg', '_%i.jpg' % i)
            # elif output_image.endswith('.png'):
            #     output_image_path = output_image.replace('.png', '_%i.jpg' % i)
            # else:
            #     output_image_path = output_image + ('_%i.jpg' % i)
            #
            output_image_path = os.path.join(
                output_image,
                input_image.split("/")[-1] + ('_%i.jpg' % i))
            cv2.imwrite(output_image_path, cropped)
Exemplo n.º 13
0
    def __init__(self, cfg):
        orientation = np.array(
            [cfg['lcs']['h'], cfg['lcs']['p'], cfg['lcs']['r']])
        pos = np.array([cfg['lcs']['x'], cfg['lcs']['y'], cfg['lcs']['z']])
        scale = np.array(
            [cfg['lcs']['sx'], cfg['lcs']['sy'], cfg['lcs']['sz']])
        rotation = utils.get_rotation_matrix(orientation)
        translation = utils.get_translation_matrix(pos)
        scale = utils.get_scale_matrix(scale)
        o2w, w2o = utils.get_o2w_w2o_matrices(translation, rotation, scale)
        self.o2w_ = np.copy(o2w)
        self.w2o_ = np.copy(w2o)
        # self.o2w_tr_ = np.copy(np.linalg.inv(self.o2w_.transpose()))
        self.o2w_tr_ = self.o2w_.transpose()

        self.color_ = np.array([
            cfg['material']['color']['r'], cfg['material']['color']['g'],
            cfg['material']['color']['b']
        ])
        self.material_type_ = refl_refr.MaterialTypes.DIFFUSE
        if ('type' in cfg['material']) is True:
            if cfg['material']['type'] == 'REFLECTION':
                self.material_type_ = refl_refr.MaterialTypes.REFLECTION
            elif cfg['material']['type'] == 'REFLECTION_AND_REFRACTION':
                self.material_type_ = refl_refr.MaterialTypes.REFLECTION_AND_REFRACTION
        self.refr_index_ = 1.0
        if ('refr_index' in cfg['material']) is True:
            self.refr_index_ = cfg['material']['refr_index']
        self.refl_coef_ = 0.5
        if ('refl_coef' in cfg['material']) is True:
            self.refl_coef_ = cfg['material']['refl_coef']
        self.K_d_ = 0.3
        if ('K_d' in cfg['material']) is True:
            self.K_d_ = cfg['material']['K_d']
        self.K_s_ = 0.5
        if ('K_s' in cfg['material']) is True:
            self.K_s_ = cfg['material']['K_s']
Exemplo n.º 14
0
def alignFace(image):
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

    height, width = image.shape[:2]
    s_height, s_width = height, width
    image = cv2.resize(image, (s_width, s_height))

    dets = detector(image, 1)

    if len(dets) == 1:
        shape = predictor(image, dets[0])
        left_eye = extract_left_eye_center(shape)
        right_eye = extract_right_eye_center(shape)

        M = get_rotation_matrix(left_eye, right_eye)
        rotated = cv2.warpAffine(image,
                                 M, (s_width, s_height),
                                 flags=cv2.INTER_CUBIC)

        return rotated
    else:
        print("Not a single face")
        return None
Exemplo n.º 15
0
    def generate_or_sq(self, bp, sequence=None, start_pos=np.array([0,0,0]), dir=np.array([0, 0, 1]), perp=None, double=True, rot=0., angle=np.pi/180*33.75, length_change=0, region_begin=0, region_end=0):
        # we need numpy array for these
        start_pos = np.array(start_pos, dtype=float)
        dir = np.array(dir, dtype=float)
        if sequence == None:
            sequence = np.random.randint(0, 4, bp)
        elif len(sequence) != bp:
            n = bp - len(sequence)
            sequence += np.random.randint(0, 4, n)
            base.Logger.log("sequence is too short, adding %d random bases" % n, base.Logger.WARNING)
        # angle should be an array, with a length 1 less than the # of base pairs
        if not isinstance(angle, np.ndarray):
            angle = np.ones(bp) * angle
        elif len(angle) != bp - 1:
            base.Logger.log("generate_or_sq: incorrect angle array length, should be 1 less than number of base pairs", base.Logger.CRITICAL)
        # create the sequence of the second strand as made of complementary bases
        sequence2 = [3-s for s in sequence]
        sequence2.reverse()

        # we need to find a vector orthogonal to dir
        dir_norm = np.sqrt(np.dot(dir,dir))
        if dir_norm < 1e-10:
            base.Logger.log("direction must be a valid vector, defaulting to (0, 0, 1)", base.Logger.WARNING)
            dir = np.array([0, 0, 1])
        else: dir /= dir_norm

        if perp is None:
            v1 = np.random.random_sample(3)
            v1 -= dir * (np.dot(dir, v1))
            v1 /= np.sqrt(sum(v1*v1))
        else:
            v1 = perp;

        # and we need to generate a rotational matrix
        R0 = utils.get_rotation_matrix(dir, rot)
#        R = utils.get_rotation_matrix(dir, angle)
        #R = get_rotation_matrix(dir, [1, BP])

        ns1 = base.Strand()
        a1 = v1
        a1 = np.dot (R0, a1)
        rb = np.array(start_pos)
        a3 = dir
        for i in range(bp):
            ns1.add_nucleotide(base.Nucleotide(rb - base.CM_CENTER_DS * a1, a1, a3, sequence[i]))
            if i != bp-1:
                R = utils.get_rotation_matrix(dir, angle[i])
                a1 = np.dot(R, a1)
                rb += a3 * base.BASE_BASE
                if length_change:
                    for j in range(len(length_change)):
                        if i >= region_begin[j] and i < region_end[j]:
                            if length_change[j]:
                                rb += a3 * base.BASE_BASE * (- (float(length_change[j])/(region_end[j] - region_begin[j])))

        if double == True:

            angle = np.flipud(angle)
            a1 = -a1
            a3 = -dir
            ns2 = base.Strand()

            for i in range(bp):

                ns2.add_nucleotide(base.Nucleotide(rb - base.CM_CENTER_DS * a1, a1, a3, sequence2[i]))
                if i != bp - 1:
                    R = utils.get_rotation_matrix(dir,angle[i]).transpose()
                    a1 = np.dot(R, a1)
                    rb += a3 * base.BASE_BASE
                    if length_change:
                        for j in range(len(length_change)):
                            if bp - 2 - i >= region_begin[j] and bp - 2 - i < region_end[j]:
                                if length_change[j]:
                                    rb += a3 * base.BASE_BASE * (- (float(length_change[j])/(region_end[j] - region_begin[j])))

            return ns1, ns2
        else: return ns1
Exemplo n.º 16
0
def align_face(name):
    input_image, output_image = source + name, destination + name

    #reading image. If 0 bytes we delete it
    output = input_image + ''
    img = cv2.imread(input_image)
    if img is None:
        if (os.path.isfile(input_image)):
            os.remove(input_image)
        return 'fail'

    #scaling images
    height, width = img.shape[:2]
    if (width == 0 or height == 0):
        no_removes += 1
        os.remove(input_image)
        return 'fail'
    s_height, s_width = height // scale, width // scale
    img = cv2.resize(img, (s_width, s_height))
    output += ' | ' + str(s_width) + ' | ' + str(s_height)

    #detects faces. If no faces -> remove
    dets = detector(img, 1)
    output += ' | ' + str(len(dets)) + '\n'
    if (len(dets) == 0):
        os.remove(input_image)
        return 'fail'

    #looping through each face, rotating it, cropping, saving, then reading in again and outputting the landmark points
    for i, det in enumerate(dets):
        shape = predictor(img, det)
        #rotate eyes to horizontal
        left_eye = extract_left_eye_center(shape)
        right_eye = extract_right_eye_center(shape)
        output += 'eyes: ' + str(left_eye) + ' ' + str(right_eye) + ' | '
        M = get_rotation_matrix(left_eye, right_eye)
        rotated = cv2.warpAffine(img,
                                 M, (s_width, s_height),
                                 flags=cv2.INTER_CUBIC)

        cropped = crop_image(rotated, det)
        if (cropped.shape[1] == 0):
            continue
        #saving
        if output_image.endswith('.jpg'):
            output_image_path = output_image.replace('.jpg', '_%i.jpg' % i)
        elif output_image.endswith('.png'):
            output_image_path = output_image.replace('.png', '_%i.jpg' % i)
        else:
            output_image_path = output_image + ('_%i.jpg' % i)
        output += ' | ' + output_image_path + ' | ' + str(cropped.shape)
        cv2.imwrite(output_image_path, cropped)

        #landmark detection
        try:
            LM_img = io.imread(output_image_path)
        except:
            os.remove(output_image_path)
            return
        dets = detector(LM_img, 1)
        output += ("Number of faces detected: {}".format(len(dets)))
        if (len(dets) == 0):
            os.remove(output_image_path)

        for k, d in enumerate(dets):
            output += (
                " | Detection {}: Left: {} Top: {} Ri: {} Bot: {}".format(
                    k, d.left(), d.top(), d.right(), d.bottom()))
            shape = predictor(LM_img, d)
            with open(output_image_path + '.txt', 'w') as lm:
                for i in range(shape.num_parts):
                    lm.write(
                        str(shape.part(i).x) + ' ' + str(shape.part(i).y) +
                        '\n')

    #print(output + '\n===============')
    return 'success'
Exemplo n.º 17
0
    def a_generate(self,
                   bp,
                   sequence=None,
                   start_pos=np.array([0, 0, 0]),
                   dir=np.array([0, 0, 1]),
                   perp=False,
                   double=True,
                   rot=None,
                   base_base_distance=None,
                   inclination=None,
                   diameter=2.35):
        if inclination == None:
            inclination = 15.5

        bp_backback_distance = 2.0
        cord = math.cos(np.deg2rad(inclination)) * bp_backback_distance
        center_to_cord = math.sqrt((diameter / 2.)**2 - (cord / 2.)**2)

        if (base_base_distance == None):
            base_base_distance = 0.3287  #a-rna, source: neidle book
        if (rot == None):
            rot = 32.7  #a-dna, source: wiki

        # we need numpy array for these
        start_pos = np.array(start_pos, dtype=float)
        dir = np.array(dir, dtype=float)
        if sequence == None:
            sequence = np.random.randint(0, 4, bp)
        elif len(sequence) != bp:
            n = bp - len(sequence)
            sequence += np.random.randint(0, 4, n)
            base.Logger.log(
                "sequence is too short, adding %d random bases" % n,
                Logger.WARNING)

        # create the sequence of the second strand as made of complementary bases
        sequence2 = [3 - s for s in sequence]
        sequence2.reverse()

        # we need to find a vector orthogonal to dir
        dir_norm = np.sqrt(np.dot(dir, dir))
        if dir_norm < 1e-10:
            base.Logger.log(
                "direction must be a valid vector, defaulting to (0, 0, 1)",
                base.Logger.WARNING)
            dir = np.array([0, 0, 1])
        else:
            dir /= dir_norm

        #x1, y1, z1 = center_to_cord,  cord / 2., -(bp_backback_distance / 2.) * np.sin (np.deg2rad(inclination))
        #x2, y2, z2 = center_to_cord, -cord / 2., +(bp_backback_distance / 2.) * np.sin (np.deg2rad(inclination))

        x2, y2, z2 = center_to_cord, -cord / 2., +(
            bp_backback_distance / 2.) * np.sin(np.deg2rad(inclination))
        x1, y1, z1 = center_to_cord, +cord / 2., -(
            bp_backback_distance / 2.) * np.sin(np.deg2rad(inclination))

        r1 = np.array([x1, y1, z1])
        r2 = np.array([x2, y2, z2])
        r1_to_r2 = r2 - r1

        ZAXIS = np.array([0., 0., 1.])

        RISE = base_base_distance

        R = utils.get_rotation_matrix(ZAXIS, np.deg2rad(rot))

        ns1 = base.Strand()

        for i in xrange(len(sequence)):
            r1 = np.dot(R, r1) + RISE * ZAXIS
            r2 = np.dot(R, r2) + RISE * ZAXIS
            r1_to_r2 = r2 - r1
            a1 = r1_to_r2 / math.sqrt(np.dot(r1_to_r2, r1_to_r2))
            a1proj = np.array([a1[0], a1[1], 0.])
            a1projnorm = math.sqrt(np.dot(a1proj, a1proj))
            a3 = -(-math.cos(np.deg2rad(inclination)) * ZAXIS +
                   math.sin(np.deg2rad(inclination)) * a1proj / a1projnorm)
            #a3 = math.cos(np.deg2rad(inclination)) * ZAXIS - math.sin(np.deg2rad(inclination))* a1proj / a1projnorm
            ns1.add_nucleotide(
                base.Nucleotide(r1 + base.CM_CENTER_DS * a1, a1, a3,
                                sequence[i]))

        if double == True:
            a1 = -a1
            a3 = -dir
            R = R.transpose()
            ns2 = base.Strand()
            for i in xrange(len(sequence)):
                r1_to_r2 = r2 - r1
                a1 = -r1_to_r2 / math.sqrt(np.dot(r1_to_r2, r1_to_r2))
                a1proj = np.array([a1[0], a1[1], 0.])
                a1projnorm = math.sqrt(np.dot(a1proj, a1proj))
                a3 = -(math.cos(np.deg2rad(inclination)) * ZAXIS +
                       math.sin(np.deg2rad(inclination)) * a1proj / a1projnorm)
                #a3 = -math.cos(np.deg2rad(inclination)) * ZAXIS - math.sin(np.deg2rad(inclination))* a1proj / a1projnorm
                ns2.add_nucleotide(
                    base.Nucleotide(r2 + base.CM_CENTER_DS * a1, a1, a3,
                                    sequence2[i]))
                r1 = np.dot(R, r1) - RISE * ZAXIS
                r2 = np.dot(R, r2) - RISE * ZAXIS

            #display_info(ns1,ns2,np.deg2rad(rot),RISE,diameter/2.)
            return ns1, ns2

        else:
            return ns1
Exemplo n.º 18
0
    def generate(self,
                 bp,
                 sequence=None,
                 start_pos=np.array([0, 0, 0]),
                 dir=np.array([0, 0, 1]),
                 perp=False,
                 double=True,
                 rot=None,
                 base_base_distance=None):
        base.CM_CENTER_DS -= 0.
        if (base_base_distance == None):
            base_base_distance = base.BASE_BASE
        if (rot == None):
            rot = 35.9
    # we need numpy array for these
        start_pos = np.array(start_pos, dtype=float)
        dir = np.array(dir, dtype=float)
        if sequence == None:
            sequence = np.random.randint(0, 4, bp)
        elif len(sequence) != bp:
            n = bp - len(sequence)
            sequence += np.random.randint(0, 4, n)
            base.Logger.log(
                "sequence is too short, adding %d random bases" % n,
                Logger.WARNING)

    # create the sequence of the second strand as made of complementary bases
        sequence2 = [3 - s for s in sequence]
        sequence2.reverse()

        # we need to find a vector orthogonal to dir
        dir_norm = np.sqrt(np.dot(dir, dir))
        if dir_norm < 1e-10:
            base.Logger.log(
                "direction must be a valid vector, defaulting to (0, 0, 1)",
                base.Logger.WARNING)
            dir = np.array([0, 0, 1])
        else:
            dir /= dir_norm

        if perp is None or perp is False:
            v1 = np.random.random_sample(3)
            v1 -= dir * (np.dot(dir, v1))
            v1 /= np.sqrt(sum(v1 * v1))
        else:
            v1 = perp

    # and we need to generate a rotational matrix
        R = utils.get_rotation_matrix(dir, np.deg2rad(rot))
        #R = get_rotation_matrix(dir, np.deg2rad(35.9))
        #R = utils.get_rotation_matrix(dir, [1, BP])

        ns1 = base.Strand()

        a1 = v1
        #a1 = np.dot (R0, a1)
        rb = np.array(start_pos)
        a3 = dir
        for i in range(bp):
            ns1.add_nucleotide(
                base.Nucleotide(rb - base.CM_CENTER_DS * a1, a1, a3,
                                sequence[i]))
            if i != bp - 1:
                a1 = np.dot(R, a1)
                rb += a3 * base_base_distance

        if double == True:
            a1 = -a1
            a3 = -dir
            R = R.transpose()
            ns2 = base.Strand()
            for i in range(bp):
                ns2.add_nucleotide(
                    base.Nucleotide(rb - base.CM_CENTER_DS * a1, a1, a3,
                                    sequence2[i]))
                a1 = np.dot(R, a1)
                rb += a3 * base_base_distance

            return ns1, ns2
        else:
            return ns1
Exemplo n.º 19
0
    def get_input(self, canvas=None, scale=None):
        rotation_matrices = [
            utils.get_rotation_matrix(d) for d in self.sensor_directions
        ]

        results = []
        for rotation_matrix in rotation_matrices:
            seen_objects = []
            direction = rotation_matrix @ self.game.snake.direction
            direction = direction / np.linalg.norm(direction)
            ray_vector = [
                self.game.snake.head_position + x for x in [0, direction]
            ]

            image = self.detect_point(ray_vector, self.game.food.pos,
                                      self.game.food.width)
            if image is not None:
                seen_objects.append((image, 'food'))

            for body_point in itertools.islice(self.game.snake.body, 1, None):
                image = self.detect_point(ray_vector, body_point,
                                          self.game.snake.width)
                if image is not None:
                    seen_objects.append((
                        image,
                        'body'))  #### TODO: HACK HACK HACK change back to body

            for wall in self.game.walls:
                for point in wall.endpoints:
                    image = self.detect_point(ray_vector, point, wall.width)
                    if image is not None:
                        seen_objects.append((image, 'wall'))

                # credit: https://rootllama.wordpress.com/2014/06/20/ray-line-segment-intersection-test-in-2d/
                v1 = self.game.snake.head_position - wall.endpoints[0]
                v2 = wall.endpoints[1] - wall.endpoints[0]
                v3 = np.array([-direction[1], direction[0]])
                denominator = v2 @ v3
                if denominator == 0:
                    continue  # in this case it will be handled by endpoints
                t_ray = -abs(np.cross(v2, v1)) / denominator
                t_wall = (v1 @ v3) / denominator

                if 0 <= t_wall <= 1 and t_ray >= 0:
                    seen_objects.append((t_ray, 'wall'))

            if not seen_objects:
                raise ValueError("Snake has seen beyond the edge of the world")
            seen_object = min(seen_objects)
            #results.append(np.array([seen_object[0]]))
            object_type = np.zeros(len(self.SENSOR_MAPPING)) + 2.5
            object_type[self.SENSOR_MAPPING.index(
                seen_object[1])] = seen_object[0]
            results.append(object_type)

            if canvas is not None:
                x, y = self.game.snake.head_position
                x, y = x * scale, y * scale
                m = x + direction[0] * seen_object[0] * scale
                n = y + direction[1] * seen_object[0] * scale
                canvas.create_line(x, y, m, n, width=1, fill="red")

        current_input = np.concatenate(results)
        self.inputs.append(current_input)

        result = self.inputs
        if len(result) < self.memory_size:
            return np.array(self.memory_size * list(result[-1]))
        return np.concatenate(result)
Exemplo n.º 20
0
    def capture(self, id, name):
        try:
            user_name = name
            id = id
        except:
            print("Vous devez entrer un nom")
        path = os.path.join(users_dir, user_name)
        if not os.path.isdir(path):
            os.mkdir(path)
        # Generate name for image file
        pin = sorted(
            [int(n[:n.find('.')])
             for n in os.listdir(path) if n[0] != '.'] + [0])[-1] + 1
        print("Le programmes va capturer 20 images. \
		\nDeplacez votre tete pour augmenter la precision pendant le fonctionnement.\n"
              )

        # The program loops until it has 20 images of the face.
        count = 0
        pause = 0
        t = 0
        count_max = 20
        # Loop until the camera is working

        # Loop until the camera is working
        for frame in camera.capture_continuous(rawCapture,
                                               format="bgr",
                                               use_video_port=True):

            if count >= count_max:
                rawCapture.seek(0)
                rawCapture.truncate(0)
                break

            # grab the raw NumPy array representing the image, then initialize the timestamp
            # and occupied/unoccupied text
            frame = frame.array

            # Get image size
            height, width, channels = frame.shape
            r = 100.0 / width
            dim = (100, int(height * r))

            # Flip frame
            frame = cv.flip(frame, 1, 0)

            # Convert to grayscale
            gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

            # Detect faces
            dets = detector(frame, 1)

            for i, det in enumerate(dets):
                shape = predictor(frame, det)
                left_eye = extract_left_eye_center(shape)
                right_eye = extract_right_eye_center(shape)

                M = get_rotation_matrix(left_eye, right_eye)
                rotated = cv.warpAffine(frame,
                                        M, (width, height),
                                        flags=cv.INTER_CUBIC)

                cropped = crop_image(rotated, det)
                cv.rectangle(frame, (det.left(), det.top()),
                             (det.right(), det.bottom()), (255, 255, 0), 2)

                # Remove false positives

                if (False):
                    print("Non claire")
                else:
                    # To create diversity, only save every fith detected image
                    if (pause == 0):
                        print("enregistrement de la capture " +
                              str(count + 1) + "/" + str(count_max))

                        # Save image file
                        cv.imwrite('%s/%s.png' % (path, pin), cropped)
                        pin += 1
                        count += 1
                        pause = 1

            if (pause > 0):
                pause = (pause + 1) % 3
            qtimg = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
            #qtimg = cv.resize(qtimg, dim, interpolation = cv.INTER_AREA)
            image = QtGui.QImage(qtimg, width, height, width * 3,
                                 QtGui.QImage.Format_RGB888)
            pixmap = QtGui.QPixmap.fromImage(image)
            pixmap_resized = pixmap.scaled(350, 260, QtCore.Qt.KeepAspectRatio)
            pixmapItem = QtWidgets.QGraphicsPixmapItem(pixmap_resized)
            if count == count_max:
                image = QtGui.QImage('camera.png')
                pixmap = QtGui.QPixmap.fromImage(image)
                pixmap_resized = pixmap.scaled(350, 260,
                                               QtCore.Qt.KeepAspectRatio)
                pixmapItem = QtWidgets.QGraphicsPixmapItem(pixmap_resized)
            self.scene.addItem(pixmapItem)
            rawCapture.seek(0)
            rawCapture.truncate(0)
            QtWidgets.QApplication.processEvents()
            key = cv.waitKey(10)

            if key == 27:
                break
        image = QtGui.QImage('/camera.png')
        idle = QtGui.QPixmap.fromImage(image)
        idle_resized = pixmap.scaled(350, 260, QtCore.Qt.KeepAspectRatio)
        pixmapItem = QtWidgets.QGraphicsPixmapItem(pixmap_resized)
        self.scene.addItem(pixmapItem)
        cv.destroyAllWindows()
        QtWidgets.QApplication.processEvents()
Exemplo n.º 21
0
                ".png") or filename.endswith(".jpeg") or filename.endswith(
                    ".bmp"):
            print('transforming ' + str(counter) + '/' + str(maxFiles) + ': ' +
                  filename)
            img = cv2.imread(input_image_folder + '/' + filename,
                             cv2.IMREAD_GRAYSCALE)
            height, width = img.shape[:2]
            s_height, s_width = height // scale, width // scale
            img = cv2.resize(img, (s_width, s_height))
            dets = detector(img, 1)
            for i, det in enumerate(dets):
                shape = predictor(img, det)
                left_eye = extract_left_eye_center(shape)
                right_eye = extract_right_eye_center(shape)

                M = get_rotation_matrix(left_eye, right_eye)
                rotated = cv2.warpAffine(img,
                                         M, (s_width, s_height),
                                         flags=cv2.INTER_CUBIC)

                cropped = crop_image(rotated, det)

                if filename.endswith('.jpg'):
                    output_image = filename.replace('.jpg', '_%i.jpg' % i)
                elif filename.endswith('.png'):
                    output_image = filename.replace('.png', '_%i.jpg' % i)
                elif filename.endswith('.jpeg'):
                    output_image = filename.replace('.jpeg', '_%i.jpg' % i)
                elif filename.endswith('.bmp'):
                    output_image = filename.replace('.bmp', '_%i.bmp' % i)
                else:
Exemplo n.º 22
0
    def generate_or_sq(self,
                       bp,
                       sequence=None,
                       start_pos=np.array([0., 0., 0.]),
                       direction=np.array([0., 0., 1.]),
                       perp=None,
                       double=True,
                       rot=0.,
                       angle=np.pi / 180 * 33.75,
                       length_change=0,
                       region_begin=0,
                       region_end=0):
        if length_change and len(region_begin) != len(region_end):
            if (len(region_end) + 1) == len(region_begin):
                base.Logger.log(
                    "the lengths of begin (%d) and end (%d) arrays are mismatched; I will try to proceed by using the number of basepairs as the last element of the end array"
                    % (len(region_begin), len(region_end)),
                    base.Logger.WARNING)
                region_end.append(bp + 1)
            else:
                base.Logger.die(
                    "the lengths of begin (%d) and end (%d) arrays are unrecoverably mismatched"
                    % (len(region_begin), len(region_end)))

        # we need numpy array for these
        start_pos = np.array(start_pos, dtype=float)
        direction = np.array(direction, dtype=float)
        if sequence == None:
            sequence = np.random.randint(0, 4, bp)
        elif len(sequence) != bp:
            n = bp - len(sequence)
            sequence += np.random.randint(0, 4, n)
            base.Logger.log(
                "sequence is too short, adding %d random bases" % n,
                base.Logger.WARNING)
        # angle should be an array, with a length 1 less than the # of base pairs
        if not isinstance(angle, np.ndarray):
            angle = np.ones(bp) * angle
        elif len(angle) != bp - 1:
            base.Logger.log(
                "generate_or_sq: incorrect angle array length, should be 1 less than number of base pairs",
                base.Logger.CRITICAL)
        # create the sequence of the second strand as made of complementary bases
        sequence2 = [3 - s for s in sequence]
        sequence2.reverse()

        # we need to find a vector orthogonal to direction
        dir_norm = np.sqrt(np.dot(direction, direction))
        if dir_norm < 1e-10:
            base.Logger.log(
                "direction must be a valid vector, defaulting to (0, 0, 1)",
                base.Logger.WARNING)
            direction = np.array([0, 0, 1])
        else:
            direction /= dir_norm

        if perp is None:
            v1 = np.random.random_sample(3)
            v1 -= direction * (np.dot(direction, v1))
            v1 /= np.sqrt(sum(v1 * v1))
        else:
            v1 = perp

        # and we need to generate a rotational matrix
        R0 = utils.get_rotation_matrix(direction, rot)

        ns1 = base.Strand()
        a1 = v1
        a1 = np.dot(R0, a1)
        rb = np.array(start_pos)
        a3 = direction
        Rs = []
        for i in range(bp):
            ns1.add_nucleotide(
                base.Nucleotide(rb - base.CM_CENTER_DS * a1, a1, a3,
                                sequence[i]))
            if i != bp - 1:
                R = utils.get_rotation_matrix(direction, angle[i])
                Rs.append(R)
                a1 = np.dot(R, a1)
                rb += a3 * base.BASE_BASE
                if length_change:
                    for j in range(len(length_change)):
                        if i >= region_begin[j] and i < region_end[j]:
                            if length_change[j]:
                                rb += a3 * base.BASE_BASE * (
                                    -(float(length_change[j]) /
                                      (region_end[j] - region_begin[j])))

        if double == True:
            a1 = -a1
            a3 = -direction
            ns2 = base.Strand()

            for i in range(bp):

                ns2.add_nucleotide(
                    base.Nucleotide(rb - base.CM_CENTER_DS * a1, a1, a3,
                                    sequence2[i]))
                if i != bp - 1:
                    # we loop over the rotation matrices in the reverse order, and use the transpose of each matrix
                    a1 = np.dot(Rs.pop().transpose(), a1)
                    rb += a3 * base.BASE_BASE
                    if length_change:
                        for j in range(len(length_change)):
                            if bp - 2 - i >= region_begin[
                                    j] and bp - 2 - i < region_end[j]:
                                if length_change[j]:
                                    rb += a3 * base.BASE_BASE * (
                                        -(float(length_change[j]) /
                                          (region_end[j] - region_begin[j])))

            return ns1, ns2
        else:
            return ns1
Exemplo n.º 23
0
	def run(self):
		old = ""
		self.count, self.count_u, confidence = 0, 0, 0
		print("thread is : ", int(self.thread().currentThreadId()))
		local_DB = sqlite3.connect('Data/users.db')
		cur = local_DB.cursor()
		start = time.time()
		while True:
			dur = time.time() - start
			dirty = False
			if dur > 10.0:
				queryb = {'id': 1}
				if float(self.temp()) > 60 :
					self.activate_fan()
				else :
					self.deactivate_fan()
				try:
					res1 = requests.post(urlb, data=queryb)
					#print(res1.text)
					start = time.time()
					print("pulsed")
					# mergeDB()
				except requests.ConnectionError as e:
					print("no connection")
					dirty = True

			while self.working:
				dure = time.clock()
				for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
					# grab the raw NumPy array representing the image, then initialize the timestamp
					# and occupied/unoccupied text
					if (not self.working):
						rawCapture.seek(0)
						rawCapture.truncate(0)
						break
					frame = frame.array

					height, width, channels = frame.shape
					# Convert to grayscalel
					gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

					# Resize to speed up detection (optinal, change size above)
					mini = cv.resize(
						frame, (int(gray.shape[1] / size), int(gray.shape[0] / size)))

					# Detect faces and loop through each one
					# faces = self.lbp_cascade.detectMultiScale(mini, 1.1, 3)
					dets = detector(gray, 1)
					um_faces = len(dets)
					if um_faces == 0:
						self.status.emit("Denied")
						self.user.emit("aucun personne")
					for i, det in enumerate(dets):
						shape = predictor(frame, det)
						left_eye = extract_left_eye_center(shape)
						right_eye = extract_right_eye_center(shape)

						M = get_rotation_matrix(left_eye, right_eye)
						rotated = cv.warpAffine(
							frame, M, (int(width / size), int(height / size)), flags=cv.INTER_CUBIC)

						cropped = crop_image(rotated, det)
						cropped = cv.cvtColor(cropped, cv.COLOR_BGR2GRAY)
						# Try to recognize the face
						if cropped is None:
							continue
						prediction, confidence = self.model.predict(cropped)
						print(confidence)
						cv.rectangle(frame, (det.left(), det.top()),
									 (det.right(), det.bottom()), (255, 255, 0), 2)
						if confidence < 160:
							# Grant accesss
							cur.execute("SELECT prenom, depatement FROM users WHERE nom = ?",(self.names[prediction],))
							row = cur.fetchone()
							print(row)
							print(prediction)
							if old == self.names[prediction]:
								self.count += 1
								if self.count > 3:
									count = 0
									self.status.emit("Autoriser")
									self.user.emit(
										"Bienvenue, Mr,{}".format(old))
									cur.execute(
										"INSERT INTO log (nom,prenom,departement,date) VALUES (?,?,?,datetime('now'))", (old, row[0], row[1]))
									local_DB.commit()
									query = {'name': old,
											 'prenom': row[0],
											 'departement':row[1]}
									if not dirty:
										res = requests.post(url, data=query)
									self.stop()
							else :
								old = self.names[prediction]
						else:
							self.status.emit("Denied")
							self.user.emit("non reconue")
							self.count_u += 1
							if self.count_u > 5:
								self.count_u = 0
								self.stop()
					# Show the image and check for ESC being pressed
					qtimg = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
					# qtimg = cv.resize(qtimg, dim, interpolation = cv.INTER_AREA)
					image = QtGui.QImage(qtimg, width,
										 height, width * 3, QtGui.QImage.Format_RGB888)
					pixmap = QtGui.QPixmap.fromImage(image)
					pixmap_resized = pixmap.scaled(
						350, 260, QtCore.Qt.KeepAspectRatio)
					pixmapItem = QtWidgets.QGraphicsPixmapItem(pixmap)
					self.changePixmap.emit(pixmapItem)
					rawCapture.seek(0)
					rawCapture.truncate(0)
					if (time.clock() - dure) > 20:
						self.stop()
					QtWidgets.QApplication.processEvents()
Exemplo n.º 24
0
    def generate(self, bp, sequence=None, start_pos=np.array([0, 0, 0]), dir=np.array([0, 0, 1]), perp=None, rot=0., double=True, circular=False, DELTA_LK=0, BP_PER_TURN=10.34, ds_start=None, ds_end=None, force_helicity=False):
        """
        Generate a strand of DNA.
            - linear, circular (circular)
            - ssDNA, dsDNA (double)
            - Combination of ss/dsDNA (ds_start, ds_end)
            Note: Relevent argument(s) in parentheses.

        Arguments:
        bp --- Integer number of bp/nt (required)
        sequence --- Array of integers or string. Should be same length as bp (default None)
            Default (None) generates a random sequence.
            Ex: [0,1,2,3,0]
            Ex: "AGCTA"
            See dictionary base.base_to_number for int/char conversion {0:'A'}
        start_pos --- Location to begin building the strand (default np.array([0, 0, 0]))
        dir --- a3 vector, orientation of the base (default np.array([0, 0, 1]))
        perp --- Sets a1 vector, the orientation of the backbone. (default False)
            Must be perpendicular to dir (as a1 must be perpendicular to a3)
            If perp is None or False, perp is set to a random orthogonal angle
        rot --- Rotation of first bp (default 0.)
        double --- Generate dsDNA (default True)
        circular --- Generate closed circular DNA (defalt False)
            Limitations...
            For ssDNA (double=False): bp >= 4
            For dsDNA (double=True) : bp >= 30
            Will throw warnings. Allowed, but use at your own risk.
        DELTA_LK --- Integer change in linking number from Lk0 (default 0)
            Only valid if circular==True
        BP_PER_TURN --- Base pairs per complete 2*pi helix turn. (default 10.34)
            Only valid if circular==True
        ds_start --- Index (from 0) to begin double stranded region (default None)
        ds_end --- Index (from 0) to end double stranded region (default None)
            Default is None, which is entirely dsDNA; sets ds_start = 0, ds_end=bp
            Ex: ds_start=0, ds_end=10 will create a double stranded region on bases
                range(0,10): [0,1,2,3,4,5,6,7,8,9]
            Note: To generate a nicked circular dsDNA, manually change state with
                  {Strand}.make_noncircular()
        force_helicity --- Force generation of helical strands. Use helicity by default
            for bp > 30. Warns from 18 to 29. Will crash oxDNA below 18. (default False)

        Note: Minimuim circular duplex is 18. Shorter circular strands disobey FENE.
        For shorter strands, circular ssDNA is generated in a circle instead of having
        imposed helicity.

        Examples:
        Generate ssDNA:
            generate(bp=4,sequence=[0,1,2,3],double=False,circular=False)
        Generate circular dsDNA with +2 Linking number:
            generate(bp=45,double=True,circular=True,DELTA_LK=2)
        Generate a circular ssDNA (45nt) with ssDNA (25nt) annealed to indices 0 to 24:
            generate(bp=45,double=True,circular=True,ds_start=0,ds_end=25)
        """
        # we need numpy array for these
        start_pos = np.array(start_pos, dtype=float)
        dir = np.array(dir, dtype=float)
        if isinstance(sequence, list):
            sequence = np.array(sequence)

        # Loads of input checking...
        if isinstance(sequence, str):
            try:
                sequence = [base.base_to_number[x] for x in sequence]
            except KeyError:
                base.Logger.die("Key Error: sequence is invalid" % n)
        if sequence == None:
            sequence = np.random.randint(0, 4, bp)
        elif len(sequence) != bp:
            n = bp - len(sequence)
            sequence = np.append(sequence, np.random.randint(0, 4, n))
            base.Logger.log("sequence is too short, adding %d random bases" % n, base.Logger.WARNING)

        if circular == True and bp < 30:
            # 30 is about the cut off for circular dsDNA. Anything shorter will probably clash.
            # oxDNA can relax down to 18.
            # 4 is about the cut off for circular ssDNA. Use dsDNA cutoff for saftey.
            base.Logger.log("sequence is too short! Proceed at your own risk", base.Logger.WARNING)

        option_use_helicity = True
        if circular == True and bp < 30 and double == False:
            base.Logger.log("sequence is too short! Generating ssDNA without imposed helicity", base.Logger.WARNING)
            # Do not impose helcity to generate shorter circular ssDNA
            if not force_helicity:
                option_use_helicity = False

        if ds_start == None:
            ds_start = 0
        if ds_end == None:
            ds_end = bp
        if ds_start > ds_end:
            base.Logger.die("ds_end > ds_start")
        if  ds_end > bp:
            base.Logger.die("ds_end > bp")

        # we need to find a vector orthogonal to dir
        dir_norm = np.sqrt(np.dot(dir,dir))
        if dir_norm < 1e-10:
            base.Logger.log("direction must be a valid vector, defaulting to (0, 0, 1)", base.Logger.WARNING)
            dir = np.array([0, 0, 1])
        else:
            dir /= dir_norm

        if perp is None or perp is False:
            v1 = np.random.random_sample(3)
            v1 -= dir * (np.dot(dir, v1))
            v1 /= np.sqrt(sum(v1*v1))
        else:
            v1 = perp;

        # Setup initial parameters
        ns1 = base.Strand()
        # and we need to generate a rotational matrix
        R0 = utils.get_rotation_matrix(dir, rot)
        #R = get_rotation_matrix(dir, np.deg2rad(35.9))
        R = utils.get_rotation_matrix(dir, [1, BP])
        a1 = v1
        a1 = np.dot (R0, a1)
        rb = np.array(start_pos)
        a3 = dir

        # Circular strands require a continuious deformation of the ideal helical pitch
        if circular == True:
            # Unit vector orthogonal to plane of torus
            # Note: Plane of torus defined by v1,dir
            torus_perp = np.cross(v1,dir)
            # bp-bp rotation factor to yield a smooth deformation along the torus
            smooth_factor = np.mod(bp,BP_PER_TURN)/float(bp) + 1
            # Angle between base pairs along torus
            angle = 2. * np.pi / float(bp)
            # Radius of torus
            radius = base.FENE_R0_OXDNA / math.sqrt(2. * (1. - math.cos(angle)));

        if circular == True and option_use_helicity:
            # Draw backbone in a helical spiral around a torus
            # Draw bases pointing to center of torus
            for i in range(bp):
                # Torus plane defined by dir and v1
                v_torus = v1 *base.BASE_BASE * math.cos(i * angle) + \
                        dir * base.BASE_BASE * math.sin(i * angle)
                rb += v_torus

                # a3 is tangent to the torus
                a3 = v_torus/np.linalg.norm(v_torus)
                R = utils.get_rotation_matrix(a3, [i * (round(bp/BP_PER_TURN) + DELTA_LK)/float(bp) * 360, DEGREES])

                # a1 is orthogonal to a3 and the torus normal
                a1 = np.cross (a3, torus_perp)

                # Apply the rotation matrix
                a1 = np.dot(R, a1)
                ns1.add_nucleotide(base.Nucleotide(rb - base.CM_CENTER_DS * a1, a1, a3, sequence[i]))
            ns1.make_circular(check_join_len=True)
        elif circular == True and not option_use_helicity:
            for i in xrange(bp):
                rbx = math.cos (i * angle) * radius + 0.34 * math.cos(i * angle)
                rby = math.sin (i * angle) * radius + 0.34 * math.sin(i * angle)
                rbz = 0.
                rb = np.array([rbx, rby, rbz])
                a1x = math.cos (i * angle)
                a1y = math.sin (i * angle)
                a1z = 0.
                a1 = np.array([a1x, a1y, a1z])
                ns1.add_nucleotide(base.Nucleotide(rb, a1, np.array([0, 0, 1]), sequence[i]))
            ns1.make_circular(check_join_len=True)
        else:
            # Add nt in canonical double helix
            for i in range(bp):
                ns1.add_nucleotide(base.Nucleotide(rb - base.CM_CENTER_DS * a1, a1, a3, sequence[i]))
                if i != bp-1:
                    a1 = np.dot(R, a1)
                    rb += a3 * base.BASE_BASE

        # Fill in complement strand
        if double == True:
            ns2 = base.Strand()
            for i in reversed(range(ds_start, ds_end)):
                # Note that the complement strand is built in reverse order
                nt = ns1._nucleotides[i]
                a1 = -nt._a1
                a3 = -nt._a3
                nt2_cm_pos = -(base.FENE_EPS + 2*base.POS_BACK) * a1 + nt.cm_pos
                ns2.add_nucleotide(base.Nucleotide(nt2_cm_pos, a1, a3, 3-sequence[i]))
            if ds_start == 0 and ds_end == bp and circular == True:
                ns2.make_circular(check_join_len=True)
            return ns1, ns2
        else:
            return ns1