Example #1
0
    def __init__(self, filename, scale):

        self.file = open(filename, 'r')

        # Read hierarchy
        self.__expectKeyword('HIERARCHY')

        items = self.__expectKeyword('ROOT')

        self.root = Joint(items[1])

        self.__readJoint(self.root, scale)

        # Read motion
        self.__expectKeyword('MOTION')

        items = self.__expectKeyword('Frames:')
        self.frames = int(items[1])
        items = self.__expectKeyword('Frame')  # Time:
        self.frameTime = float(items[2])

        for i in range(self.frames):
            line = self.file.readline()
            items = line.split()
            data = [float(item) for item in items]
            data = self.__getChannelData(self.root, data)
Example #2
0
    def draw_left_arm(self,
                      left_shoulder_lateral_radians=0,
                      left_shoulder_frontal_radians=0,
                      left_elbow_lateral_radians=0,
                      color='c-',
                      draw=True):

        left_shoulder_lateral = Joint(
            dh_params=(-half_pi + left_shoulder_lateral_radians,
                       shoulder_length, 0, -half_pi),
            initial_transformation=self._get_torso_corner_transformation(
                left_shoulder_position, 'x', -half_pi))

        left_shoulder_frontal = Joint(
            prev_joint=left_shoulder_lateral,
            dh_params=(half_pi - left_shoulder_frontal_radians, 0,
                       -upper_arm_length, -half_pi))

        left_elbow_lateral = Joint(prev_joint=left_shoulder_frontal,
                                   dh_params=(-left_elbow_lateral_radians, 0,
                                              0, 0))

        left_wrist_t = left_elbow_lateral.link_t.dot(
            get_translate_matrix(-lower_arm_length, 0, 0))
        left_wrist = apply_matrix_to_origin(left_wrist_t)

        if draw:
            self.draw_link(left_shoulder_lateral, color)
            self.draw_link(left_shoulder_frontal, color)
            self._painter.draw_line(left_elbow_lateral.vertex,
                                    left_wrist,
                                    color=color)

        return left_shoulder_lateral, left_shoulder_frontal, left_elbow_lateral, left_wrist
Example #3
0
    def __init__(self, line_flag=False):

        # log setting
        program = os.path.basename(__name__)
        self.logger = logging.getLogger(program)
        logging.basicConfig(
            format='%(asctime)s : %(name)s : %(levelname)s : %(message)s')

        # load config file
        f = open(Experiment.CONFIG_YAML, 'r')
        self.config = yaml.load(f)
        f.close()

        self.english_corpus_dir = self.config['english_corpus_dir']
        self.japanese_corpus_dir = self.config['japanese_corpus_dir']
        self.japanese_original_corpus_dir = self.config[
            'japanese_original_corpus_dir']
        self.img_features_npy = self.config['img_features_npy']
        self.img_original_dir = self.config['img_original_dir']
        self.img_correspondence_path = self.config['img_correspondence_path']

        self.joint = Joint(self.english_corpus_dir, self.img_features_npy,
                           self.japanese_corpus_dir, self.img_original_dir,
                           self.img_correspondence_path,
                           self.japanese_original_corpus_dir,
                           Experiment.PCA_COMPRESS_WORD_DIM,
                           Experiment.PCA_COMPRESS_IMG_DIM, line_flag)
        self.logger.info("<Initilalizing Experiment>")
        if Experiment.SEED_NUM is not None:
            self.logger.info("seed: %s", Experiment.SEED_NUM)
            np.random.seed(Experiment.SEED_NUM)
    def __init__(self, en_dir, img_path, jp_dir, img_original_dir=None, img_correspondence_path=None, jp_original_dir=None, compress_word_dim=100, compress_img_dim=100, line_flag=False):

        Joint.__init__(self, en_dir, img_path, jp_dir, img_original_dir, img_correspondence_path, jp_original_dir, compress_word_dim, compress_img_dim, line_flag)

        self.bcca = gcca.BridgedCCA()

        self.__prep_dir()
Example #5
0
    def setup_joints(self):
        pi = pigpio.pi()

        # pi.set_mode(constants.GPIO_GRABBER, pigpio.OUTPUT)
        # pi.set_mode(constants.GPIO_ELBOW, pigpio.OUTPUT)
        # pi.set_mode(constants.GPIO_WRIST, pigpio.OUTPUT)

        self.joints = {
            ServoName.GRABBER:
            Joint(ServoName.GRABBER.value, constants.GPIO_GRABBER,
                  constants.GRABBER_POS_INIT, constants.GRABBER_POS_MIN,
                  constants.GRABBER_POS_MAX, constants.SERVO_POS_DELTA,
                  self.curr_control_type, self.locked, self.held,
                  self.last_pressed_button_joint,
                  self.last_pressed_button_command, pi, False),
            ServoName.ELBOW:
            Joint(ServoName.ELBOW.value, constants.GPIO_ELBOW,
                  constants.ELBOW_POS_INIT, constants.ELBOW_POS_MIN,
                  constants.ELBOW_POS_MAX, constants.SERVO_POS_DELTA,
                  self.curr_control_type, self.locked, self.held,
                  self.last_pressed_button_joint,
                  self.last_pressed_button_command, pi, False),
            ServoName.WRIST:
            Joint(ServoName.WRIST.value, constants.GPIO_WRIST,
                  constants.WRIST_POS_INIT, constants.WRIST_POS_MIN,
                  constants.WRIST_POS_MAX, constants.SERVO_POS_DELTA,
                  self.curr_control_type, self.locked, self.held,
                  self.last_pressed_button_joint,
                  self.last_pressed_button_command, pi, True)
        }
Example #6
0
 def make_finger(nameSuffix, mat, L2, L3, L4):
     i = str(nameSuffix)
     return JointDOF2('MCP'+i, mat, (-Pi/9, Pi/9), (-Pi/2, 0), [
         Joint('PIP'+i, Joint.make_mat((L2, 0, 0), -Pi/6), (-Pi/2, 0), [
             Joint('DIP'+i, Joint.make_mat((L3, 0, 0), -Pi/6), (-Pi/2, 0), [
                 Joint('EP'+i, Joint.make_mat((L3, 0, 0), -Pi/6), None, [])
             ])
         ])
     ])
Example #7
0
def main():
    "Function to contsruct an arm and input movements"

    parts = [
        Joint(name='r1', z_axis=[0, 0, 1]),
        Bone(length=5),
        Joint(name='r2', z_axis=[0, 1, 0])
    ]

    robot_arm = Arm(parts=parts)
Example #8
0
        def addNew(val):
            joint = Joint(1, self.numJoints)
            joint.initJoint = jointInit
            self.joints.append(joint)

            self.numJoints += 1
            self.link_slide.valmax = self.numJoints - 1
            self.link_slide.ax.set_xlim(self.link_slide.valmin,
                                        self.link_slide.valmax)
            update_link()
