예제 #1
0
 def dot_plan(self, t_step):
     return torch.from_numpy(
         np.hstack([
             spalde(t_step, self._x_spl)[0],
             spalde(t_step, self._y_spl)[0],
             spalde(t_step, self._yaw_spl)[0]
         ])).to(device=getattr(self.x0, 'device', None),
                dtype=self.x0.dtype)
예제 #2
0
 def getNormal(self, point):
     best = self.controlpoints[0]
     spot = 0
     for i in np.linspace(0, 1, 50):
         sa = spalde(float(i), self.tck)
         new = (sa[0][0], sa[1][0])
         if euclidean(point, new) < euclidean(point, best):
             best = new
             spot = i
     
     sa = spalde(float(spot), self.tck)
     dvector = np.array([sa[0][1], sa[1][1]])
     normal = normalizeVector(rotateVector(dvector, angle=.5*pi))
     return normal
예제 #3
0
def make_spline(points, config):
    # TODO: periodic in new version
    # tck, u = splprep([points[0, :], points[1, :]], k=3, s=points.shape[1] * config['s_factor'], per=1)
    points[1, :] *= -1.
    tck, u = splprep([points[0, :], points[1, :]],
                     k=3,
                     s=points.shape[1] * config['s_factor'],
                     per=1)
    spline_size = (points.shape[1] - 1) * config['interp_factor']
    # make a u vector that has much more values for interpolation
    new_u = np.arange(spline_size)
    new_u = new_u / float(spline_size - 1)

    # evaluate spline, out is Nx2
    spline = np.asarray(splev(new_u, tck)).T

    # get thetas
    derivs = spalde(new_u, tck)
    Dx = np.asarray(derivs[0])
    Dy = np.asarray(derivs[1])
    dx = Dx[:, 1]
    dy = Dy[:, 1]
    ddx = Dx[:, 2]
    ddy = Dy[:, 2]
    curvature = (dx * ddy - dy * ddx) / ((dx * dx + dy * dy)**1.5)
    theta = np.arctan2(dy, dx)

    return spline, theta, curvature
예제 #4
0
def main():
    args = get_argparser().parse_args()
    init_logger(args)
    dev = Client(args.server, args.port, "pdq2")

    freq = dev.get_freq()
    times = np.around(eval(args.times, globals(), {}) * freq)
    voltages = eval(args.voltages, globals(), dict(t=times / freq))

    dt = np.diff(times.astype(np.int))
    if args.order:
        tck = interpolate.splrep(times, voltages, k=args.order, s=0)
        u = interpolate.spalde(times, tck)
    else:
        u = voltages[:, None]
    segment = []
    for dti, ui in zip(dt, u):
        segment.append({
            "duration":
            int(dti),
            "channel_data": [{
                "bias": {
                    "amplitude": [float(uij) for uij in ui]
                }
            }]
        })
    program = [[] for i in range(args.frame)]
    program.append(segment)
    dev.park()
    dev.program(program, [args.channel])
    dev.unpark()
    dev.cmd("TRIGGER", args.free)
예제 #5
0
파일: cli.py 프로젝트: nist-ionstorage/pdq2
def main(dev=None):
    """Test a PDQ2 stack.

    Parse command line arguments, configures PDQ2 stack, interpolate the
    time/voltage data using a spline, generate a wavesynth program from the
    data and upload it to the specified channel. Then perform the desired
    arming/triggering/starting functions on the stack.
    """
    parser = get_argparser()
    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.WARNING)

    if args.dump:
        dev = open(args.dump, "wb")
    dev = Pdq2(args.serial, dev)

    if args.reset:
        dev.write(b"\x00\x00")  # flush any escape
        dev.cmd("RESET", True)
        time.sleep(.1)

    dev.cmd("DCM", args.multiplier)
    freq = 50e6
    if args.multiplier:
        freq *= 2

    times = np.around(eval(args.times, globals(), {})*freq)
    voltages = eval(args.voltages, globals(), dict(t=times/freq))

    dev.cmd("START", False)
    dev.cmd("ARM", True)
    dev.cmd("TRIGGER", True)

    dt = np.diff(times.astype(np.int))
    if args.order:
        tck = interpolate.splrep(times, voltages, k=args.order, s=0)
        u = interpolate.spalde(times, tck)
    else:
        u = voltages[:, None]
    segment = []
    for dti, ui in zip(dt, u):
        segment.append({
            "duration": int(dti),
            "channel_data": [{
                "bias": {
                    "amplitude": [float(uij) for uij in ui]
                }
            }]
        })
    program = [[] for i in range(dev.channels[args.channel].num_frames)]
    program[args.frame] = segment
    dev.program(program, [args.channel])

    dev.cmd("TRIGGER", args.free)
    dev.cmd("ARM", not args.disarm)
    dev.cmd("START", True)
예제 #6
0
def main():
    args = get_argparser().parse_args()
    init_logger(args)
    dev = Client(args.server, args.port, "pdq2")

    freq = dev.get_freq()
    times = np.around(eval(args.times, globals(), {})*freq)
    voltages = eval(args.voltages, globals(), dict(t=times/freq))

    dt = np.diff(times.astype(np.int))
    if args.order:
        tck = interpolate.splrep(times, voltages, k=args.order, s=0)
        u = interpolate.spalde(times, tck)
    else:
        u = voltages[:, None]
    segment = []
    for dti, ui in zip(dt, u):
        segment.append({
            "duration": int(dti),
            "channel_data": [{
                "bias": {
                    "amplitude": [float(uij) for uij in ui]
                }
            }]
        })
    program = [[] for i in range(args.frame)]
    program.append(segment)
    dev.park()
    dev.program(program, [args.channel])
    dev.unpark()
    dev.cmd("TRIGGER", args.free)
