Converts position coordinates of trajectory into displacements between consecutive frames
772552
def to_displacements(self):
        
        if not self.coords_are_displacement:
            displacements = np.subtract(self.frac_coords, np.roll(self.frac_coords, 1, axis=0))
            displacements[0] = np.zeros(np.shape(self.frac_coords[0]))
            # Deal with PBC
            displacements = [np.subtract(item, np.round(item)) for item in displacements]

            self.frac_coords = displacements
            self.coords_are_displacement = True
        return
253326
def export_frame_coordinates(topology, trajectory, nframe, output=None):
    
    if output is None:
        basename, ext = os.path.splitext(trajectory)
        output = '{}.frame{}.inpcrd'.format(basename, nframe)

    # ParmEd sometimes struggles with certain PRMTOP files
    if os.path.splitext(topology)[1] in ('.top', '.prmtop'):
        top = AmberPrmtopFile(topology)
        mdtop = mdtraj.Topology.from_openmm(top.topology)
        traj = mdtraj.load_frame(trajectory, int(nframe), top=mdtop)
        structure = parmed.openmm.load_topology(top.topology, system=top.createSystem())
        structure.box_vectors = top.topology.getPeriodicBoxVectors()

    else:  # standard protocol (the topology is loaded twice, though)
        traj = mdtraj.load_frame(trajectory, int(nframe), top=topology)
        structure = parmed.load_file(topology)

    structure.positions = traj.openmm_positions(0)

    if traj.unitcell_vectors is not None:  # if frame provides box vectors, use those
        structure.box_vectors = traj.openmm_boxes(0)

    structure.save(output, overwrite=True)
206766
def tran(inimage,outimage,direction='forward',x=None,y=None,
        coords=None, coordfile=None,colnames=None,separator=None,
        precision=6, output=None,verbose=True):
    
    single_coord = False

    # Only use value provided in `coords` if nothing has been specified for coordfile
    if coords is not None and coordfile is None:
        coordfile = coords
        warnings.simplefilter('always',DeprecationWarning)
        warnings.warn("Please update calling code to pass in `coordfile` instead of `coords`.",
            category=DeprecationWarning)
        warnings.simplefilter('default',DeprecationWarning)

    if coordfile is not None:
        if colnames in util.blank_list:
            colnames = ['c1','c2']
        # Determine columns which contain pixel positions
        cols = util.parse_colnames(colnames,coordfile)
        # read in columns from input coordinates file
        xyvals = np.loadtxt(coordfile,usecols=cols,delimiter=separator)
        if xyvals.ndim == 1: # only 1 entry in coordfile
            xlist = [xyvals[0].copy()]
            ylist = [xyvals[1].copy()]
        else:
            xlist = xyvals[:,0].copy()
            ylist = xyvals[:,1].copy()
        del xyvals
    else:
        if isinstance(x,np.ndarray):
            xlist = x.tolist()
            ylist = y.tolist()
        elif not isinstance(x,list):
            xlist = [x]
            ylist = [y]
            single_coord = True
        else:
            xlist = x
            ylist = y

    # start by reading in WCS+distortion info for each image
    im1wcs = wcsutil.HSTWCS(inimage)
    if im1wcs.wcs.is_unity():
        print("####\nNo valid input WCS found in {}.\n  Results may be invalid.\n####\n".format(inimage))

    if util.is_blank(outimage):
        fname,fextn = fileutil.parseFilename(inimage)
        numsci = fileutil.countExtn(fname)
        chips = []
        for e in range(1,numsci+1):
            chips.append(wcsutil.HSTWCS(fname,ext=('sci',e)))
        if len(chips) == 0:
            chips = [im1wcs]
        im2wcs = distortion.utils.output_wcs(chips)
    else:
        im2wcs = wcsutil.HSTWCS(outimage)

    if im2wcs.wcs.is_unity():
        print("####\nNo valid output WCS found in {}.\n  Results may be invalid.\n####\n".format(outimage))

    # Setup the transformation
    p2p = wcs_functions.WCSMap(im1wcs,im2wcs)

    if direction[0].lower() == 'f':
        outx,outy = p2p.forward(xlist,ylist)
    else:
        outx,outy = p2p.backward(xlist,ylist)

    if isinstance(outx,np.ndarray):
        outx = outx.tolist()
        outy = outy.tolist()

    # add formatting based on precision here...
    xstr = []
    ystr = []
    fmt = "%."+repr(precision)+"f"
    for ox,oy in zip(outx,outy):
        xstr.append(fmt%ox)
        ystr.append(fmt%oy)

    if verbose or (not verbose and util.is_blank(output)):
        print('# Coordinate transformations for ',inimage)
        print('# X(in)      Y(in)             X(out)         Y(out)\n')
        for xs,ys,a,b in zip(xlist,ylist,xstr,ystr):
            print("%.4f  %.4f    %s  %s"%(xs,ys,a,b))

    # Create output file, if specified
    if output:
        f = open(output,mode='w')
        f.write("# Coordinates converted from %s\n"%inimage)
        for xs,ys in zip(xstr,ystr):
            f.write('%s    %s\n'%(xs,ys))
        f.close()
        print('Wrote out results to: ',output)

    if single_coord:
        outx = outx[0]
        outy = outy[0]
    return outx,outy
