elif homoplasy:
        homoplasycount += 1
    elif not int(SNP["location"]) in nonhomlocations:
        nonhomlocations.add(int(SNP["location"]))

print '\t'.join(
    map(str, [
        len(locations),
        len(locations) - len(homoplasylocations),
        len(homoplasylocations),
        (float(len(homoplasylocations)) / len(locations)) * 100, SNPcount,
        SNPcount - homoplasycount, homoplasycount,
        (float(homoplasycount) / SNPcount) * 100
    ]))

print 'Note: For total non-homoplasies, total homoplasies and % of SNPs that are homoplasic, for each site where homoplasy occurs, one SNP is considered non-homoplasic and the remainder are counted as homoplasic'

legend_colours = [(pylab.Rectangle((0, 0), 1, 1, fc="b")),
                  (pylab.Rectangle((0, 0), 1, 1, fc="r"))]
n, bins, patches = plt.hist(map(list, [nonhomlocations, homoplasylocations]),
                            bins=50,
                            color=["b", "r"],
                            histtype="barstacked")
plt.legend(legend_colours, ["Non homoplasy sites", "Homoplasy sites"])
plt.xlabel("Genome position")
plt.ylabel("SNP Frequency")
plt.xlim(0, 1100000)
plt.show()

#print missinglist
Exemplo n.º 2
0
 x = (x[:, None] + xsubject).flatten()
 y = np.array(Y).flatten()
 weight = 1. if trac == "Human" else 0.8
 c = [
     light_color(perfcolors[cond], weight=weight) for cond in conds
     for subj in subjects
 ]
 kwargs = dict(s=1., c=c, marker='.', zorder=2)
 if trac in visible_trackers:
     ax.scatter(x, y, **kwargs)
 # background patches and titles
 fc = light_color(obscolor[obsname], weight=0.07)
 patch = pl.Rectangle(((oi * nTracker) - 0.5, 0.),
                      nTracker,
                      5,
                      fc=fc,
                      ec="0.8",
                      lw=0.5,
                      zorder=-1)
 ax.add_patch(patch)
 linex = np.array([-0.43, nTracker - 0.57]), np.array(
     [nTracker / 2 - 0.5, nTracker / 2 - 0.5])
 liney = np.array([3.1, 3.1]), np.array([3.1, 3.15])
 for lx, ly in zip(linex, liney):
     kwargs = dict(lw=0.5,
                   color=obscolor[obsname],
                   zorder=5,
                   clip_on=False)
     ax.plot((oi * nTracker) + lx, ly, **kwargs)
 ax.text((oi * nTracker) + nTracker / 2 - 0.5,
         3.2,
Exemplo n.º 3
0
Arquivo: obs.py Projeto: tgreve/trgpy
def frequency_vs_redshift(transitions=['12CO(1-0)'],
                          observatory='JCMT',
                          plot=False):
    """
       Started:
       Updated: 05.02.17
    """

    # Output observatory header to terminal and define rx-list.
    if observatory == 'JVLA':
        #print('{0:>96}'.format('JVLA'))
        print('JVLA')
        rx = band['JVLA']
    elif observatory == 'SMA':
        #print('{0:>52}'.format('SMA'))
        print('SMA')
        rx = band['SMA']
    elif observatory == 'ALMA':
        print("ALMA")
        rx = band['ALMA']
    elif observatory == 'GBT':
        print("GBT")
        rx = band['GBT']
    elif observatory == 'IRAM NOEMA':
        #print('{0:>59}'.format('IRAM NOEMA'))
        print('IRAM NOEMA')
        rx = band['IRAM NOEMA']
    elif observatory == 'IRAM 30m':
        #print('{0:>81}'.format('IRAM 30m (EMIR)'))
        print('IRAM 30m (EMIR)')
        rx = band["IRAM-30m"]
    elif observatory == 'JCMT':
        #print('{0:>41}'.format('JCMT'))
        print('JCMT')
        rx = band['JCMT']
    elif observatory == 'FIRI':
        #print('{0:>33}'.format('FIRI (25-400um)'))
        print('FIRI (25-400um)')
        rx = band['FIRI']

    # Returned array containing z-range for given transition and rx combination
    rx_z_range = [[[0 for i in range(2)] for j in range(len(rx))]
                  for k in range(len(transitions))]
    foo = np.array(rx_z_range)

    # Prepare output string.
    str_out = '{0:22} {1:16}'.format('Line', 'Rest frequency')
    for i in np.arange(0, len(rx), 1):
        str_out = str_out + ' {0:15}'.format(rx[i][0])
    print(str_out)
    print('{0:22} {1:16}'.format('', '[GHz]'))

    # Calculate redshift ranges for trans+rx combinations and output to
    # terminal. Also determine the min/max frequency of rx.
    frq_min = 1.E6
    frq_max = 0.
    i = 0
    foo = []
    for trans in transitions:
        output_string = '{0:8.2f}'.format(freq[trans])
        output_string = '{0:20} {1:19}'.format(trans, output_string)
        for j in range(0, len(rx), 1):
            z_range = np.array([freq[trans], freq[trans]]) / rx[j][1:] - 1

            if z_range[0] > 0 and z_range[0] <= 25:
                if z_range[1] < 0: z_range[1] = 0
                dz_string = '{0:4.2f} {1:1} {2:4.2f}'.format(
                    z_range[1], '-', z_range[0])
                output_string = output_string + '{0:16}'.format(dz_string)
                rx_z_range[i][j][:] = [
                    trans, rx[j][0], [z_range[0], z_range[1]]
                ]
            else:
                output_string = output_string + '{0:16}'.format('--')

            # Determine min/max frequency range used for plot
            if frq_min > rx[j][1:][0]:
                frq_min = rx[j][1:][0]
            if frq_max < rx[j][1:][1]:
                frq_max = rx[j][1:][1]
        print(output_string)
        i = i + 1

    # Plot
    if plot:
        # Setup plot.
        pl.setup_graph(x_label=r'$z$',
                       y_label=r'$\nu_{\rm obs}\,{\rm [GHz]}$',
                       fig_size=(8, 8))
        plt.xlim(0., 10)
        ylim1 = frq_min * 0.5
        ylim2 = frq_max * 1.1
        plt.ylim(ylim1, ylim2)

        # Plot the observing bands.
        for i in range(0, len(rx), 1):
            rectangle = plt.Rectangle((0, rx[i][1]),
                                      10,
                                      rx[i][2] - rx[i][1],
                                      facecolor='green',
                                      edgecolor='black')
            plt.gca().add_patch(rectangle)
            plt.annotate(rx[i][0], xy=(0.1, rx[i][1]), fontsize=14)

        # Plot line frequency vs. redshift.
        z = np.linspace(0.001, 10, 100000)
        for var in transitions:
            if var in freq:
                frq_observed = freq[var] / (1. + z)
                plt.plot(z, frq_observed, 'k-', linewidth=2.0)
                y_label = freq[var]
                x_label = max(0.001, freq[var] / y_label - 1.)
                plt.annotate(var, xy=(x_label, y_label), fontsize=14)
        plt.show()
Exemplo n.º 4
0
def w51a_fields():
    """
    Map fields on the UKIDSS image.
    """
    img = pyfits.getdata(
        '/u/jlu/data/w51/ukidss/g48.9-0.3/ukidss_rgb_r_k.fits')

    s0coords = np.array([570.0, 598.0])
    scale = 0.2  # arcsec/pixel

    xaxis = (np.arange(img.shape[0], dtype=float) - s0coords[0]) * scale * -1.0
    yaxis = (np.arange(img.shape[1], dtype=float) - s0coords[1]) * scale

    fieldCenters = []
    fieldCenters.append({'name': 'f1', 'x': 3.341, 'y': -3.351})  # f1
    fieldCenters.append({'name': 'f2', 'x': 5.855, 'y': 3.693})  # f2
    fieldCenters.append({'name': 'f3', 'x': -2.611, 'y': 6.240})  # f3
    fieldCenters.append({'name': 'f4', 'x': -7.000, 'y': -2.500})  # f4

    ##########
    # Plot
    ##########
    py.clf()
    py.imshow(img,
              extent=[xaxis[0], xaxis[-1], yaxis[0], yaxis[-1]],
              cmap=py.cm.YlOrBr_r,
              vmin=500,
              vmax=50000)
    py.xlabel('R.A. Offset (arcsec)')
    py.ylabel('Dec. Offset (arcsec)')
    py.axis([20, -20, -20, 20])

    fig = py.gca()

    for f in fieldCenters:
        box = py.Rectangle([f['x'] - 5, f['y'] - 5],
                           10.0,
                           10.0,
                           fill=False,
                           edgecolor='lightgreen',
                           linewidth=2)
        fig.add_patch(box)

        if (np.sign(f['x']) > 0):
            ha = 'left'
        else:
            ha = 'right'

        if (np.sign(f['y']) > 0):
            va = 'top'
        else:
            va = 'bottom'

        xText = f['x'] + (4.5 * np.sign(f['x']))
        yText = f['y'] + (4.5 * np.sign(f['y']))
        py.text(xText,
                yText,
                f['name'],
                fontsize=18,
                fontweight='bold',
                color='lightgreen',
                horizontalalignment=ha,
                verticalalignment=va)
        py.savefig('/u/jlu/work/w51/maps/w51a_fields.png')
Exemplo n.º 5
0
    # mark sender position with transparent red circle
    ctrpos = pylab.array(topo.GetPosition(tgt)[0])
    ax.add_patch(
        pylab.Circle(ctrpos,
                     radius=0.1,
                     zorder=99,
                     fc='r',
                     alpha=0.4,
                     ec='none'))

    # mark mask position with open red rectangle
    ax.add_patch(
        pylab.Rectangle(ctrpos - (0.2, 0.5),
                        0.4,
                        1.0,
                        zorder=1,
                        fc='none',
                        ec='r',
                        lw=3))

# mark layer edge
ax.add_patch(
    pylab.Rectangle((-1.5, -1.5), 3.0, 3.0, zorder=1, fc='none', ec='k', lw=3))

# beautify
ax.set_xticks(pylab.arange(-1.5, 1.55, 0.5))
ax.set_yticks(pylab.arange(-1.5, 1.55, 0.5))
ax.grid(True)
ax.axis([-2.0, 2.0, -2.0, 2.0])
ax.set_aspect('equal', 'box')
ax.set_title('Connection sources')
Exemplo n.º 6
0
def plot_aarect_circle_data1(offset):
    (center_aarect, ring_touching, ring_near, ring_far,
     near_distance, far_distance, rays) = aarect_circle_data1(offset)

    rx = center_aarect.cshape.rx
    ry = center_aarect.cshape.ry
    small = create_obj_with_aarect('small', center_aarect.cshape.center,
                                rx - near_distance*2.0, ry - near_distance*2.0)
    

    def get_aarect_params(obj):
        x, y = obj.cshape.center
        rx = obj.cshape.rx
        ry = obj.cshape.ry
        #pylab wants lower left corner and width , height
        
        return obj.name, x-rx, y-ry, rx*2, ry*2
    
    def get_circle_params(obj):
        x, y = obj.cshape.center 
        return obj.name, x, y, obj.cshape.r
    
    import pylab
    fig = pylab.figure(figsize=(6.0, 6.0)) #size in inches
    fig.suptitle('aarect_circle_data1', fontsize=12)
    pylab.axes().set_aspect('equal') # aspect ratio

    name, x, y, w, h = get_aarect_params(center_aarect)
    rect = pylab.Rectangle((x,y), w, h,  ec='black', fc='none')
    pylab.gca().add_patch(rect)
    xmin = x
    xmax = x + w
    ymin = y
    ymax = y + h  

##    rx = center_aarect.cshape.rx
##    ry = center_aarect.cshape.ry
##    small = create_obj_with_aarect('small', center_aarect.cshape.center,
##                                rx - near_distance*2.0, ry - near_distance*2.0)
##    name, x, y, w, h = get_params(small)
##    rect = pylab.Rectangle((x,y), w, h,  ec='g', fc='none')
##    pylab.gca().add_patch(rect)


    for ring, color in [ (ring_touching, 'r'), (ring_near, 'g'),
                         (ring_far, 'b') ]:
        for obj in ring:
            name, x, y, r = get_circle_params(obj)
            cir = pylab.Circle((x,y), radius=r,  ec=color, fc='none')
            pylab.gca().add_patch(cir)
    xmin = xmin - (far_distance + r)*2.5
    xmax = xmax + (far_distance + r)*2.5
    ymin = ymin -(far_distance + r)*1.5
    ymax = ymax + (far_distance + r)*1.5
    ymin = -2.5
    # axis: xmin, xmax, ymin, ymax
    pylab.axis([xmin, xmax, ymin, ymax])

    # make legends
    labels = ['center_aarect', 'overlapping ring', 'near ring', 'far ring']
    colors = ['black', 'r', 'g', 'b' ]
    dummys = [ pylab.Line2D([0,1], [0,1], lw=2.0, c=e) for e in colors]
    pylab.gca().legend(dummys, labels, ncol=2, loc='lower center')

    #pylab.show()
    pylab.savefig('aarect_circle1_data.png')
Itgts = [t for t in alltgts if nest.GetStatus([t], 'model')[0] == 'I']

# obtain positions of targets
Etpos = tuple(zip(*topo.GetPosition(Etgts)))
Itpos = tuple(zip(*topo.GetPosition(Itgts)))

# plot excitatory
pylab.clf()
pylab.subplot(121)
pylab.scatter(Etpos[0], Etpos[1])
ctrpos = pylab.array(topo.GetPosition(E_id)[0])
ax = pylab.gca()
ax.add_patch(pylab.Circle(ctrpos, radius=0.02, zorder=99,
                          fc='r', alpha=0.4, ec='none'))
ax.add_patch(
    pylab.Rectangle(ctrpos + pylab.array((-0.4, -0.2)), 0.8, 0.4, zorder=1,
                    fc='none', ec='r', lw=3))
ax.add_patch(
    pylab.Rectangle(ctrpos + pylab.array((-0.2, -0.4)), 0.4, 0.8, zorder=1,
                    fc='none', ec='r', lw=3))
ax.add_patch(
    pylab.Rectangle(ctrpos + pylab.array((-0.5, -0.5)), 1.0, 1.0, zorder=1,
                    fc='none', ec='k', lw=3))
ax.set(aspect='equal', xlim=[-0.5, 0.5], ylim=[-0.5, 0.5],
       xticks=[], yticks=[])

# plot inhibitory
pylab.subplot(122)
pylab.scatter(Itpos[0], Itpos[1])
ctrpos = topo.GetPosition(E_id)[0]
ax = pylab.gca()
ax.add_patch(pylab.Circle(ctrpos, radius=0.02, zorder=99,
Exemplo n.º 8
0
import random, pylab

N = 20
L = 10.0
sigma = 0.1
conf = []
while len(conf) < N:
    conf.append(random.uniform(sigma, L - sigma))
    for k in range(len(conf) - 1):
        if abs(conf[-1] - conf[k]) < 2.0 * sigma:
            conf = []
            break

# begin of graphical output
bluesquare = pylab.Rectangle((sigma, 0), L - 2 * sigma, 0.33 * L, fc='b')
pylab.gca().add_patch(bluesquare)
for pin in conf:
    whiterec = pylab.Rectangle((pin - 2 * sigma, 0),
                               4 * sigma,
                               0.33 * L,
                               fc='w',
                               ec='w')
    pylab.gca().add_patch(whiterec)
for pin in conf:
    redrec = pylab.Rectangle((pin - sigma, 0), 2 * sigma, 0.33 * L, fc='r')
    pylab.gca().add_patch(redrec)
pylab.axis('scaled')
pylab.axis('scaled')
pylab.axis([0, L, 0, 0.33 * L])
pylab.xlabel('$x$', fontsize=14)
pylab.title('red: clothes pins; blue: remaining available space')
Exemplo n.º 9
0
    ax.set_ylabel("Performance\navg ± sem", labelpad=-24)
    ax.set_yticks([perf_level["chance"], perf_level["perfect"]])
    ax.set_yticklabels([f"\n{pc:.2f}\n(chance)", f"\n{pp:.2f}\n(perfect)"])

    # xticks
    ax.set_xticks(np.arange(nTracker))
    ax.set_xticklabels([
        dict(Human="Human", TRU="Correct prior", IND="IND prior")[tr]
        for tr in trackers
    ],
                       fontsize=8)

    patch = pl.Rectangle((0.5, 0.),
                         5,
                         5,
                         fc="0.9",
                         ec="0.8",
                         lw=0.5,
                         zorder=-1)
    ax.add_patch(patch)
    t = ax.text(1.8,
                3 - 0.2,
                "Bayesian observer\nmodel predictions",
                fontsize=6,
                va="center",
                ha="center",
                color="0.15")

if "C" in PLOT:
    for i, s in enumerate(("graph", "assignment", "confusion")):
        ax = axes["obsmodel_%d" % i]
Exemplo n.º 10
0
import random, pylab

N = 15
L = 10.0
sigma = 0.1
conf = []

while len(conf) < N:
    conf.append(random.uniform(sigma, L - sigma))
    for k in range(len(conf) - 1):
        if abs(conf[-1] - conf[k]) < 2.0 * sigma:
            conf = []
            break

# begin of graphical output
bluesquare = pylab.Rectangle((sigma, 0), L - 2 * sigma, 0.33 * L, fc="b")
pylab.gca().add_patch(bluesquare)
for pin in conf:
    whiterec = pylab.Rectangle((pin - 2 * sigma, 0),
                               4 * sigma,
                               0.33 * L,
                               fc="w",
                               ec="w")
    pylab.gca().add_patch(whiterec)
for pin in conf:
    redrec = pylab.Rectangle((pin - sigma, 0), 2 * sigma, 0.33 * L, fc="r")
    pylab.gca().add_patch(redrec)

pylab.axis("scaled")
pylab.axis("scaled")
pylab.axis([0, L, 0, 0.33 * L])
Exemplo n.º 11
0
    fh.hubble_fit()
    cxx, cyy, czz = fh.conf_interval('om', 'w', 60)

    #plt.style.use('dark_background')
    #plt.figure(frameon=False)
    ylim = plt.ylim(-2.0, -0.41)
    xlim = plt.xlim(0., 0.45)
    plt.plot([0.3, 0.3], ylim, 'k--', lw=3, zorder=0)
    plt.plot(xlim, [-1, -1], 'k--', lw=3, zorder=0)
    plt.contourf(cx,
                 cy,
                 Statistics.pvalue2sigma(1 - cz),
                 np.array([np.min(Statistics.pvalue2sigma(1 - cz)), 1., 2.]),
                 cmap=plt.cm.Reds_r,
                 vmin=1,
                 alpha=0.8)
    plt.contourf(cxx,
                 cyy,
                 Statistics.pvalue2sigma(1 - czz),
                 np.array([np.min(Statistics.pvalue2sigma(1 - czz)), 1., 2.]),
                 cmap=plt.cm.Blues_r,
                 vmin=1,
                 alpha=0.8)
    plt.ylim(-1.45, -0.55)
    plt.xlim(0.11, 0.45)
    plt.ylabel('w', fontsize=18)
    plt.xlabel('$\Omega_m$', fontsize=18)
    p1 = plt.Rectangle((0, 0), 1, 1, fc="red")
    p2 = plt.Rectangle((0, 0), 1, 1, fc="blue")
    plt.legend([p1, p2], ['using SALT2', 'using SUGAR'])
Exemplo n.º 12
0
def DisplayTIC(fname, start=1, end='end', xaxis='time'):
    """
    Displays the TIC of a file and indicates two positions
    -----

    Keyword arguments:
        fname -- name of input file (mzML)\n
        start -- position of the first marker\n
        end -- position of the second marker\n
        xaxis -- format of the x-axis; either time (time) or spectrum # (id)
    """

    import pymzml
    import matplotlib.pyplot as plt

    msrun = pymzml.run.Reader(fname)

    if start == 'start':
        start = 1
    else:
        start = int(start)

    if xaxis == 'time':

        if end == 'end':
            # a random big number to fill the plot until the end
            # an explicit endtime cannot be calculated before iterating
            # over spectra
            end = 10000000
        else:
            end = int(end)

        time = []
        intensity = []
        for spectrum in msrun:
            try:
                time.append(spectrum['scan start time'] * 60)
                intensity.append(spectrum['total ion current'])
            except:
                continue

        print(start, end)

        f, ax = plt.subplots()
        ax.set_ylim([0, 1.1 * max(intensity)])
        ax.set_xlim([0, max(time)])
        ax.add_patch(
            plt.Rectangle(
                (start, 0),
                end - start,
                1.1 * max(intensity),
                fc='#336699',  # foreground colour
                ec='none'))  # edge colour
        ax.plot(time, intensity, 'black')
        ax.set_xlabel('time[sec]')
        ax.set_ylabel('intensity')

        f.tight_layout()
        return f

    if xaxis == 'id':

        if end == 'end':
            end = msrun.info['spectrum_count']
        else:
            end = int(end)

        scan_id = []
        intensity = []
        for spectrum in msrun:
            try:
                # removes entry 'TIC' on the last spectrum
                if isinstance(spectrum['id'], int):
                    scan_id.append(spectrum['id'])
                    intensity.append(spectrum['total ion current'])
            except:
                continue

        f, ax = plt.subplots()
        ax.set_ylim([0, 1.1 * max(intensity)])
        ax.set_xlim([0, max(scan_id)])
        # see   http://stackoverflow.com/questions/10665163/
        #       draw-rectangle-add-patch-in-pylab-mode
        ax.add_patch(
            plt.Rectangle((start, 0),
                          end - start,
                          1.1 * max(intensity),
                          fc='#336699',
                          ec='none'))
        ax.plot(scan_id, intensity, 'black')
        ax.set_xlabel('scan id')
        ax.set_ylabel('intensity')

        f.tight_layout()
        return f
Exemplo n.º 13
0
    def get_modes_asgn(self,
                       groups,
                       thresh=0.70,
                       moddiff=10.0,
                       freqthresh=1200.0,
                       graph=False):
        """
        Automatic assignment of normal modes to groups basing on cotributions of chosen groups/types of atoms to the normal modes.

        @param groups: assignment of atoms to the groups, see VibToolsMolecule.attype_groups() in Molecule module
        @type groups: list
        @param thresh: threshold for modes similarity (0.0,1.0)
        @type thresh: float
        @param moddiff: maximal distance between two neighboring normal modes in the same group
        @type moddiff: float
        @param freqthresh: lower frequency limit of considered normal modes
        @type freqthresh: float
        @param graph: plotting modes similarity matrix
        @type graph: bool
        @rtype: list
        @return: list of normal modes assigned to groups containing the most similar normal modes  
        """

        nmodes = self.nmodes
        freqs = self.freqs

        M = numpy.zeros((nmodes, nmodes))
        tmp = []
        groupmodes = []

        compos = self.get_composition(groups)
        compos = compos.transpose()

        for i in range(nmodes):
            compos[i, :] /= math.sqrt(numpy.dot(compos[i, :], compos[i, :]))

        for i in range(nmodes):
            for j in range(nmodes):
                M[i, j] = numpy.dot(compos[i, :], compos[j, :])
                diff = abs(freqs[i] - freqs[j])
                if diff > moddiff: M[i, j] /= diff / moddiff

        i = numpy.flatnonzero(freqs > freqthresh)[0]
        i = numpy.flatnonzero(M[i, :] > thresh)[0]
        tmp.append(i)
        while i < nmodes - 1:
            if M[i, i + 1] < thresh:
                groupmodes.append(tmp)
                tmp = []
            i += 1
            tmp.append(i)
        if tmp <> []: groupmodes.append(tmp)
        tmp = []

        for g in groupmodes:
            if len(g) > 1: tmp.append(g)
        groupmodes = tmp

        if graph == True:
            pylab.matshow(M)
            pylab.colorbar()
            pylab.grid()
            for i in groupmodes:
                p = pylab.Rectangle((i[0] - 0.5, i[0] - 0.5),
                                    i[-1] - i[0] + 1,
                                    i[-1] - i[0] + 1,
                                    facecolor='none',
                                    edgecolor='white',
                                    lw='2.0')
                pylab.gca()
                pylab.gca().add_patch(p)
            pylab.show()

        return groupmodes
Exemplo n.º 14
0
def plot_tracking(frame, pos, target_sz, should_resize_image, im, ground_truth):

    global \
        tracking_figure, tracking_figure_title, tracking_figure_axes, \
        tracking_rectangle, gt_point, \
        z_figure_axes, response_figure_axes

    timeout = 1e-6
    #timeout = 0.05  # uncomment to run slower
    if frame == 0:
        #pylab.ion()  # interactive mode on
        tracking_figure = pylab.figure()
        gs = pylab.GridSpec(1, 3, width_ratios=[3, 1, 1])

        tracking_figure_axes = tracking_figure.add_subplot(gs[0])
        tracking_figure_axes.set_title("Tracked object (and ground truth)")

        z_figure_axes = tracking_figure.add_subplot(gs[1])
        z_figure_axes.set_title("Template")

        response_figure_axes = tracking_figure.add_subplot(gs[2])
        response_figure_axes.set_title("Response")

        tracking_rectangle = pylab.Rectangle((0, 0), 0, 0)
        tracking_rectangle.set_color((1, 0, 0, 0.5))
        tracking_figure_axes.add_patch(tracking_rectangle)

        gt_point = pylab.Circle((0, 0), radius=5)
        gt_point.set_color((0, 0, 1, 0.5))
        tracking_figure_axes.add_patch(gt_point)

        tracking_figure_title = tracking_figure.suptitle("")

        pylab.show(block=False)

    elif tracking_figure is None:
        return  # we simply go faster by skipping the drawing
    elif not pylab.fignum_exists(tracking_figure.number):
        #print("Drawing window closed, end of game. "
        #      "Have a nice day !")
        #sys.exit()
        print("From now on drawing will be omitted, "
              "so that computation goes faster")
        tracking_figure = None
        return

    global z, response
    tracking_figure_axes.imshow(im, cmap=pylab.cm.gray)

    rect_y, rect_x = tuple(pos - target_sz/2.0)
    rect_height, rect_width = target_sz

    if should_resize_image:
        rect_y = rect_y * 2
        rect_x = rect_x * 2
        rect_height = rect_height * 2
        rect_width = rect_width * 2

    tracking_rectangle.set_xy((rect_x, rect_y))
    tracking_rectangle.set_width(rect_width)
    tracking_rectangle.set_height(rect_height)

    if len(ground_truth) > 0:
        gt = ground_truth[frame]
        gt_y, gt_x = gt
        gt_point.center = (gt_x, gt_y)

    if tracker.z is not None:
        z_figure_axes.imshow(tracker.z, cmap=pylab.cm.hot)

    if tracker.response is not None:
        response_figure_axes.imshow(tracker.response, cmap=pylab.cm.hot)

    tracking_figure_title.set_text("Frame %i (out of %i)"
                                   % (frame + 1, len(ground_truth)))

    if debug and False and (frame % 1) == 0:
        print("Tracked pos ==", pos)

    #tracking_figure.canvas.draw()  # update
    pylab.draw()
    pylab.waitforbuttonpress(timeout=timeout)

    return
Exemplo n.º 15
0
               markeredgewidth=0,
               zorder=1,
               label='_nolegend_')

    # mark sender position with transparent red circle
    ctrpos = topo.GetPosition(ctr_id)[0]
    pylab.gca().add_patch(
        pylab.Circle(ctrpos,
                     radius=0.15,
                     zorder=99,
                     fc='r',
                     alpha=0.4,
                     ec='none'))

    # mark mask positions with open red/blue circles
    pylab.gca().add_patch(
        pylab.Circle(ctrpos, radius=0.5, zorder=2, fc='none', ec='b', lw=3))
    pylab.gca().add_patch(
        pylab.Circle(ctrpos, radius=1.0, zorder=2, fc='none', ec='r', lw=3))

# mark layer edge
pylab.gca().add_patch(
    pylab.Rectangle((-1.5, -1.5), 3.0, 3.0, zorder=1, fc='none', ec='k', lw=3))

# beautify
pylab.axes().set_xticks(pylab.arange(-1.5, 1.55, 0.5))
pylab.axes().set_yticks(pylab.arange(-1.5, 1.55, 0.5))
pylab.grid(True)
pylab.axis([-1.6, 1.6, -1.6, 1.6])
pylab.axes().set_aspect('equal', 'box')