Example #9
0
	def __init__(self, robot, motion_proxy, am_proxy):
		self.posture = Posture(robot, motion_proxy)
		self.motion_proxy = motion_proxy
		self.am_proxy = am_proxy
		self.manager_proxy = ALProxy("ALBehaviorManager", robot.ip, robot.port)
		self.master_joint = Joint(motion_proxy)
		self.unrefined_movement = Unrefined_Control(master_joint, motion_proxy)
		self.is_aware = True
		self.robot_upper_joints = ['Head', 'LShoulder', 'LElbow', 'LWrist', 'RShoulder', 'RElbow', 'RWrist','LHand', 'RHand']
		self.previous_behaviour = None
		pass
Example #10
0
 def create_empty_data_struct(self):
     COF = Joint(None, None, "COF")
     COM = Joint(None, None, "COF")
     C7 = Joint(None, None, "COF")
     angle_lower = Angle(None, None, "angle_lower")
     angle_trunk = Angle(None, None, "angle_trunk")
     phase = OLD_PHASE_OUT_PHASE(None, None, None, name="phase")
     return Move(cof=COF,
                 com=COM,
                 c7=C7,
                 angle_l=angle_lower,
                 angle_t=angle_trunk,
                 phase=phase)
Example #11
0
    def draw_neck_and_head(self,
                           neck_transversal_radians=0,
                           neck_lateral_radians=0):

        neck_transversal = Joint(
            dh_params=(0 + neck_transversal_radians, neck_length, 0, half_pi),
            initial_transformation=get_translate_matrix(0, 0, torso_height))

        neck_lateral = Joint(prev_joint=neck_transversal,
                             dh_params=(-neck_lateral_radians, 0, 0, 0))
        self.draw_link(neck_transversal)

        self._draw_head(head_t=neck_lateral.link_t)
    def __init__(self, line_flag=False):

        # log setting
        program = os.path.basename(__name__)
        self.logger = logging.getLogger(program)
        logging.basicConfig(format='%(asctime)s : %(name)s : %(levelname)s : %(message)s')

        # load config file
        f = open(Experiment.CONFIG_YAML, 'r')
        self.config = yaml.load(f)
        f.close()

        self.english_corpus_dir = self.config['english_corpus_dir']
        self.japanese_corpus_dir = self.config['japanese_corpus_dir']
        self.japanese_original_corpus_dir = self.config['japanese_original_corpus_dir']
        self.img_features_npy = self.config['img_features_npy']
        self.img_original_dir = self.config['img_original_dir']
        self.img_correspondence_path = self.config['img_correspondence_path']

        self.joint = Joint(
            self.english_corpus_dir,
            self.img_features_npy,
            self.japanese_corpus_dir,
            self.img_original_dir,
            self.img_correspondence_path,
            self.japanese_original_corpus_dir,
            Experiment.PCA_COMPRESS_WORD_DIM,
            Experiment.PCA_COMPRESS_IMG_DIM,
            line_flag
        )
        self.logger.info("<Initilalizing Experiment>")
        if Experiment.SEED_NUM is not None:
            self.logger.info("seed: %s" , Experiment.SEED_NUM)
            np.random.seed(Experiment.SEED_NUM)
Example #13
0
    def createSkeleton(self, node, parent=None):
        """Create the skeleton hierarchy.

        This method creates the skeleton recursively. Each invocation
        creates one joint.
        """
        order = self.rotationOrder(node.channels)
        # Create a new Joint object
        j = Joint(name=node.name,
                  pos=vec3(node.offset),
                  rotationorder=order,
                  parent=parent)
        # Store the joint in the node so that later the motion can be applied
        node.joint = j

        vtx = ValueTable(type="double")
        vty = ValueTable(type="double")
        vtz = ValueTable(type="double")
        vtx.output_slot.connect(j.anglex_slot)
        vty.output_slot.connect(j.angley_slot)
        vtz.output_slot.connect(j.anglez_slot)
        node.vtx = vtx
        node.vty = vty
        node.vtz = vtz
        if node.isRoot():
            vtpos = ValueTable(type="vec3")
            vtpos.output_slot.connect(j.pos_slot)
            node.vtpos = vtpos

        for c in node.children:
            self.createSkeleton(c, j)
Example #14
0
def get_joints_from_table(table):
    joints = []
    if not (table_ok):
        raise ValueError('Antecedants should be sorted in the table')
    for j, row in enumerate(table):
        if (row[0] == 0):
            antc = None
        else:
            antc = joints[row[0] - 1]
        # TODO: redefine sameas by starting with index 0 (-1 <=> None)
        if (row[1] == 0):
            sameas = None
        else:
            sameas = joints[row[1] - 1]
        jnt = Joint(
            j=j + 1,
            antc=antc,
            sameas=sameas,
            mu=row[2],
            sigma=row[3],
            gamma=row[4],
            b=row[5],
            alpha=row[6],
            d=row[7],
            theta=row[8],
            r=row[9],
        )
        joints.append(jnt)
    # TODO: add recursion detection for antecedants
    return joints
def setup_solver(solver):
    Pi = np.pi
    def get_pos(stringIdx, fretIdx, z=0.):
        fp = FretPos(stringIdx, fretIdx)
        x, y = fretSp.pos_fret_to_plane(fp)
        return np.dot(fretSp.localMat, [x, y, z, 1])[:3]
    X1 = [ ('EP1', (6, 1)), ('EP2', (2, 2)), ('EP3', (3, 3)), ('EP4', (1, 3)), ]
    Am = [ ('EP1', (2, 1)), ('EP2', (4, 2)), ('EP3', (3, 2)), ]
    F = [ ('EP1', (6, 1)), ('EP2', (3, 2)), ('EP3', (5, 3)), ('EP4', (4, 3)), ]

    C = [ ('EP1', (2, 1)), ('EP2', (4, 2)), ('EP3', (5, 3)), ] 
    bar = 0
    C7 = [ ('EP1', (2, bar+1)), ('EP2', (4, bar+2)), ('EP3', (5, bar+3)), ('EP4', (1, bar+3)), ]
    G = [ ('EP3', (6, 3)), ('EP2', (5, 2)), ('EP4', (1, 3)), ]
    Em = [ ('EP2', (5, 2)), ('EP3', (4, 2)), ]
    Dm = [ ('EP1', (1, 1)), ('EP2', (3, 2)), ('EP4', (2, 3)), ('EP3', (4, 3)), ]
    GB = [ ('EP1', (6, 3)), ('EP4', (1, 7)), ]
    B7 = [ ('EP1', (4, 1)), ('EP2', (5, 2)), ('EP3', (3, 2)), ('EP4', (1, 2)), ]
    A = [('EP1', (4, 2)),('EP2', (3, 2)),('EP3', (2, 2))]

    # Choose an arrangement
    arrangement = A
    fretSp.set_marks([FretPos(i, j) for (_, (i, j)) in arrangement])

    # Prepare the solver
    solver.set_joints(model.root)
    solver.set_target_pos([(f, get_pos(i, j)) for (f, (i, j)) in arrangement])
    for (f, (i, j)) in arrangement:
        joint = Joint.get(f)
        s = model.scales[['EP0', 'EP1', 'EP2', 'EP3', 'EP4'].index(f)]
        pos = get_pos(i, j, s * model.L4)
        solver.set_constaints([
            RefPosConstraint(joint.parent, pos, .8)
            ])

    # define constraints
    solver.set_constaints([
        # RefAngleConstraint(Joint.get('MCP1z'), -Pi/6, 1),
        # RefAngleConstraint(Joint.get('MCP2z'), -Pi/6, 1),
        # RefAngleConstraint(Joint.get('MCP3z'), -Pi/6, 1),
        # RefAngleConstraint(Joint.get('MCP4z'), -Pi/6, 1),
        RefAngleConstraint(Joint.get('MCP1y'), -Pi/8, 1),
        RefAngleConstraint(Joint.get('MCP2y'), 0, 1),
        RefAngleConstraint(Joint.get('MCP3y'), 0, 1),
        RefAngleConstraint(Joint.get('MCP4y'), Pi/8, 1),
    ])
    return solver