973820
def transform_frame(frame, transform, columns=None, direction='forward',
                    return_all=True, args=(), **kwargs):
    
    tfun, tname = parse_transform(transform, direction)
    columns = to_list(columns)
    if columns is None:
        columns = frame.columns
    if return_all:
        transformed = frame.copy()
        for c in columns:
            transformed[c] = tfun(frame[c], *args, **kwargs)
    else:
        transformed = frame.filter(columns).apply(tfun, *args, **kwargs)
    return transformed
1271806
def rectify(self, frames):
        
        new_frames = []
        for i, side in enumerate(("left", "right")):
            new_frames.append(cv2.remap(frames[i],
                                        self.undistortion_map[side],
                                        self.rectification_map[side],
                                        cv2.INTER_NEAREST))
        return new_frames
734830
def _original_frame(self, x, y):
        
        if self._inverted:
            return self.obs.naxis1 - x, self.obs.naxis2 - y
        return x, y
1164921
def load_trajectory(name, skip=1, format=None):
    '''

    '''
    df = datafile(name, format=format)
    dt, coords = df.read('trajectory', skip=skip)
    boxes = df.read('boxes')
    viewer.current_traj = coords
    viewer.frame_times = dt
    
    viewer.traj_controls.set_ticks(len(dt))
    
    def update(index):
        
        f = coords[index]        
        
        for fp in _frame_processors:
            f = fp(coords, index)

        # update the current representation
        viewer.representation.update_positions(f)
        viewer.representation.update_box(boxes[index])
        current_system().r_array = f
        current_system().box_vectors = boxes[index]
        viewer.traj_controls.set_time(dt[index])
        viewer.update()
    
    viewer.traj_controls.show()
    viewer.traj_controls.frame_changed.connect(update)
253924
def itertrajs(meta, stride=1):
    

    tops = preload_tops(meta)
    for i, row in meta.iterrows():
        yield i, md.join(md.iterload(row['traj_fn'],
                                     top=tops[row['top_fn']],
                                     stride=stride),
                         discard_overlapping_frames=False,
                         check_topology=False)
1326411
def staggered_positions(n_channels):
    """"""
    i = np.arange(n_channels - 1)
    x, y = (-1) ** i * (5 + i), 10 * (i + 1)
    pos = np.flipud(np.r_[np.zeros((1, 2)), np.c_[x, y]])
    return pos
1337381
def do_keyframes_overlap(self):
        """"""
        skl = self.sorted_key_list()
        for i in range(len(skl)-1):
            this_time = self.dct[skl[i]]['__abs_time__']
            next_time = self.dct[skl[i+1]]['__abs_time__']
            if abs(next_time-this_time) < 1e-6:
                # key frame times overlap
                return skl[i]
        # Return None if all passed
        return None
291984
def odometry2Pose3D(odom):
    '''
    

    '''
    pose = Pose3d()
    ori = odom.pose.pose.orientation

    pose.x = odom.pose.pose.position.x
    pose.y = odom.pose.pose.position.y
    pose.z = odom.pose.pose.position.z
    #pose.h = odom.pose.pose.position.h
    pose.yaw = quat2Yaw(ori.w, ori.x, ori.y, ori.z)
    pose.pitch = quat2Pitch(ori.w, ori.x, ori.y, ori.z)
    pose.roll = quat2Roll(ori.w, ori.x, ori.y, ori.z)
    pose.q = [ori.w, ori.x, ori.y, ori.z]
    pose.timeStamp = odom.header.stamp.secs + (odom.header.stamp.nsecs *1e-9)

    return pose