예제 #7
0
 def test_spalde_scalar_input(self):
     """Ticket #629"""
     x = np.linspace(0,10)
     y = x**3
     tck = interp.splrep(x, y, k=3, t=[5])
     res = interp.spalde(np.float64(1), tck)
     des = np.array([1., 3., 6., 6.])
     assert_almost_equal(res, des)
예제 #8
0
 def test_spalde_scalar_input(self):
     """Ticket #629"""
     x = np.linspace(0, 10)
     y = x**3
     tck = interp.splrep(x, y, k=3, t=[5])
     res = interp.spalde(np.float64(1), tck)
     des = np.array([1., 3., 6., 6.])
     assert_almost_equal(res, des)
예제 #9
0
파일: curvature.py 프로젝트: m4nh/ariadne
    def computeScore(self, path, initial_direction=None):
        """
        Computes the score for a given path. Considering also degenerate paths

        Parameters
        ----------
        path : AriadnePath
            target path

        initial_direction : np.array
            initial direction used to compute the score of single-edge paths

        """

        #######################################
        # Path with k nodes
        #######################################
        if path.size() <= self.k:
            return 1.0

        #######################################
        # Normal Path
        #######################################
        spline = self.computeSpline(path)
        if spline is None:
            return 1.0

        u = spline['u']
        tck = spline['tck']

        der = spalde(u, tck)

        total_curvature = 0.0
        total_curvature_pos = 0.0
        for i in range(0, len(u)):

            d1 = (der[0][i][1], der[1][i][1])
            d2 = (der[0][i][2], der[1][i][2])
            x1 = d1[0]
            y1 = d1[1]
            x2 = d2[0]
            y2 = d2[1]
            curvature = (x1 * y2 - y1 * x2) / \
                ((x1 * x1 + y1 * y1)**(3.0 / 2.0))
            total_curvature += curvature
            total_curvature_pos += math.fabs(curvature)

        normalized_curvature = total_curvature_pos / float(len(u))
        final_curvature = min(1.0, 1.0 - normalized_curvature)
        return final_curvature
예제 #10
0
    def eval_spline(self, dist):
        """Use spline to generate point

        Args:
            dist (float): lane change dist

        Returns:
            spalde: Evaluate all derivatives of a B-spline.
            https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.interpolate.spalde.html
        """
        center_line = self._track_data.center_line
        min_dist = self._lane["spline"][0][SPLINE_DEGREE]
        max_dist = self._lane["spline"][0][-SPLINE_DEGREE - 1]
        if dist < min_dist:
            dist += center_line.length
        if dist > max_dist:
            dist -= center_line.length
        return spalde(max(min_dist, min(dist, max_dist)), self._lane["spline"])
예제 #11
0
파일: curvature.py 프로젝트: m4nh/ariadne
    def computeCurvatures(self, spline):
        u = spline['u']
        tck = spline['tck']

        der = spalde(u, tck)

        curvatures = np.zeros((len(u), 1))
        for i in range(0, len(u)):

            d1 = (der[0][i][1], der[1][i][1])
            d2 = (der[0][i][2], der[1][i][2])
            x1 = d1[0]
            y1 = d1[1]
            x2 = d2[0]
            y2 = d2[1]
            curvature = (x1 * y2 - y1 * x2) / \
                ((x1 * x1 + y1 * y1)**(3.0 / 2.0))
            curvatures[i] = curvature
        return curvatures
    def _eval_spline(self, initial_dist, sim_time, spline):
        '''Use spline to generate point

        Args:
            initial_dist (float): bot car initial distance
            sim_time (float): current simulation time
            spline (splprep): B-spline representation of an N-dimensional curve.
            https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.splprep.html

        Returns:
            spalde: Evaluate all derivatives of a B-spline.
            https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.interpolate.spalde.html
        '''
        center_line = self.track_data._center_line_
        dist = self._get_dist_from_sim_time(initial_dist, sim_time)
        min_dist = spline[0][SPLINE_DEGREE]
        max_dist = spline[0][-SPLINE_DEGREE - 1]
        if dist < min_dist: dist += center_line.length
        if dist > max_dist: dist -= center_line.length
        return spalde(max(min_dist, min(dist, max_dist)), spline)
예제 #13
0
  def splade(self,tx,tck):
    """
    Task: wrapper around the scipy splade
          it computes the derivatives of the curves 
    Input:   tx    1d array of parameter values of the points interpolated
                   0 <= tx[i] <=1, and ordered increasingly
                   e.g. np.linspace(0,1,m)
             tck   the output of splprep:
                   tck[0]= array of knots
                   tck[1]= list of arrays
                           =the coefficients of the spline polynomials
                           in each point
                   tck[2]= degree of the common polynomials
    Output: lder   the values of the derivatives
                   list of list of arrays
                   D^k x_i[j]=lder[j][i][k]
                       k degree of derivative
                       i index of a point
                       j component of point vector 
    """

    lder=spinterp.spalde(tx,tck)

    return(lder)