Example #16
0
def build_joint(joint_id: id, reverse_direction: int):
    servo = Servo(joint_id, False)
    joint = Joint(servo,
                  min_angle=0,
                  max_angle=180,
                  reverse_direction=reverse_direction,
                  instant_move=False)
    return joint
Example #17
0
 def constructJoints(self, jointFile):
     f = open(jointFile, 'r')
     tempjoint = []
     next(f)
     for line in f:
         tempjoint.append(Joint(line))
     f.close()
     return tempjoint
Example #18
0
    def __init__(self,
                 en_dir,
                 img_path,
                 jp_dir,
                 img_original_dir=None,
                 img_correspondence_path=None,
                 jp_original_dir=None,
                 compress_word_dim=100,
                 compress_img_dim=100,
                 line_flag=False):

        Joint.__init__(self, en_dir, img_path, jp_dir, img_original_dir,
                       img_correspondence_path, jp_original_dir,
                       compress_word_dim, compress_img_dim, line_flag)

        self.bcca = gcca.BridgedCCA()

        self.__prep_dir()
Example #19
0
def coord_to_joint(coord, person_id, conf):
    # type: (Tuple[int, float, float, float], int, float) -> Joint
    """
    Given a `coord`, i.e. a tuple (jtype, x3d, y3d, z3d) and a person ID,
    returns the corresponding `Joint` object
    """
    return Joint(np.array(
        [-1, person_id, coord[0], -1, -1, coord[1], coord[2], coord[3], 0, 0]),
                 confidence=conf)
Example #20
0
File: body.py Project: sainy/robot
class RightLeg:
    r_toe = Joint("right toe", init_pos={"x": 9, "y": 10, "z": 0})
    r_sole = Joint("right sole",
                   init_pos={
                       "x": 6,
                       "y": 5,
                       "z": 0
                   },
                   dw_joint=[r_toe])
    r_ankle = Joint("right ankle",
                    init_pos={
                        "x": 3,
                        "y": -1,
                        "z": 0
                    },
                    dw_joint=[r_sole])
    r_knee = Joint("right knee",
                   init_pos={
                       "x": 4,
                       "y": 0,
                       "z": 40
                   },
                   dw_joint=[r_ankle])
    r_thigh = Joint("right thigh",
                    init_pos={
                        "x": 3,
                        "y": 0,
                        "z": 95
                    },
                    dw_joint=[r_knee])

    def __init__(self):
        rl = {"name": "RightLeg"}
        rl["controller"] = [
            self.r_toe, self.r_sole, self.r_ankle, self.r_knee, self.r_thigh
        ]
        Store.register(rl)

    def printInfo(self):
        self.r_toe.printInfo()
        self.r_sole.printInfo()
        self.r_ankle.printInfo()
        self.r_knee.printInfo()
        self.r_thigh.printInfo()
Example #21
0
File: body.py Project: sainy/robot
class LeftLeg:
    l_toe = Joint("left toe", init_pos={"x": -9, "y": 10, "z": 0})
    l_sole = Joint("left sole",
                   init_pos={
                       "x": -6,
                       "y": 5,
                       "z": 0
                   },
                   dw_joint=[l_toe])
    l_ankle = Joint("left ankle",
                    init_pos={
                        "x": -3,
                        "y": -1,
                        "z": 0
                    },
                    dw_joint=[l_sole])
    l_knee = Joint("left knee",
                   init_pos={
                       "x": -4,
                       "y": 0,
                       "z": 40
                   },
                   dw_joint=[l_ankle])
    l_thigh = Joint("left thigh",
                    init_pos={
                        "x": -3,
                        "y": 0,
                        "z": 95
                    },
                    dw_joint=[l_knee])

    def __init__(self):
        ll = {"name": "LeftLeg"}
        ll["controller"] = [
            self.l_toe, self.l_sole, self.l_ankle, self.l_knee, self.l_thigh
        ]
        Store.register(ll)

    def printInfo(self):
        self.l_toe.printInfo()
        self.l_sole.printInfo()
        self.l_ankle.printInfo()
        self.l_knee.printInfo()
        self.l_thigh.printInfo()
Example #22
0
    def onHierarchy(self, links):
        # At the end, this list contains the leaves which need
        # a dummy joint at the end.
        leaves = []
        for parentname, childnames in links:
            leaves += childnames
            if parentname in leaves:
                leaves.remove(parentname)
            # Create the second joint of the bone called parentname
            # (which is the first joint of the bone called data["name"])
            parent = self.joints[parentname]
            data = self.bones[parentname]
            dir = data["direction"].normalize()
            length = data["length"]
            for childname in childnames:
                data = self.bones[childname]
                axis = data["axis"]
                ao = data["axis_order"]
                axis_order = ao[2]+ao[1]+ao[0]
                j = Joint(name = data["name"],
                          rotationorder = axis_order,
                          radius = 0.3,
                          pos = length*dir.normalize(),
                          parent = parent)
                exec "fromEuler = mat3.fromEuler%s"%axis_order.upper()
                R = fromEuler(radians(axis.x), radians(axis.y), radians(axis.z))
                j.setOffsetTransform(mat4(1).setMat3(R))
                j.freezePivot()
                self.joints[j.name] = j

        # Create end joints
        for name in leaves:
            parent = self.joints[name]
            data = self.bones[name]
            try:
                dir = data["direction"].normalize()
            except:
                dir = vec3(0)
            length = data["length"]
            Joint(name = name+"_end",
                  rotationorder = "xyz",
                  radius = 0.3,
                  pos = length*dir,
                  parent = parent)