205235
def _left_motion(self, event):
        """"""
        iid = self.current_iid
        if iid is None:
            return
        marker = self._markers[iid]
        if marker["move"] is False:
            return
        delta = marker["finish"] - marker["start"]
        # Limit x to 0
        x = max(self._timeline.canvasx(event.x), 0)
        # Check if the timeline needs to be extended
        limit = self.get_time_position(self._finish - delta)
        if self._extend is False:
            x = min(x, limit)
        elif x > limit:  # self._extend is True
            self.configure(finish=(self.get_position_time(x) + (marker["finish"] - marker["start"])) * 1.1)
        # Get the new start value
        start = self.get_position_time(x)
        finish = start + (marker["finish"] - marker["start"])
        rectangle_id, text_id = marker["rectangle_id"], marker["text_id"]
        if rectangle_id not in self._timeline.find_all():
            return
        x1, y1, x2, y2 = self._timeline.coords(rectangle_id)
        # Overlap protection
        allow_overlap = marker["allow_overlap"]
        allow_overlap = self._marker_allow_overlap if allow_overlap == "default" else allow_overlap
        if allow_overlap is False:
            for marker_dict in self.markers.values():
                if marker_dict["allow_overlap"] is True:
                    continue
                if marker["iid"] != marker_dict["iid"] and marker["category"] == marker_dict["category"]:
                    if marker_dict["start"] < start < marker_dict["finish"]:
                        start = marker_dict["finish"] if start < marker_dict["finish"] else marker_dict["start"]
                        finish = start + (marker["finish"] - marker["start"])
                        x = self.get_time_position(start)
                        break
                    if marker_dict["start"] < finish < marker_dict["finish"]:
                        finish = marker_dict["finish"] if finish > marker_dict["finish"] else marker_dict["start"]
                        start = finish - (marker_dict["finish"] - marker_dict["start"])
                        x = self.get_time_position(start)
                        break
        # Vertical movement
        if marker["change_category"] is True or \
                (marker["change_category"] == "default" and self._marker_change_category):
            y = max(self._timeline.canvasy(event.y), 0)
            category = min(self._rows.keys(), key=lambda category: abs(self._rows[category][0] - y))
            marker["category"] = category
            y1, y2 = self._rows[category]
        # Snapping to ticks
        if marker["snap_to_ticks"] is True or (marker["snap_to_ticks"] == "default" and self._marker_snap_to_ticks):
            # Start is prioritized over finish
            for tick in self._ticks:
                tick = self.get_time_position(tick)
                # Start
                if abs(x - tick) < self._snap_margin:
                    x = tick
                    break
                # Finish
                x_finish = x + delta
                if abs(x_finish - tick) < self._snap_margin:
                    delta = self.get_time_position(marker["finish"] - marker["start"])
                    x = tick - delta
                    break
        rectangle_coords = (x, y1, x2 + (x - x1), y2)
        self._timeline.coords(rectangle_id, *rectangle_coords)
        if text_id is not None:
            text_x, text_y = TimeLine.calculate_text_coords(rectangle_coords)
            self._timeline.coords(text_id, text_x, text_y)
        if self._after_id is not None:
            self.after_cancel(self._after_id)
        args = (iid, (marker["start"], marker["finish"]), (start, finish))
        self._after_id = self.after(10, self._after_handler(iid, "move_callback", args))
        marker["start"] = start
        marker["finish"] = finish
683261
def smooth_location_by_average(opts = {})
      seconds_either_side = opts[:averaging_window] || 20

      # calculate the first and last points to which the smoothing should be applied
      earliest = (find_point_by_time_or_offset(opts[:start]) || @earliest_point).time
      latest = (find_point_by_time_or_offset(opts[:end]) || @latest_point).time

      tmp_points = []

      @points.each do |point|
        if point.time > latest || point.time < earliest
          tmp_points.push point # add the point unaltered
          next
        end
        lat_av = 0.to_f
        lon_av = 0.to_f
        alt_av = 0.to_f
        n = 0
        # k ranges from the time of the current point +/- 20s
        (-1 * seconds_either_side..seconds_either_side).each do |k|
          # find the point nearest to the time offset indicated by k
          contributing_point = closest_point(point.time + k)
          # sum up the contributions to the average
          lat_av += contributing_point.lat
          lon_av += contributing_point.lon
          alt_av += contributing_point.elevation
          n += 1
        end
        # calculate the averages
        tmp_point = point.clone
        tmp_point.lon = (lon_av / n).round(7)
        tmp_point.elevation = (alt_av / n).round(2)
        tmp_point.lat = (lat_av / n).round(7)
        tmp_points.push tmp_point
      end
      @points.clear
      reset_meta_data
      # now commit the averages back and recalculate the distances
      tmp_points.each do |point|
        append_point(point)
      end
    end