예제 #14
0
def preprocess_centerline(raw_centerline, config):
    # [x, y, theta, s]
    tck, u = splprep(raw_centerline[:, 0],
                     raw_centerline[:, 1],
                     s=config['preproc_smooth'],
                     k=5,
                     per=True)
    # unew = np.arange(0, 1.0, 0.002)
    unew = np.linspace(0., 1., config['num_preproc_points'])
    new_centerline = np.asarray(splev(unew, tck)).T
    diffs = np.linagl.norm(new_centerline[1:] - new_centerline[:-1], axis=1)
    s = np.cumsum(diffs)
    s = np.insert(s, 0, 0)
    derivs = spalde(unew, tck)
    Dx = np.asarray(derivs[0])
    Dy = np.asarray(derivs[1])
    dx = Dx[:, 1]
    dy = Dy[:, 1]
    theta = np.arctan2(dy, dx)
    waypoints = np.empty((new_centerline.shape[0], 4))
    waypoints[:, 0:2] = new_centerline
    waypoints[:, 2] = theta
    waypoints[:, 3] = s
    return waypoints
예제 #15
0
파일: cli.py 프로젝트: m-labs/pdq2
def main(dev=None, args=None):
    """Test a PDQ stack.

    Parse command line arguments, configures PDQ stack, interpolate the
    time/voltage data using a spline, generate a wavesynth program from the
    data and upload it to the specified channel. Then perform the desired
    arming/triggering/starting functions on the stack.
    """
    parser = get_argparser()
    args = parser.parse_args(args=args)

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.WARNING)

    if args.dump:
        dev = open(args.dump, "wb")
    dev = PDQ(args.serial, dev)

    if args.reset:
        dev.write(b"")  # flush eop
        dev.set_config(reset=True)
        time.sleep(.1)

    dev.set_crc(0)
    dev.checksum = 0

    freq = 50e6
    if args.multiplier:
        freq *= 2

    times = np.around(eval(args.times, globals(), {})*freq)
    voltages = eval(args.voltages, globals(), dict(t=times/freq))

    dev.set_config(reset=False, clk2x=args.multiplier, enable=False,
                   trigger=False, aux_miso=args.aux_miso,
                   aux_dac=args.aux_dac, board=0xf)

    dt = np.diff(times.astype(np.int))
    if args.order and interpolate:
        tck = interpolate.splrep(times, voltages, k=args.order, s=0)
        u = interpolate.spalde(times, tck)
    else:
        u = voltages[:, None]
    segment = []
    for dti, ui in zip(dt, u):
        segment.append({
            "duration": int(dti),
            "channel_data": [{
                "bias": {
                    "amplitude": [float(uij) for uij in ui]
                }
            }]
        })
    program = [[] for i in range(dev.channels[args.channel].num_frames)]
    program[args.frame] = segment
    dev.program(program, [args.channel])

    dev.set_frame(args.frame)
    dev.set_config(reset=False, clk2x=args.multiplier, enable=not args.disarm,
                   trigger=args.free, aux_miso=args.aux_miso,
                   aux_dac=args.aux_dac, board=0xf)