Example #23
0
 def set_target_pos(self, jointPosPairs):
     """
     @param jointPosPairs: [(str, Pos3D)], a list of (jointName, effectorPos) 
         pairs.
     """
     self.m = m = 3 * len(jointPosPairs)
     self.targetPoss = T = np.zeros(m, dtype=np.double)
     for i, (jname, pos) in enumerate(jointPosPairs):
         self.targets.append(Joint.get(jname))
         T[3 * i : 3 * i + 3] = pos
Example #24
0
def get_pose(frame_data, person_id):
    # type: (np.ndarray, int) -> Pose
    """
	:param frame_data: data of the current frame
	:param person_id: person identifier
	:return: list of joints in the current frame with the required person ID
	"""
    pose = [Joint(j) for j in frame_data[frame_data[:, 1] == person_id]]
    pose.sort(key=(lambda j: j.type))
    return Pose(pose, "JTA")
Example #25
0
def demo_7() -> World:
    world = World(gravity=GRAVITY, iterations=IMPULSE_ITERATIONS)

    Ground = Body([100.0, 10.0])
    Ground.position = np.array([0.0, 0.5 * Ground.width[1]])
    world.add_body(Ground)

    PLANK_COUNT = 15
    PLANK_MASS = 50.0
    PLANK_WIDTH = 5.0
    GAP = 1.25
    period = PLANK_WIDTH + GAP
    deck_length = period * PLANK_COUNT - GAP
    deck_startx = -deck_length / 2
    joint_startx = -deck_length / 2 - GAP / 2

    planks = []
    for i in range(PLANK_COUNT):
        p = Body([PLANK_WIDTH, 0.25 * 5], PLANK_MASS)
        p.position = np.array(
            [deck_startx + PLANK_WIDTH / 2 + period * i, 25.0])
        planks.append(p)
        world.add_body(p)

    # Joint Tuning
    FREQUENCY_HERTZ = 2.0
    frequency_radians = 2.0 * np.pi * FREQUENCY_HERTZ
    DAMPING_RATIO = 0.7
    damping_coeffcient = 2.0 * PLANK_MASS * DAMPING_RATIO * frequency_radians
    stiffness = PLANK_MASS * frequency_radians**2
    softness = 1 / (damping_coeffcient + TIMESTEP * stiffness)
    bias_factor = TIMESTEP * stiffness / (damping_coeffcient +
                                          TIMESTEP * stiffness)

    limbs = [Ground] + planks + [Ground]
    for i, (limb1, limb2) in enumerate(zip(limbs, limbs[1:])):
        j = Joint(limb1, limb2, np.array([joint_startx + period * i, 25.0]))
        j.softness = softness
        j.bias_factor = bias_factor
        world.add_joint(j)

    return world
Example #26
0
def refine_pose(pose, refiner):
    # type: (Sequence[Sequence[float]], Refiner) -> Optional[List[np.ndarray]]
    """
    :param pose: list of joints where each joint is in the form [jtype, x3d, y3d, z3d]
    :param refiner: pose refiner model
    :return: refined pose -> list of 14 ordered joints where each joint is in the form [x3d, y3d, z3d]
        >> see `Joint.NAMES` for joint order
    """

    # convert `pose` list into a `Pose` object
    joints = []
    for jtype in range(14):
        _joint = [j for j in pose if j[0] == jtype]
        if len(_joint) == 1:
            _, x, y, z = _joint[0][0], _joint[0][1], _joint[0][2], _joint[0][3]
            joint = np.array([-1, -1, jtype, -1, -1, x, y, z, 0, 0])
            joint = Joint(joint)
            joints.append(joint)
        else:
            joint = np.array([-1, -1, jtype, -1, -1, -1, -1, -1, 1, 1])
            joint = Joint(joint)
            joints.append(joint)
    pose = Pose(joints)

    # convert `Pose` object into a fountain
    rr_pose_pred = pose.to_rr_pose(MAX_LS)
    for jtype in range(1, 14):
        if not pose[jtype].visible:
            rr_pose_pred[jtype - 1] = np.array([-1, -1, -1])
    rr_pose_pred = torch.tensor(rr_pose_pred).unsqueeze(0).float()

    # refine fountain with `refiner` model
    refined_rr_pose_pred = refiner.forward(rr_pose_pred).numpy().squeeze()

    if pose[0].type == 0:
        refined_pose_pred = Pose.from_rr_pose(refined_rr_pose_pred,
                                              head_pos3d=pose[0].pos3d,
                                              max_ls=MAX_LS)
        return refined_pose_pred
    else:
        return None
Example #27
0
    def __init__(self, interruptCallback, log):
        """The interruptCallack function must be provided so the caller can receive interrupts from the sensors"""

        # Remember the callback function so we can call it when an interrupt condition is met
        self.interruptCallback = interruptCallback

        ## Set up the joint on the given Servo Bonnet pin
        self.joint = Joint(4)

        # Set up the distance sensor on the given RPi pin
        self.distanceSensor = DistanceSensor(14, log)
        self._distanceSensorThread = None  # thread on which to run continuous monitoring
        self._runningDistanceSensor = False  # flag to indicate if continuous monitoring is running
        self._pauseDistanceSensor = False  # flag to indicate if continuous monitoring is paused
        self.lastDistance = None  # last distance measured

        # Set up the thermal sensor (uses I2C to the RPi)
        # The thermal sensor reads a 8x8 matrix (64 readings)
        self.thermalSensor = ThermalSensor()
        self.thermalSensorThread = None  # thread on which to run continuous monitoring
        self._runningThermalSensor = False  # flag to indicate if continuous monitoring is running
        self._pauseThermalSensor = False  # flag to indicate if continuous monitoring is paused
        self.lastMaxTemperature = None  # last max temperature read from the 8x8 matrix
        self.lastMinTemperature = None  # last min temperature read from the 8x8 matrix

        # Set up the PIR, which is on the tail
        self.tail = MotionSensor(13)

        # Settings - can be overridden by the body
        self.joint.midAngle = 90  # midpoint angle for servo (facing forwards)
        self.joint.highAngle = 135  # high angle for servo (rightmost angle)
        self.joint.lowAngle = 45  # lowest angle for servo (leftmost angle)
        self.trackDelta = 10  # change in angle each iteration when tracking movement
        self.shortDistance = 20  # distance in cm to obstacle below which triggers a short-distance interrupt
        self.longDistance = 1000  # distance in cm to obstacle above which triggers a long-distance interrupt
        self.humanDetectMinTemperature = 26  # temperature in C which triggers human-detect interrupt
        self.humanDetectMaxTemperature = 30  # temperature in C which triggers human-detect interrupt
        self.colMovementThreshold = 5  # total temperature change in a matrix column above which we say we saw movement
        self.movementWaitSeconds = 2  # how long to wait between thermal readings to detect movement

        self.log = log