959376
def lorenz_animation(N_trajectories=20, rseed=1, frames=200, interval=30):
    """"""
    from scipy import integrate
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib.colors import cnames

    def lorentz_deriv(coords, t0, sigma=10., beta=8./3, rho=28.0):
        """Compute the time-derivative of a Lorentz system."""
        x, y, z = coords
        return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]

    # Choose random starting points, uniformly distributed from -15 to 15
    np.random.seed(rseed)
    x0 = -15 + 30 * np.random.random((N_trajectories, 3))

    # Solve for the trajectories
    t = np.linspace(0, 2, 500)
    x_t = np.asarray([integrate.odeint(lorentz_deriv, x0i, t)
                      for x0i in x0])

    # Set up figure & 3D axis for animation
    fig = plt.figure()
    ax = fig.add_axes([0, 0, 1, 1], projection='3d')
    ax.axis('off')

    # choose a different color for each trajectory
    colors = plt.cm.jet(np.linspace(0, 1, N_trajectories))

    # set up lines and points
    lines = sum([ax.plot([], [], [], '-', c=c)
                 for c in colors], [])
    pts = sum([ax.plot([], [], [], 'o', c=c, ms=4)
               for c in colors], [])

    # prepare the axes limits
    ax.set_xlim((-25, 25))
    ax.set_ylim((-35, 35))
    ax.set_zlim((5, 55))

    # set point-of-view: specified by (altitude degrees, azimuth degrees)
    ax.view_init(30, 0)

    # initialization function: plot the background of each frame
    def init():
        for line, pt in zip(lines, pts):
            line.set_data([], [])
            line.set_3d_properties([])

            pt.set_data([], [])
            pt.set_3d_properties([])
        return lines + pts

    # animation function: called sequentially
    def animate(i):
        # we'll step two time-steps per frame.  This leads to nice results.
        i = (2 * i) % x_t.shape[1]

        for line, pt, xi in zip(lines, pts, x_t):
            x, y, z = xi[:i + 1].T
            line.set_data(x, y)
            line.set_3d_properties(z)

            pt.set_data(x[-1:], y[-1:])
            pt.set_3d_properties(z[-1:])

        ax.view_init(30, 0.3 * i)
        fig.canvas.draw()
        return lines + pts

    return animation.FuncAnimation(fig, animate, init_func=init,
                                   frames=frames, interval=interval)
474829
function (start, end, pos, complete) {
		var ret = [],
			i = start.length,
			startVal;

		if (pos === 1) { // land on the final path without adjustment points appended in the ends
			ret = complete;

		} else if (i === end.length && pos < 1) {
			while (i--) {
				startVal = parseFloat(start[i]);
				ret[i] =
					isNaN(startVal) ? // a letter instruction like M or L
						start[i] :
						pos * (parseFloat(end[i] - startVal)) + startVal;

			}
		} else { // if animation is finished or length not matching, land on right value
			ret = end;
		}
		return ret;
	}
1074064
function () {
            var i,
                len = trackerPoints.length,
                trackPoint,
                gPoint,
                now = $.now(),
                elapsedTime,
                distance,
                speed;

            elapsedTime = now - lastTime;
            lastTime = now;

            for ( i = 0; i < len; i++ ) {
                trackPoint = trackerPoints[ i ];
                gPoint = trackPoint.gPoint;
                // Math.atan2 gives us just what we need for a velocity vector, as we can simply
                //   use cos()/sin() to extract the x/y velocity components.
                gPoint.direction = Math.atan2( gPoint.currentPos.y - trackPoint.lastPos.y, gPoint.currentPos.x - trackPoint.lastPos.x );
                // speed = distance / elapsed time
                distance = trackPoint.lastPos.distanceTo( gPoint.currentPos );
                trackPoint.lastPos = gPoint.currentPos;
                speed = 1000 * distance / ( elapsedTime + 1 );
                // Simple biased average, favors the most recent speed computation. Smooths out erratic gestures a bit.
                gPoint.speed = 0.75 * speed + 0.25 * gPoint.speed;
            }
        }
339768
def getouterframes(frame, context=1):
    """"""
    framelist = []
    while frame:
        framelist.append((frame,) + getframeinfo(frame, context))
        frame = frame.f_back
    return framelist