예제 #16
0
def updateVesselWidthRelatedParameters(Img, dict_side1_updated,
                                       dict_side2_updated, dict_vesselAngles):
    if len(Img.shape) == 3:
        Img_green = Img[:, :, 1]
    else:
        Img_green = Img.copy()

    # clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    # Img_green = clahe.apply(Img_green)
    Img_green_illum = illuminationCorrection2(Img_green,
                                              kernel_size=35,
                                              filterOption=0)
    X = np.arange(0, Img_green.shape[0])
    Y = np.arange(0, Img_green.shape[1])
    InterpFunc = interpolate.RectBivariateSpline(
        X, Y, Img_green_illum)  # Img_green_illum

    dict_vesselWidth_updated = {}
    dict_splinePoints_updated = {}  ##no need to update splinePoints
    dict_smoothSide1_updated = {}
    dict_smoothSide2_updated = {}
    dict_profileIntensity_updated = {}

    for vesselKey in dict_side1_updated.keys():
        if len(dict_side1_updated[vesselKey]
               [0]) > 20:  #if the vessel is shorter than 20 then remove it
            dict_vesselWidth_updated[vesselKey] = np.hypot(
                (dict_side1_updated[vesselKey][0] -
                 dict_side2_updated[vesselKey][0]),
                (dict_side1_updated[vesselKey][1] -
                 dict_side2_updated[vesselKey][1]))

            # try:
            tempMaxWidth = np.max(dict_vesselWidth_updated[vesselKey])
            tempMaxWidth = np.ceil(tempMaxWidth) + 2
            """Later test the cases that part of the side1 and 2 are removed"""

            ##Update smoothside1 and 2
            sidePointList1 = np.array([
                dict_side1_updated[vesselKey][0].reshape(-1),
                dict_side1_updated[vesselKey][1].reshape(-1)
            ])
            sidePointList2 = np.array([
                dict_side2_updated[vesselKey][0].reshape(-1),
                dict_side2_updated[vesselKey][1].reshape(-1)
            ])
            dict_smoothSide1_updated[vesselKey] = splineInterpolation(
                sidePointList1, order=2)
            dict_smoothSide2_updated[vesselKey] = splineInterpolation(
                sidePointList2, order=2)

            ##Update the dict_profileIntensity
            centerline0 = np.concatenate(
                ((dict_side1_updated[vesselKey][0].reshape(-1,1) + dict_side2_updated[vesselKey][0].reshape(-1,1)) / 2.0, \
                 (dict_side1_updated[vesselKey][1].reshape(-1,1)+ dict_side2_updated[vesselKey][1].reshape(-1,1)) / 2.0),
                axis=1)

            controlPoint = centerline0[::5, :]
            order = 1
            tck, u = interpolate.splprep(controlPoint.transpose(),
                                         k=order,
                                         s=0)
            unew = np.linspace(0, 1.00, centerline0.shape[0])
            out = interpolate.splev(unew, tck)
            dict_splinePoints_updated[vesselKey] = out

            derivative = interpolate.spalde(
                unew, tck
            )  ##two lists are returned, the first list is derivative for row, second is for col.

            der_row = np.array(derivative[0])
            der_col = np.array(derivative[1])

            der = np.array([der_row[:, 1], der_col[:, 1]]).transpose()
            normal1 = np.dot(der, np.array([[0, 1], [-1, 0]]))
            normal1 = np.float32(normal1) / np.tile(
                np.sqrt(normal1[:, 0]**2 + normal1[:, 1]**2),
                (2, 1)).transpose()

            dict_vesselAngles[vesselKey] = normal1
            inc = np.arange(0, tempMaxWidth) - tempMaxWidth // 2
            tempProfileRows = np.dot(normal1[:, 0].reshape(
                (-1, 1)), inc.reshape(1, -1)) + np.tile(
                    out[0].reshape(-1, 1), (1, len(inc)))
            tempProfileCols = np.dot(normal1[:, 1].reshape(
                (-1, 1)), inc.reshape(1, -1)) + np.tile(
                    out[1].reshape(-1, 1), (1, len(inc)))

            dict_profileIntensity_updated[vesselKey] = InterpFunc.ev(
                tempProfileRows, tempProfileCols)

        else:
            dict_side1_updated.pop(vesselKey)
            dict_side2_updated.pop(vesselKey)


    return dict_splinePoints_updated, dict_profileIntensity_updated, dict_side1_updated, dict_side2_updated, \
           dict_smoothSide1_updated, dict_smoothSide2_updated, dict_vesselWidth_updated
예제 #17
0
 def alde(self, x):
     u = np.array([spalde(x, si) for si in self.s])
     if len(x) == 1:
         u = u[:, None, :]
     return u