Example #28
0
File: body.py Project: sainy/robot
class Body:
    """this class is used to initial the whole body.

    each key point in the body is definited at this place."""
    Left_hand = LeftHand()
    Right_hand = RightHand()
    Left_leg = LeftLeg()
    Right_leg = RightLeg()
    head = Joint("The head top", init_pos={"x": 0, "y": 0, "z": 175})
    neck = Joint("body's neck",
                 init_pos={
                     "x": 0,
                     "y": 0,
                     "z": 150
                 },
                 dw_joint=[head, Left_hand.l_hand, Right_hand.r_hand])
    back = Joint("the back of body",
                 init_pos={
                     "x": 0,
                     "y": 0,
                     "z": 125
                 },
                 dw_joint=[neck])
    waist = Joint("the waist of body",
                  init_pos={
                      "x": 0,
                      "y": 0,
                      "z": 110
                  },
                  dw_joint=[back, Left_leg.l_thigh, Right_leg.r_thigh])

    def __init__(self):
        body = {"name": "The whole body"}
        body["controller"] = [self.head, self.neck, self.back, self.waist]
        Store.register(body)

    def printInfo(self):
        self.waist.printInfo()
Example #29
0
    def load_model(self):
        n = len(self)
        x_mid_cheville = (np.ones(n) * (self.raw.ankle_r + self.raw.ankle_l) /
                          2)
        y_mid_cheville = (np.ones(n) *
                          (self.raw.ankle_r_y + self.raw.ankle_l_y) / 2)

        t0 = Joint(x_mid_cheville, y_mid_cheville, 'translation vector'
                   )  #vector de translation vers l'origine du model

        self.P0 = Joint(x_mid_cheville, y_mid_cheville, 'P0') - t0

        self.ankle_l = Joint(self.raw.ankle_l, self.raw.ankle_l_y,
                             'ankle_l') - t0
        self.ankle_r = Joint(self.raw.ankle_r, self.raw.ankle_r_y,
                             'ankle_r') - t0

        self.c7 = Joint(self.raw["C7"], self.raw["C7_y"], "C7") - t0
        self.pelvis = Joint(self.raw["COM"], self.raw["COM_y"], "COM") - t0

        self.cof = Joint(self.raw["COF"], np.zeros(n), "COF") - t0
        self.cof_rel = CenterOfForce(self.raw["COF_REL"], None, "COF_REL")
        self.cof_rel.x_arr *= 2  # THIS CORRECTS THE ERROR IN COP_K_REL. the problem is in Unity, in the choplo project. gameManager line 295.

        self.hip_left = Joint(self.raw['HipLeft_y'], self.raw['HipLeft_z'],
                              'hip_l') - t0
        self.hip_right = Joint(self.raw['HipRight_y'], self.raw['HipRight_z'],
                               'hip_r') - t0
        self.left_leg = TotalLeg(self.hip_left, self.ankle_l, "left")
        self.right_leg = TotalLeg(self.hip_right, self.ankle_r, "right")
        self.hat = HAT(self.pelvis, self.c7)

        self.com = CenterOfMasse(
            "center_of_mass_legsANDhat",
            segments=[self.hat, self.left_leg, self.right_leg]).to_joint()
        self.ddot_com = Joint(self.cof.x_arr - self.com.x_arr,
                              np.zeros(len(self.raw)), "ddot_com")
Example #30
0
def get_joints_from_person_coords(coords_one_person_frame):

    coords_one_person_frame = coords_one_person_frame[[
        'frame_no_cam', 'person_id', 'joint_type', 'x_2D_joint', 'y_2D_joint',
        'x_3D_joint', 'y_3D_joint', 'z_3D_joint', 'joint_occluded',
        'joint_self_occluded', 'x_top_left_BB', 'y_top_left_BB',
        'x_bottom_right_BB', 'y_bottom_right_BB', 'x_2D_person', 'y_2D_person',
        'wears_glasses', 'ped_type'
    ]]
    person_joints = []
    for person_joint_coords in coords_one_person_frame.values.tolist():
        person_joint = Joint(person_joint_coords)
        person_joints.append(person_joint)

    return person_joints
Example #31
0
    def __init__(self, filename):

        self.name = None
        self.joints = None
        self.root = None
        self.units = None
        self.name2joint = {}

        self.root = Joint(-1, "root", [0, 0, 0], [0, 0, 0], 1, "rx ry rz")
        self.name2joint["root"] = self.root

        def __init_name(name):
            self.name = name

        def __init_units(units):
            self.units = units

        def __init_joints(joint_data):

            self.joints = [Joint.from_dict(entry) for entry in joint_data]
            for joint in self.joints:
                self.name2joint[joint.name] = joint

        def __init_root(root_data):
            self.root.direction = np.array(
                [float(i) for i in root_data["position"]])
            self.root.theta_degrees = np.array(
                [float(i) for i in root_data["orientation"]])

        def __init_hierarchy(hierarchy):
            for h in hierarchy:
                parent_name, dep_names = h
                for dep_name in dep_names:
                    self.name2joint[dep_name].parent = self.name2joint[
                        parent_name]

        reader = ASFReader(filename)
        reader.onName = __init_name
        reader.onUnits = __init_units
        reader.onRoot = __init_root
        reader.onBonedata = __init_joints
        reader.read()

        reader = ASFReader(filename)
        reader.onHierarchy = __init_hierarchy
        reader.read()
Example #32
0
 def __init__(self, leg_name, offset, servos):
     self.leg_name = leg_name
     if not path.exists("config/" + leg_name):
         makedirs(leg_name)
     
     self.offset = offset
     self.upper_hip = Joint(servos["upper_hip"], "config/" + leg_name + "/upper_hip.json")
     self.hip = Segment("config/" + leg_name + "/hip.json")
     self.lower_hip = Joint(servos["lower_hip"], "config/" + leg_name + "/lower_hip.json")
     self.femur = Segment("config/" + leg_name + "/femur.json")
     self.knee = Joint(servos["knee"], "config/" + leg_name + "/knee.json")
     self.tibia = Segment("config/" + leg_name + "/tibia.json")
Example #33
0
    def __readJoint(self, joint, scale=0.25):

        self.__expectKeyword('{')

        self.__calcPosition(joint, scale)

        items = self.__expectKeyword('CHANNELS')
        joint.channels = items[2:]
        joint.parseChannels(items[2:])

        if int(items[1]) != len(joint.channels):
            RuntimeError('Expected %d channels found %d' %
                         (items[1], len(joint.channels)))

        # Read child joints
        while 1:
            line = self.file.readline()
            items = line.split()

            if items[0] == 'JOINT':

                child = Joint(items[1])
                joint.children.append(child)
                child.parent = joint
                self.__readJoint(child, scale)

            elif items[0] == 'End':  # Site

                child = Joint('End effector')
                joint.children.append(child)
                child.channels = []
                child.parent = joint

                self.__expectKeyword('{')

                self.__calcPosition(child, scale)

                self.__expectKeyword('}')

            elif items[0] == '}':

                break

            else:

                raise RuntimeError('Expected %s found %s' %
                                   ('JOINT, End Site or }', items[0]))
Example #34
0
    def draw_left_lower_limp(self,
                             left_hip_transversal_radians=0,
                             left_hip_frontal_radians=0,
                             left_hip_lateral_radians=0,
                             left_knee_lateral_radians=0,
                             left_ankle_lateral_radians=0,
                             left_ankle_frontal_radians=0,
                             color='c-',
                             draw=True,
                             get_lines=False):

        left_hip_transversal = Joint(
            dh_params=(-half_pi + left_hip_transversal_radians, hip_length, 0,
                       -half_pi),
            initial_transformation=self._get_torso_corner_transformation(
                left_hip_top_position, 'x', -pi))

        hip_frontal = Joint(prev_joint=left_hip_transversal,
                            dh_params=(-half_pi - left_hip_frontal_radians, 0,
                                       0, -half_pi))
        hip_lateral = Joint(prev_joint=hip_frontal,
                            dh_params=(0 + left_hip_lateral_radians, 0,
                                       upper_leg_length, 0))

        knee_lateral = Joint(prev_joint=hip_lateral,
                             dh_params=(0 + left_knee_lateral_radians, 0,
                                        lower_leg_length, 0))

        ankle_lateral = Joint(prev_joint=knee_lateral,
                              dh_params=(0 - left_ankle_lateral_radians, 0, 0,
                                         half_pi))
        ankle_frontal = Joint(prev_joint=ankle_lateral,
                              dh_params=(half_pi + left_ankle_frontal_radians,
                                         0, 0, -half_pi))

        if draw or get_lines:
            leg_links = self.draw_link(left_hip_transversal, color),\
                        self.draw_link(hip_lateral, color),\
                        self.draw_link(knee_lateral, color)

        if get_lines:
            ankle_foot_links = self._draw_foot(ankle_t=ankle_frontal.link_t,
                                               color=color,
                                               draw=draw,
                                               get_lines=get_lines)
            return tuple(list(leg_links) + list(ankle_foot_links))
        else:
            foot_center = self._draw_foot(ankle_t=ankle_frontal.link_t,
                                          color=color,
                                          draw=draw)
            return left_hip_transversal, hip_frontal, hip_lateral, knee_lateral, ankle_lateral, ankle_frontal, foot_center
Example #35
0
def demo_2() -> World:
    world = World(gravity=GRAVITY, iterations=IMPULSE_ITERATIONS)

    body_1 = Body([100.0, 10.0])
    body_1.position = np.array([0.0, 0.5 * body_1.width[1]])
    body_1.friction = 0.2
    body_1.rotation = 0.0
    world.add_body(body_1)

    body_2 = Body([5.0, 5.0], 100.0)
    body_2.position = np.array([45.0, 60.0])
    body_2.friction = 0.2
    body_2.rotation = 0.0
    world.add_body(body_2)

    joint = Joint(body_1, body_2, body_2.position * [0, 1])
    world.add_joint(joint)

    return world
Example #36
0
    def onHierarchy(self, links):
        # At the end, this list contains the leaves which need
        # a dummy joint at the end.
        leaves = []
        for parentname, childnames in links:
            leaves += childnames
            if parentname in leaves:
                leaves.remove(parentname)
            # Create the second joint of the bone called parentname
            # (which is the first joint of the bone called data["name"])
            parent = self.joints[parentname]
            data = self.bones[parentname]
            dir = data["direction"].normalize()
            length = data["length"]
            for childname in childnames:
                data = self.bones[childname]
                axis = data["axis"]
                ao = data["axis_order"]
                axis_order = ao[2] + ao[1] + ao[0]
                j = Joint(name=data["name"],
                          rotationorder=axis_order,
                          radius=0.3,
                          pos=length * dir.normalize(),
                          parent=parent)
                exec "fromEuler = mat3.fromEuler%s" % axis_order.upper()
                R = fromEuler(radians(axis.x), radians(axis.y),
                              radians(axis.z))
                j.setOffsetTransform(mat4(1).setMat3(R))
                j.freezePivot()
                self.joints[j.name] = j

        # Create end joints
        for name in leaves:
            parent = self.joints[name]
            data = self.bones[name]
            try:
                dir = data["direction"].normalize()
            except:
                dir = vec3(0)
            length = data["length"]
            Joint(name=name + "_end",
                  rotationorder="xyz",
                  radius=0.3,
                  pos=length * dir,
                  parent=parent)
Example #37
0
def make_hand():
    def make_finger(nameSuffix, mat, L2, L3, L4):
        i = str(nameSuffix)
        return JointDOF2('MCP'+i, mat, (-Pi/9, Pi/9), (-Pi/2, 0), [
            Joint('PIP'+i, Joint.make_mat((L2, 0, 0), -Pi/6), (-Pi/2, 0), [
                Joint('DIP'+i, Joint.make_mat((L3, 0, 0), -Pi/6), (-Pi/2, 0), [
                    Joint('EP'+i, Joint.make_mat((L3, 0, 0), -Pi/6), None, [])
                ])
            ])
        ])
    # All lengths are in meters
    poss = [(), 
            (L1 * scales[1], 0, HB/2),
            (L1 * scales[2], 0, HB/6),
            (L1 * scales[3], 0, -HB/6),
            (L1 * scales[4], 0, -HB/2),
            ]
    hand = JointDOF3('W', np.array([
        # wrist matrix
            [1, 0, 0, Larm],
            [0, 1, 0, 0],
            [0, 0, 1, 0],
            [0, 0, 0, 1]]), 
            None, None, None, [
            make_finger(i, Joint.make_mat(poss[i], 0.),
                L2 * scales[i], L3 * scales[i], L4 * scales[i])
            for i in range(1, 5)
        ])

    arm = JointDOF3('ARM', np.array([
            [0, 0, -1, .04 - config.x0],
            [1, 0, 0, .03 - config.y0 - Larm],
            [0, -1, 0, -config.z0],
            [0, 0, 0, 1],
        ]), None, None, None, [hand])

    root = arm
    return root
def nn_by_img(dataset_id):
    joint = Joint()
    joint.load_transformed_data()
    joint.pca_fit(30)
    joint.load_labels()
    joint.img_nearest_neighbor(dataset_id, 30)
def plot_img_data(dataset_idx):
    joint = Joint()
    joint.load_transformed_data()
    joint.load_labels()
    joint.plot_img_data(dataset_idx)
def nn_by_tag(search_tag):
    joint = Joint()
    joint.load_transformed_data()
    joint.pca_fit(30)
    joint.load_labels()
    joint.tag_nearest_neighbor(search_tag, 30)
def plot_tag_img_pairs(search_tag):
    joint = Joint()
    joint.load_transformed_data()
    joint.load_labels()
    joint.plot_tag_img_pairs(search_tag, 30)
def plot_tag_data(search_tag):
    joint = Joint()
    joint.load_transformed_data()
    joint.load_labels()
    joint.plot_tag_data(search_tag)
Example #43
0
from beta import Beta
from joint import Joint