예제 #18
0
def vesselWidthProfile(Img, IllumImage, Img_BW, Mask, dict_segmentPixelLocs):
    if len(Img.shape) == 3:
        Img_green = Img[:, :, 1]
    else:
        Img_green = Img

    Img_BW[Img_BW > 0] = 1
    Mask[Mask > 0] = 1

    height, width = Img_BW.shape[:2]

    if len(IllumImage.shape) == 3:
        IllumGreenReverse = np.uint8(255 - IllumImage[:, :, 1])
    else:
        IllumGreenReverse = np.uint8(255 - IllumImage)

    #print IllumGreenReverse.shape, " =?= ", Mask.shape
    try:
        IllumGreenReverse = cv2.bitwise_and(IllumGreenReverse,
                                            IllumGreenReverse,
                                            mask=Mask)
    except:
        print 'error creating IllumGreenReverse'
        #Mask = np.array([np.append(Img_BW[k], 0) for k in range(0, len(Img_BW))])
        import pdb
        pdb.set_trace()

    DistTransform_vessel = cv2.distanceTransform(
        Img_BW,
        distanceType=cv2.cv.CV_DIST_L2,
        maskSize=cv2.cv.CV_DIST_MASK_PRECISE)
    maxVesselWidth = 6 * np.max(DistTransform_vessel)
    """smooth the skeleton image into a spline image."""
    ##for RectBivariateSpline
    X = np.arange(0, Img_green.shape[0])
    Y = np.arange(0, Img_green.shape[1])
    InterpFunc_Illum = interpolate.RectBivariateSpline(
        X, Y, IllumGreenReverse)  #ImgGreenReverse
    InterpFunc = interpolate.RectBivariateSpline(X, Y,
                                                 Img_green)  #ImgGreenReverse
    ##The interpolated image should be the reverse image

    SplineImg = np.zeros(Img_BW.shape)
    dict_splinePoints = {}
    dict_centerPoint = {}
    dict_vesselAngles = {}
    dict_profileRows = {}
    dict_profileCols = {}
    dict_profileIntensity = {}
    dict_profileIntensity_Illum = {}

    for vesselLabel in dict_segmentPixelLocs.keys():  #['1', '2', '15', '25']
        pixelLocs0 = dict_segmentPixelLocs[vesselLabel]
        if pixelLocs0.shape[
                0] >= 21:  #11 previously. This means that vessel length <11 are not used for width calculation.
            pixelLocs = pixelLocs0[
                5:
                -5, :]  #the first and end 5 pixels near branch points are removed
            controlPoint = pixelLocs[np.arange(
                len(pixelLocs))[::10], :]  ##select every other 5 points.
            for loc in controlPoint:
                SplineImg[int(loc[0]), int(loc[1])] = 1

            order = 1
            tck, u = interpolate.splprep(controlPoint.transpose(),
                                         k=order,
                                         s=0)
            unew = np.linspace(0, 1.00, len(pixelLocs))
            out = interpolate.splev(unew, tck)
            dict_splinePoints[vesselLabel] = out
            derivative = interpolate.spalde(
                unew, tck
            )  ##two lists are returned, the first list is derivative for row, second is for col.

            der_row = np.array(derivative[0])
            der_col = np.array(derivative[1])

            der = np.array([der_row[:, 1], der_col[:, 1]]).transpose()
            normal1 = np.dot(der, np.array([[0, 1], [-1, 0]]))
            normal1 = np.float32(normal1) / np.tile(
                np.sqrt(normal1[:, 0]**2 + normal1[:, 1]**2),
                (2, 1)).transpose()

            dict_centerPoint[vesselLabel] = (out[0], out[1])
            dict_vesselAngles[vesselLabel] = normal1
            inc = np.arange(0, maxVesselWidth) - maxVesselWidth // 2
            dict_profileRows[vesselLabel] = np.dot(
                normal1[:, 0].reshape((-1, 1)), inc.reshape(1, -1)) + np.tile(
                    out[0].reshape(-1, 1), (1, len(inc)))
            dict_profileCols[vesselLabel] = np.dot(
                normal1[:, 1].reshape((-1, 1)), inc.reshape(1, -1)) + np.tile(
                    out[1].reshape(-1, 1), (1, len(inc)))
            """Remove the ones outside image region"""
            dict_profileRows[vesselLabel][
                dict_profileRows[vesselLabel] >= height - 1] = np.nan
            dict_profileRows[vesselLabel][
                dict_profileRows[vesselLabel] < 0] = np.nan
            dict_profileRows[vesselLabel][
                dict_profileCols[vesselLabel] >= width - 1] = np.nan
            dict_profileRows[vesselLabel][
                dict_profileCols[vesselLabel] < 0] = np.nan

            dict_profileCols[vesselLabel][np.isnan(
                dict_profileRows[vesselLabel])] = np.nan

            dict_profileRows[vesselLabel] = dict_profileRows[vesselLabel][
                ~np.isnan(dict_profileRows[vesselLabel]).any(axis=1)]
            dict_profileCols[vesselLabel] = dict_profileCols[vesselLabel][
                ~np.isnan(dict_profileCols[vesselLabel]).any(axis=1)]

            dict_profileIntensity[vesselLabel] = InterpFunc.ev(
                dict_profileRows[vesselLabel], dict_profileCols[vesselLabel])
            dict_profileIntensity_Illum[vesselLabel] = InterpFunc_Illum.ev(
                dict_profileRows[vesselLabel], dict_profileCols[vesselLabel])

    ##################################################################
    """To calculate the acurate vessel width and vessel edges"""

    smooth_scale_parallel = 3
    smooth_scale_perpendicular = 0.15
    enforce_connectedness = True

    dict_ProfileMap, dict_BWVesselProfiles, dict_BWRegionProfiles = createVesselProfileMasks(
        dict_profileRows, dict_profileCols, Img_BW, Mask)
    dict_side1 = {}
    dict_side2 = {}
    dict_smoothSide1 = {}
    dict_smoothSide2 = {}
    dict_vesselWidth = {}
    dict_profileSide = {}
    for vesselKey in dict_profileRows.keys():

        #% Create the default side coordinates
        dict_side1[vesselKey] = (np.zeros(len(dict_centerPoint[vesselKey][0])),
                                 np.zeros(len(dict_centerPoint[vesselKey][1])))
        dict_side2[vesselKey] = (np.zeros(len(dict_centerPoint[vesselKey][0])),
                                 np.zeros(len(dict_centerPoint[vesselKey][1])))

        #Extract the profiles and coordinates
        im_profiles = dict_profileIntensity_Illum[vesselKey]
        im_profiles_rows = dict_profileRows[vesselKey]
        im_profiles_cols = dict_profileCols[vesselKey]
        n_profiles = dict_profileRows[vesselKey].shape[0]

        ##get the width estimate of each vessel
        col_central = dict_profileIntensity_Illum[vesselKey].shape[1] // 2
        BW_vessel_profiles = dict_BWVesselProfiles[vesselKey]
        binary_sums = np.sum(BW_vessel_profiles, 1)
        width_estimate0 = np.median(
            binary_sums)  #[BW_vessel_profiles[:, col_central]]
        if width_estimate0 > col_central:
            width_estimate0 = col_central

        ##Compute a mean profile for the entire vessel, omitting pixels closer to other vessels
        BW_regions = dict_BWRegionProfiles[vesselKey]
        im_profiles_closest = im_profiles.copy()
        im_profiles_closest[np.bitwise_not(BW_regions)] = np.NaN
        profile_mean = np.nanmean(im_profiles_closest, 0)

        try:
            left_mean_col, right_mean_col = find_maximum_gradient_columns(
                profile_mean.copy(),
                width_estimate0)  #profile_mean will be changed inside the func
        except:
            pass

        width_estimate = right_mean_col - left_mean_col

        # Create 1D Gaussian filters for smoothing parallel and perpendicular to the vessel
        # Sigma values are based on the square root of the scaled width
        # estimates
        gv = gaussian_filter_1d_sigma(
            np.sqrt(width_estimate * smooth_scale_parallel)).reshape(-1, 1)
        gh = gaussian_filter_1d_sigma(
            np.sqrt(width_estimate * smooth_scale_perpendicular)).reshape(
                -1, 1)

        #Apply Gaussian smoothing
        im_profiles_filtered = filters.convolve(im_profiles,
                                                np.dot(gv, gh.transpose()))

        #Compute 2nd derivative perpendicular to vessel orientation
        im_profiles_2d = compute_discrete_2d_derivative(im_profiles_filtered)
        ##Remove from consideration pixels outside the search region
        im_profiles_2d[np.bitwise_not(BW_regions)] = np.NAN

        diffs = np.diff(im_profiles_2d, axis=1)
        cross_offsets = -im_profiles_2d[:, :-1] / diffs
        cross_offsets[np.bitwise_or(cross_offsets >= 1,
                                    cross_offsets < 0)] = np.NAN
        cross = cross_offsets + np.tile(np.arange(0, cross_offsets.shape[1]),
                                        (cross_offsets.shape[0], 1))

        #Separate crossings according to whether they are positive -> negative
        #or negative -> positive, i.e. whether they are potentially rising or
        #falling edges, and only allow those on the appropriate size of the centerline
        cross_rising0 = cross.copy()
        cross_rising0[np.bitwise_or(diffs > 0,
                                    cross_rising0 > col_central)] = np.NAN
        cross_falling0 = cross.copy()
        cross_falling0[np.bitwise_or(diffs < 0,
                                     cross_falling0 < col_central)] = np.NAN

        #Look for the vessel edges, with or without a connectivity test.
        if not enforce_connectedness:
            search_left = im_profiles_2d[:, left_mean_col] <= 0
            col_left = find_closest_crossing(cross_rising0.copy(),
                                             left_mean_col, search_left)
            search_left = im_profiles_2d[:, right_mean_col] >= 0
            col_right = find_closest_crossing(cross_falling0.copy(),
                                              right_mean_col, search_left)

        else:
            cross_rising = find_most_connected_crossings(
                cross_rising0.copy(), left_mean_col,
                np.maximum(width_estimate / 3.0, 1))
            col_left = np.nanmax(cross_rising, 1)
            cross_falling = find_most_connected_crossings(
                cross_falling0.copy(), right_mean_col,
                np.maximum(width_estimate / 3.0, 1))
            col_right = np.nanmin(cross_falling, 1)

        #% Compute the side points, and store them
        rows = np.arange(0, n_profiles).reshape(-1, 1)
        inds_found = np.bitwise_and(np.isfinite(col_left),
                                    np.isfinite(col_right))
        dict_side1[vesselKey] = get_side(im_profiles_rows, im_profiles_cols,
                                         rows[inds_found],
                                         col_left[inds_found].reshape(-1, 1))
        dict_side2[vesselKey] = get_side(im_profiles_rows, im_profiles_cols,
                                         rows[inds_found],
                                         col_right[inds_found].reshape(-1, 1))

        sidePointList1 = np.array([
            dict_side1[vesselKey][0].reshape(-1),
            dict_side1[vesselKey][1].reshape(-1)
        ])
        sidePointList2 = np.array([
            dict_side2[vesselKey][0].reshape(-1),
            dict_side2[vesselKey][1].reshape(-1)
        ])
        dict_smoothSide1[vesselKey] = splineInterpolation(sidePointList1,
                                                          order=2)
        dict_smoothSide2[vesselKey] = splineInterpolation(sidePointList2,
                                                          order=2)
        dict_vesselWidth[vesselKey] = np.hypot(
            (dict_side1[vesselKey][0] - dict_side2[vesselKey][0]),
            (dict_side1[vesselKey][1] - dict_side2[vesselKey][1]))
        # dict_vesselWidth[vesselKey] = np.hypot((dict_smoothSide1[vesselKey][0] - dict_smoothSide2[vesselKey][0]),
        #                                        (dict_smoothSide1[vesselKey][1] - dict_smoothSide2[vesselKey][1]))
    """Remove the vessels where the vessel side is not detected correctly"""
    for vesselKey in dict_side1.keys():
        if len(dict_side1[vesselKey][0]) >= 20:
            pass
        else:  ##delete the vessels where the side is not detected correctly
            dict_side1.pop(vesselKey)
            dict_side2.pop(vesselKey)
            dict_smoothSide1.pop(vesselKey)
            dict_smoothSide2.pop(vesselKey)

            dict_splinePoints.pop(vesselKey)
            dict_profileIntensity.pop(vesselKey)
            dict_vesselWidth.pop(vesselKey)
            dict_vesselAngles.pop(vesselKey)

    ########################################################################
    """End of vessel profile measurement"""
    return dict_splinePoints, dict_profileIntensity, dict_side1, dict_side2, \
           dict_smoothSide1, dict_smoothSide2, dict_vesselWidth, dict_vesselAngles, dict_profileRows, dict_profileCols