value1 = Beta(0.5, 0.5)
value2 = Beta(2.0, 5.0)

joint_sum = Joint(value1, value2, "Sum")
joint_quotient = Joint(value1, value2, "Quotient")
joint_product = Joint(value1, value2, "Product")
joint_quadro_sum = Joint(value1, value2, "QuadroSum")
joint_min = Joint(value1, value2, "Min")
joint_max = Joint(value1, value2, "Max")

print("BETA VALUE 1", value1.mean, value1.variance, value1.pdf(0.5), value1.cdf(0.5))
print("BETA VALUE 2", value2.mean, value2.variance, value2.pdf(0.5), value2.cdf(0.5))

print("JOINT SUM", joint_sum.mean, joint_sum.variance, joint_sum.pdf(0.5), joint_sum.cdf(0.5))
print("JOINT QUOTIENT", joint_quotient.mean, joint_quotient.variance, joint_quotient.pdf(0.5), joint_quotient.cdf(0.5))
print("JOINT PRODUCT", joint_product.mean, joint_product.variance, joint_product.pdf(0.5), joint_product.cdf(0.5))
print(
    "JOINT QUADRO SUM",
    joint_quadro_sum.mean,
    joint_quadro_sum.variance,
    joint_quadro_sum.pdf(0.5),
    joint_quadro_sum.cdf(0.5),
)
print("JOINT MIN", joint_min.mean, joint_min.variance, joint_min.pdf(0.5), joint_min.cdf(0.5))
print("JOINT MAX", joint_max.mean, joint_max.variance, joint_max.pdf(0.5), joint_max.cdf(0.5))

joint_sum.show("pdf")
# joint_quotient.show("pdf")
def learn_word2vec_model_from_wiki_corpus():
    joint = Joint()
    joint.learn_wiki_corpus()
def print_corrcoef():
    joint = Joint()
    joint.load_transformed_data()
    joint.print_corrcoef()
from joint import Joint

if __name__=="__main__":
    logging.root.setLevel(level=logging.INFO)


    english_corpus_dir = '../PascalSentenceDataset/english/'
    japanese_corpus_dir = '../PascalSentenceDataset/line_wakati/'
    japanese_original_corpus_dir = '../PascalSentenceDataset/japanese/'
    img_features_npy = 'pascal_features.npy'
    img_original_dir = '../PascalSentenceDataset/dataset/'
    img_correspondence_path = "../PascalSentenceDataset/correspondence.csv"
    joint = Joint(
        english_corpus_dir,
        img_features_npy,
        japanese_corpus_dir,
        img_original_dir,
        img_correspondence_path,
        japanese_original_corpus_dir
    )

    # retrieval
    joint.create_features()
    joint.pca_train_and_test_data()
    joint.cca_transform(line_flag=False, step=1, reg_param=0.1)
    joint.cca_plot()
    joint.gcca_transform(line_flag=False, step=1, reg_param=0.1)
    joint.gcca_plot()

    # joint.retrieval_j2e_by_cca(3)
    joint.retrieval_j2e_by_gcca(3)
    # joint.retrieval_j2i_by_gcca(3)
Example #47
0
from beta import Beta
from joint import Joint

value1 = Beta(1.0, 5.0)
value2 = Beta(5.0, 3.0)

joint_sum = Joint(value1, value2, "Sum")
joint_quotient = Joint(value1, value2, "Quotient")
joint_product = Joint(value1, value2, "Product")
joint_quadro_sum = Joint(value1, value2, "QuadroSum")
joint_min = Joint(value1, value2, "Min")
joint_max = Joint(value1, value2, "Max")

print("BETA VALUE 1", value1.mean, value1.variance, value1.pdf(0.5), value1.cdf(0.5), value1.norm)
print("BETA VALUE 2", value2.mean, value2.variance, value2.pdf(0.5), value2.cdf(0.5), value2.norm)