예제 #19
0
import numpy as np
from matplotlib import pyplot as plt
from scipy import interpolate

x = np.linspace(0, 2 * np.pi + np.pi / 4, 10)
y = np.sin(x)

x_new = np.linspace(0, 2 * np.pi + np.pi / 4, 100)
f_linear = interpolate.interp1d(x, y)

para_bspline = interpolate.spalde(x, y)
y_bspline = interpolate.splev(x_new, para_bspline)

plt.plot(x, y, "o", label=u"yuanshishuju")
plt.plot(x_new, f_linear(x_new), label=u"xianxingchazhi")
plt.plot(x_new, y_bspline, label=u"B-spline chazhi")
plt.legend()
plt.grid(True)

plt.show()
예제 #20
0
def main(dev=None, args=None):
    """Test a PDQ stack.

    Parse command line arguments, configures PDQ stack, interpolate the
    time/voltage data using a spline, generate a wavesynth program from the
    data and upload it to the specified channel. Then perform the desired
    arming/triggering/starting functions on the stack.
    """
    parser = get_argparser()
    args = parser.parse_args(args=args)

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.WARNING)

    if args.dump:
        dev = open(args.dump, "wb")
    dev = PDQ(args.serial, dev)

    if args.reset:
        dev.write(b"")  # flush eop
        dev.set_config(reset=True)
        time.sleep(.1)

    dev.set_crc(0)
    dev.checksum = 0

    freq = 50e6
    if args.multiplier:
        freq *= 2

    times = np.around(eval(args.times, globals(), {})*freq)
    voltages = eval(args.voltages, globals(), dict(t=times/freq))

    dev.set_config(reset=False, clk2x=args.multiplier, enable=False,
                   trigger=False, aux_miso=args.aux_miso,
                   aux_dac=args.aux_dac, board=0xf)

    dt = np.diff(times.astype(np.int))
    if args.order and interpolate:
        tck = interpolate.splrep(times, voltages, k=args.order, s=0)
        u = interpolate.spalde(times, tck)
    else:
        u = voltages[:, None]
    segment = []
    for dti, ui in zip(dt, u):
        segment.append({
            "duration": int(dti),
            "channel_data": [{
                "bias": {
                    "amplitude": [float(uij) for uij in ui]
                }
            }]
        })
    program = [[] for i in range(dev.channels[args.channel].num_frames)]
    program[args.frame] = segment
    if args.print:
        if args.print == '-':
            f = sys.stdout
        else:
            f = open(args.print, 'w')
        print('# Generated WaveSynth program\n\nprogram = \\', file=f)
        pprint.pprint(program, f)
    dev.program(program, [args.channel])

    dev.set_frame(args.frame)
    dev.set_config(reset=False, clk2x=args.multiplier, enable=not args.disarm,
                   trigger=args.free, aux_miso=args.aux_miso,
                   aux_dac=args.aux_dac, board=0xf)