# print ("JOINT SUM", joint_sum.mean, joint_sum.variance, joint_sum.pdf(0.5), joint_sum.cdf(0.5))
print("JOINT SUM", joint_sum.mean, joint_sum.variance, joint_sum.pdf(0.5), joint_sum.cdf(0.5), joint_sum.norm)
print(
    "JOINT QUOTIENT",
    joint_quotient.mean,
    joint_quotient.variance,
    joint_quotient.pdf(0.5),
    joint_quotient.cdf(0.5),
    joint_quotient.norm,
)
print(
    "JOINT PRODUCT",
    joint_product.mean,
    joint_product.variance,
    joint_product.pdf(0.5),
def create_word_feature():
    joint = Joint()
    joint.create_word_feature_matrix()
def create_tag_list():
    joint = Joint()
    joint.create_tag_list()
def plot_images_by_tag(search_tag):
    joint = Joint()
    joint.plot_img_by_tag(search_tag)
def plot_image_in_plot(img_id):
    joint = Joint()
    joint.plot_img_in_plot(img_id)
def plot_cca_result():
    joint = Joint()
    joint.load_transformed_data()
    joint.plot_transformed_data()
def create_image_feature():
    joint = Joint()
    joint.create_image_feature_matrix()
def create_labels():
    joint = Joint()
    joint.create_labels()
def fit_by_cca():
    joint = Joint()
    joint.fit_data_by_cca()
def transform_cca():
    joint = Joint()
    joint.transform_data()
Example #57
0
File: test.py Project: mhespenh/eva
#!/usr/bin/python

from joint import Joint

j = Joint(name='Pinkie', controller_addr=0x40,
          servo_id=5, usec_max=2200, usec_min=800)
j.set_angle(50)
j.shutdown()
class Experiment:

    PCA_COMPRESS_WORD_DIM = 100
    PCA_COMPRESS_IMG_DIM = 100
    SEED_NUM = None

    MAX_DIM = 300
    MIN_DIM = 10
    DIM_STEP = 10

    CONFIG_YAML = 'config.yml'

    def __init__(self, line_flag=False):

        # log setting
        program = os.path.basename(__name__)
        self.logger = logging.getLogger(program)
        logging.basicConfig(format='%(asctime)s : %(name)s : %(levelname)s : %(message)s')

        # load config file
        f = open(Experiment.CONFIG_YAML, 'r')
        self.config = yaml.load(f)
        f.close()

        self.english_corpus_dir = self.config['english_corpus_dir']
        self.japanese_corpus_dir = self.config['japanese_corpus_dir']
        self.japanese_original_corpus_dir = self.config['japanese_original_corpus_dir']
        self.img_features_npy = self.config['img_features_npy']
        self.img_original_dir = self.config['img_original_dir']
        self.img_correspondence_path = self.config['img_correspondence_path']

        self.joint = Joint(
            self.english_corpus_dir,
            self.img_features_npy,
            self.japanese_corpus_dir,
            self.img_original_dir,
            self.img_correspondence_path,
            self.japanese_original_corpus_dir,
            Experiment.PCA_COMPRESS_WORD_DIM,
            Experiment.PCA_COMPRESS_IMG_DIM,
            line_flag
        )
        self.logger.info("<Initilalizing Experiment>")
        if Experiment.SEED_NUM is not None:
            self.logger.info("seed: %s" , Experiment.SEED_NUM)
            np.random.seed(Experiment.SEED_NUM)

    def process_features(self):
        self.joint.create_features()
        self.joint.pca_train_and_test_data()

    def fit_changing_sample_num(self, sample_num_list):
        data_num = self.joint.english_feature.get_train_data_num()
        for s in sample_num_list:
            sampled_indices = feat.BaseFeature.sample_indices(data_num, s)
            self.joint.gcca_fit(s, 0.1, sampled_indices)
            self.joint.cca_fit(s, 0.1, sampled_indices)

    def calc_accuracy(self, start_dim=1, end_dim=100, dim_step=1):
        res_cca_list = []
        res_gcca_list = []

        print "|dim|CCA|GCCA|"
        for i in xrange(start_dim, end_dim, dim_step):
            res_cca = self.cca_calc_search_precision(i)
            res_gcca = self.gcca_calc_search_precision(i)
            print "|%d|%f|%f|" % (i, res_cca, res_gcca)
            res_cca_list.append(res_cca)
            res_gcca_list.append(res_gcca)

        return res_cca_list, res_gcca_list

    def plot_result(self, sample_num=500, reg_param=0.1):
        self.joint.gcca_transform(sample_num, reg_param)
        self.joint.cca_transform(sample_num, reg_param)
        self.joint.cca_plot()
        self.joint.gcca_plot()

    def calc_accuracy_changing_sample_num(self, sample_num_list, reg_param=0.1):

        res_cca_data = []
        res_gcca_data = []

        for sample_num in sample_num_list:
            self.joint.gcca_transform(sample_num, reg_param)
            self.joint.cca_transform(sample_num, reg_param)

            res_cca_list, res_gcca_list = self.calc_accuracy(Experiment.MIN_DIM, Experiment.MAX_DIM + 1, Experiment.DIM_STEP)
            res_cca_data.append(res_cca_list)
            res_gcca_data.append(res_gcca_list)

        res_cca_arr = np.array(res_cca_data)
        res_gcca_arr = np.array(res_gcca_data)
        # np.save('output/results/res_cca_arr.npy', res_cca_arr)
        # np.save('output/results/res_gcca_arr.npy', res_gcca_arr)

        # joint.gcca_transform(mode='PART', line_flag=True, step=5)
        # res_cca_arr = np.load('output/results/res_cca_arr.npy')
        # res_gcca_arr = np.load('output/results/res_gcca_arr.npy')

    def fit_chenging_regparam(self, reg_params, sample_num=500):
        data_num = self.joint.english_feature.get_train_data_num()
        for r in reg_params:
            sampled_indices = feat.BaseFeature.sample_indices(data_num, sample_num)
            self.joint.gcca_fit(sample_num, r, sampled_indices)
            self.joint.cca_fit(sample_num, r, sampled_indices)

    def calc_accuracy_changing_reg_params(self, sample_num, reg_list, col_num=5):

        res_cca_data = []
        res_gcca_data = []

        for reg in reg_list:
            self.joint.gcca_transform(sample_num,reg)
            self.joint.cca_transform(sample_num, reg)

            res_cca_list, res_gcca_list = self.calc_accuracy(Experiment.MIN_DIM, Experiment.MAX_DIM + 1 , Experiment.DIM_STEP)
            res_cca_data.append(res_cca_list)
            res_gcca_data.append(res_gcca_list)

        res_cca_arr = np.array(res_cca_data)
        res_gcca_arr = np.array(res_gcca_data)
        np.save('output/results/res_cca_reg_arr.npy', res_cca_arr)
        np.save('output/results/res_gcca_reg_arr.npy', res_gcca_arr)

        # joint.gcca_transform(line_flag=True, step=5)
        # res_cca_arr = np.load('output/results/res_cca_reg_arr.npy')
        # res_gcca_arr = np.load('output/results/res_gcca_reg_arr.npy')
        self.plot_results(res_cca_arr, res_gcca_arr, reg_list, col_num, 'REG')

    def plot_original_data(self):
        self.joint.plot_original_data()

    def cca_calc_search_precision(self, min_dim, neighbor_num=1):

        en_mat, jp_mat = self.joint.cca.z_list[0][:, :min_dim], self.joint.cca.z_list[1][:, :min_dim]
        nn = NearestNeighbors(n_neighbors=2, algorithm='ball_tree').fit(en_mat)
        dists, nn_indices = nn.kneighbors(jp_mat, neighbor_num, return_distance=True)
        hit_count = 0
        for j_idx, nn_indices_row in enumerate(nn_indices):
            # print nn_indices_row
            if j_idx in nn_indices_row:
                # print True
                hit_count += 1
            else:
                pass
                # print False
        return float(hit_count) / len(nn_indices) * 100

    def gcca_calc_search_precision(self, min_dim, neighbor_num=1):

        en_mat, im_mat, jp_mat = self.joint.gcca.z_list[0][:, :min_dim], self.joint.gcca.z_list[1][:, :min_dim], self.joint.gcca.z_list[2][:, :min_dim]
        nn = NearestNeighbors(n_neighbors=2, algorithm='ball_tree').fit(en_mat)
        dists, nn_indices = nn.kneighbors(jp_mat, neighbor_num, return_distance=True)
        hit_count = 0
        for j_idx, nn_indices_row in enumerate(nn_indices):
            # print nn_indices_row
            if j_idx in nn_indices_row:
                # print True
                hit_count += 1
            else:
                # print False
                pass
        return float(hit_count) / len(nn_indices) * 100

    def plot_results(self, res_cca, res_gcca, title_list, col_num=2, mode='SAMPLE'):

        data_num = len(res_cca)
        row_num = data_num / col_num
        if row_num - float(data_num)/col_num != 0:
            print row_num
            row_num = row_num + 1

        fig = plt.figure()
        # plt.title('Accuracy')
        for i, (title, row_cca, row_gcca) in enumerate(zip(title_list, res_cca, res_gcca)):

            plt.subplot(row_num , col_num, i + 1)
            plt.plot(np.arange(len(row_cca)) * 10 + 10, row_cca, '-r')
            plt.plot(np.arange(len(row_gcca)) * 10 + 10, row_gcca, '-b')
            x_min, x_max = plt.gca().get_xlim()
            y_min, y_max = plt.gca().get_ylim()
            if mode == 'SAMPLE':
                plt.text(0.5 * (x_min + x_max), 0.5 * (y_min + y_max), 'sample:%d' % title, ha='center', va='center', color='gray')
            elif mode == 'REG':
                plt.text(0.5 * (x_min + x_max), 0.5 * (y_min + y_max), 'reg:%s' % title, ha='center', va='center', color='gray')
        plt.tight_layout()
        plt.show()