예제 #21
0
def spline_derivative(x_vector, y_vector):
    """Take a derivative using a spline"""
    tck = interpolate.splrep(x_vector, y_vector, k=3)
    deriv_y = np.array(interpolate.spalde(x_vector, tck))
    deriv_y = deriv_y[:, 1]  # take the first derivative of the spline
    return deriv_y
예제 #22
0
파일: cli.py 프로젝트: nist-ionstorage/pdq2
def main(dev=None):
    """Test a PDQ2 stack.

    Parse command line arguments, configures PDQ2 stack, interpolate the
    time/voltage data using a spline, generate a wavesynth program from the
    data and upload it to the specified channel. Then perform the desired
    arming/triggering/starting functions on the stack.
    """
    parser = get_argparser()
    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.WARNING)

    if args.dump:
        dev = open(args.dump, "wb")
    dev = Pdq2(args.serial, dev)

    if args.reset:
        dev.write(b"\x00\x00")  # flush any escape
        dev.cmd("RESET", True)
        time.sleep(.1)

    dev.cmd("DCM", args.multiplier)
    freq = 50e6
    if args.multiplier:
        freq *= 2

    times = np.around(eval(args.times, globals(), {}) * freq)
    voltages = eval(args.voltages, globals(), dict(t=times / freq))

    dev.cmd("START", False)
    dev.cmd("ARM", True)
    dev.cmd("TRIGGER", True)

    dt = np.diff(times.astype(np.int))
    if args.order:
        tck = interpolate.splrep(times, voltages, k=args.order, s=0)
        u = interpolate.spalde(times, tck)
    else:
        u = voltages[:, None]
    segment = []
    for dti, ui in zip(dt, u):
        segment.append({
            "duration":
            int(dti),
            "channel_data": [{
                "bias": {
                    "amplitude": [float(uij) for uij in ui]
                }
            }]
        })
    program = [[] for i in range(dev.channels[args.channel].num_frames)]
    program[args.frame] = segment
    dev.program(program, [args.channel])

    dev.cmd("TRIGGER", args.free)
    dev.cmd("ARM", not args.disarm)
    dev.cmd("START", True)
예제 #23
0
def spline_derivative(x_vector, y_vector):
    """Take a derivative using a spline"""
    tck = interpolate.splrep(x_vector, y_vector, k=3)
    deriv_y = np.array(interpolate.spalde(x_vector, tck))
    deriv_y = deriv_y[:, 1]  # take the first derivative of the spline
    return deriv_y
예제 #24
0
def processimage(imagefullpath='iimage-21.png', outputpath='./', pastresults=[]):

    try:
        imdata = scipy.misc.imread(imagefullpath)[:,:,0]
    except:
        imdata = scipy.misc.imread(imagefullpath)
    # structure: 0 outside, 255 inside

    imagename = imagefullpath.split('/')[-1]

    # find the starting point

    firstline = imdata[:,0]

    w = [scipy.where(firstline==255)[0][0],0]
    b = [w[0]-1,0]
    
    # state=0 means that white moves
    state = 0

    maxx = scipy.shape(imdata)[0]
    maxy = scipy.shape(imdata)[1]
    
    ws = [w,]
    bs = [b,]

    rejcounter=0

    while 1:

        if rejcounter<2:
            position, expectation = rotate(bs[-1], ws[-1], state)
        else:
            position, expectation = rotate(bs[-1], ws[-1], state, steps=2)
        

        if position[0]<0 or position[0]>=maxx or position[1]<0 or position[1]>=maxy:
            # out of bounds rejection

            if state == 0:
                rejcounter += 1

            else:
                bs.append(position)
                rejcounter = 0
                
        
        elif imdata[position[0], position[1]] == expectation:

            if state == 0:
                ws.append(position)
            else:
                bs.append(position)

            rejcounter=0
        
        else:
            rejcounter += 1
        
        state = (state + 1) % 2

        # break if we have a closed loop
        if ws[-1] in ws[:10] and len(ws)>10:
            break
    
    ws = scipy.array(ws)

    lineimage = 255*scipy.ones(scipy.shape(imdata))
    for w in ws:
        lineimage[w[0], w[1]] = 0.

    scipy.misc.imsave(outputpath + 'line-'+imagename, lineimage)

    t = scipy.linspace(0.,1.,len(ws[:,0]))
    tck, u = interpolate.splprep([ws[:,0], ws[:,1]], s=1e3, k=2, per=1)
    #unew = scipy.linspace(0.,1.,10000)

    data = interpolate.splev(t,tck)
    # pylab.plot(data[0], data[1])
    pylab.plot(ws[:,1], ws[:,0], color='blue')

    der = scipy.array(interpolate.spalde(t,tck))
    # format [[x,y], [n], [0,1,2,3der]]

    # following wolfram mathworld
    curvature = (der[0,:,1]*der[1,:,2] - der[1,:,1]*der[0,:,2])/(der[0,:,1]**2 + der[1,:,1]**2)**1.5

    csmooth = scipy.ndimage.gaussian_filter1d(curvature, 7.)

    # splitting when the curvature changes

    limit = -0.01
    
    splits1 = scipy.where(numpy.r_[csmooth[1:] < limit,] & numpy.r_[csmooth[:-1] > limit,])[0]

    splits2 = scipy.where(numpy.r_[csmooth[1:] > limit,] & numpy.r_[csmooth[:-1] < limit,])[0]

    res = scipy.concatenate((splits1,splits2))
    res.sort()

    # clean up too short segments
    i=0
    while i < len(res)-1:
        if res[i+1]-res[i]<35:
            try:
                res = scipy.concatenate([res[:i],res[i+2:]])
            except:
                res = res[:i]
        else:
            i+=1

    # pdb.set_trace()

    
    currentresults = []

    used = []


    # determine the maximum ID number used to date
    maxidnumber = 0
    for set in pastresults:
        oldx,oldy, oldidnumber, olddata = set
        maxidnumber = max(maxidnumber, oldidnumber)

    
    for l,r in zip(res[:-1],res[1:]):
        c = curvature[l:r] 
        if c.mean()>0:
            pylab.plot(data[1][l:r],data[0][l:r], color='red')
        else:
            x = data[0][l+sp:r-sp]
            y = data[1][l+sp:r-sp]
            pylab.plot(y, x, color='green')
            if y.mean()>50 and 50<x.mean()<maxx-50 and r-l>20+2*sp:

                # fit these points with a circle
                center, radius = getCenterRadius(ws[l+sp:r-sp,0], ws[l+sp:r-sp,1])
                pylab.gca().add_patch(pylab.Circle([center[1],center[0]], radius=radius,  fc='None'))
                pylab.text(y.mean(), x.mean(), '%1.2f'%radius, fontsize='x-small')

                
                select = []
                newset = False
                for set in pastresults:
                    oldx,oldy, oldidnumber, olddata = set
                    distance = (x.mean()-oldx)**2 + (y.mean()-oldy)**2
                    select.append([distance, oldidnumber, olddata])
                    
                    
                select.sort()
                try:
                    newdata = select[0][-1] + [[x.mean(), y.mean(), radius,],]
                    if used.__contains__(select[0][-1]):
                        newset = True
                    used.append(select[0][-1]) 

                except:
                    newdata = [[x.mean(), y.mean(), radius,],]
                    newset = True

                if newset == True:
                    maxidnumber += 1
                    idnumber = maxidnumber
                else:
                    idnumber = select[0][1]
                
                print idnumber

                pylab.text(y.mean(), x.mean() - 20, '%d'%idnumber, fontsize='x-small')


                currentresults.append([x.mean(), y.mean(), idnumber, newdata])
            
    pylab.axis([0.,maxy,0.,maxx])

    # KEEP TIME SERIES THAT WERE NOT EXTENDED
    for set in pastresults:
        if not used.__contains__(set[-1]):
            set[-1] += [[scipy.nan, scipy.nan, scipy.nan,],]
            currentresults.append(set)
    
    pylab.savefig(outputpath + 'processed-'+imagename+'.pdf')
    pylab.clf()

    return currentresults
예제 #25
0
 def alde(self, x):
     u = np.array([spalde(x, si) for si in self.s])
     if len(x) == 1:
         u = u[:, None, :]
     return u