Exemple #1
0
                         top=False,
                         labelbottom=True,
                         labeltop=False,
                         width=0)
ax.set_frame_on(False)
for sg1_index, sg2_index in disulfide_bonds:
    sg1_res_id = knottin.res_id[sg1_index]
    sg2_res_id = knottin.res_id[sg2_index]
    ellipse_center = (sg1_res_id + sg2_res_id) / 2
    ellipse_width = sg2_res_id - sg1_res_id
    # Height is 2 instead of 1,
    # because only the upper half of the ellipse is visible
    ax.add_patch(
        patches.Ellipse(xy=(ellipse_center, 0),
                        width=ellipse_width,
                        height=2,
                        facecolor="None",
                        edgecolor="gold",
                        linewidth=2))
figure.tight_layout()

########################################################################
# Finally, the detected bonds are added to the structure.
# Basically, the removal step above is reversed.

for sg1_index, sg2_index in disulfide_bonds:
    knottin.bonds.add_bond(sg1_index, sg2_index, struc.BondType.SINGLE)
# The structure with added disulfide bonds
# could now be written back into a structure file
# At the moment, Biotite only supports bond input/outpout in MMTF files
#
# strucio.save_structure("structure_with_disulfide_bonds.mmtf", knottin)
Exemple #2
0
def plot_mt(
        T,
        N,
        P,
        size=200,
        plot_zerotrace=True,  # noqa
        x0=0,
        y0=0,
        xy=(0, 0),
        width=200):
    """
    Uses a principal axis T, N and P to draw a beach ball plot.

    :param ax: axis object of a matplotlib figure
    :param T: :class:`~PrincipalAxis`
    :param N: :class:`~PrincipalAxis`
    :param P: :class:`~PrincipalAxis`

    Adapted from ps_tensor / utilmeca.c / `Generic Mapping Tools (GMT)`_.

    .. _`Generic Mapping Tools (GMT)`: https://gmt.soest.hawaii.edu
    """
    # check if one or two widths are specified (Circle or Ellipse)
    try:
        assert (len(width) == 2)
    except TypeError:
        width = (width, width)
    collect = []
    colors = []
    res = [value / float(size) for value in width]
    b = 1
    big_iso = 0
    j = 1
    j2 = 0
    j3 = 0
    n = 0
    azi = np.zeros((3, 2))
    x = np.zeros(400)
    y = np.zeros(400)
    x2 = np.zeros(400)
    y2 = np.zeros(400)
    x3 = np.zeros(400)
    y3 = np.zeros(400)
    xp1 = np.zeros(800)
    yp1 = np.zeros(800)
    xp2 = np.zeros(400)
    yp2 = np.zeros(400)

    a = np.zeros(3)
    p = np.zeros(3)
    v = np.zeros(3)
    a[0] = T.strike
    a[1] = N.strike
    a[2] = P.strike
    p[0] = T.dip
    p[1] = N.dip
    p[2] = P.dip
    v[0] = T.val
    v[1] = N.val
    v[2] = P.val

    vi = (v[0] + v[1] + v[2]) / 3.
    for i in range(0, 3):
        v[i] = v[i] - vi

    radius_size = size * 0.5

    if np.fabs(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) < EPSILON:
        # pure implosion-explosion
        if vi > 0.:
            cir = patches.Ellipse(xy, width=width[0], height=width[1])
            collect.append(cir)
            colors.append('b')
        if vi < 0.:
            cir = patches.Ellipse(xy, width=width[0], height=width[1])
            collect.append(cir)
            colors.append('w')
        return colors, collect

    if np.fabs(v[0]) >= np.fabs(v[2]):
        d = 0
        m = 2
    else:
        d = 2
        m = 0

    if (plot_zerotrace):
        vi = 0.

    f = -v[1] / float(v[d])
    iso = vi / float(v[d])

    # Cliff Frohlich, Seismological Research letters,
    # Vol 7, Number 1, January-February, 1996
    # Unless the isotropic parameter lies in the range
    # between -1 and 1 - f there will be no nodes whatsoever

    if iso < -1:
        cir = patches.Ellipse(xy, width=width[0], height=width[1])
        collect.append(cir)
        colors.append('w')
        return colors, collect
    elif iso > 1 - f:
        cir = patches.Ellipse(xy, width=width[0], height=width[1])
        collect.append(cir)
        colors.append('b')
        return colors, collect

    spd = np.sin(p[d] * D2R)
    cpd = np.cos(p[d] * D2R)
    spb = np.sin(p[b] * D2R)
    cpb = np.cos(p[b] * D2R)
    spm = np.sin(p[m] * D2R)
    cpm = np.cos(p[m] * D2R)
    sad = np.sin(a[d] * D2R)
    cad = np.cos(a[d] * D2R)
    sab = np.sin(a[b] * D2R)
    cab = np.cos(a[b] * D2R)
    sam = np.sin(a[m] * D2R)
    cam = np.cos(a[m] * D2R)

    for i in range(0, 360):
        fir = i * D2R
        s2alphan = (2. + 2. * iso) / \
            float(3. + (1. - 2. * f) * np.cos(2. * fir))
        if s2alphan > 1.:
            big_iso += 1
        else:
            alphan = np.arcsin(np.sqrt(s2alphan))
            sfi = np.sin(fir)
            cfi = np.cos(fir)
            san = np.sin(alphan)
            can = np.cos(alphan)

            xz = can * spd + san * sfi * spb + san * cfi * spm
            xn = can * cpd * cad + san * sfi * cpb * cab + \
                san * cfi * cpm * cam
            xe = can * cpd * sad + san * sfi * cpb * sab + \
                san * cfi * cpm * sam

            if np.fabs(xn) < EPSILON and np.fabs(xe) < EPSILON:
                takeoff = 0.
                az = 0.
            else:
                az = np.arctan2(xe, xn)
                if az < 0.:
                    az += np.pi * 2.
                takeoff = np.arccos(
                    xz / float(np.sqrt(xz * xz + xn * xn + xe * xe)))
            if takeoff > np.pi / 2.:
                takeoff = np.pi - takeoff
                az += np.pi
                if az > np.pi * 2.:
                    az -= np.pi * 2.
            r = np.sqrt(2) * np.sin(takeoff / 2.)
            si = np.sin(az)
            co = np.cos(az)
            if i == 0:
                azi[i][0] = az
                x[i] = x0 + radius_size * r * si
                y[i] = y0 + radius_size * r * co
                azp = az
            else:
                if np.fabs(np.fabs(az - azp) - np.pi) < D2R * 10.:
                    azi[n][1] = azp
                    n += 1
                    azi[n][0] = az
                if np.fabs(np.fabs(az - azp) - np.pi * 2.) < D2R * 2.:
                    if azp < az:
                        azi[n][0] += np.pi * 2.
                    else:
                        azi[n][0] -= np.pi * 2.
                if n == 0:
                    x[j] = x0 + radius_size * r * si
                    y[j] = y0 + radius_size * r * co
                    j += 1
                elif n == 1:
                    x2[j2] = x0 + radius_size * r * si
                    y2[j2] = y0 + radius_size * r * co
                    j2 += 1
                elif n == 2:
                    x3[j3] = x0 + radius_size * r * si
                    y3[j3] = y0 + radius_size * r * co
                    j3 += 1
                azp = az
    azi[n][1] = az

    if v[1] < 0.:
        rgb1 = 'b'
        rgb2 = 'w'
    else:
        rgb1 = 'w'
        rgb2 = 'b'

    cir = patches.Ellipse(xy, width=width[0], height=width[1])
    collect.append(cir)
    colors.append(rgb2)
    if n == 0:
        collect.append(xy2patch(x[0:360], y[0:360], res, xy))
        colors.append(rgb1)
        return colors, collect
    elif n == 1:
        for i in range(0, j):
            xp1[i] = x[i]
            yp1[i] = y[i]
        if azi[0][0] - azi[0][1] > np.pi:
            azi[0][0] -= np.pi * 2.
        elif azi[0][1] - azi[0][0] > np.pi:
            azi[0][0] += np.pi * 2.
        if azi[0][0] < azi[0][1]:
            az = azi[0][1] - D2R
            while az > azi[0][0]:
                si = np.sin(az)
                co = np.cos(az)
                xp1[i] = x0 + radius_size * si
                yp1[i] = y0 + radius_size * co
                i += 1
                az -= D2R
        else:
            az = azi[0][1] + D2R
            while az < azi[0][0]:
                si = np.sin(az)
                co = np.cos(az)
                xp1[i] = x0 + radius_size * si
                yp1[i] = y0 + radius_size * co
                i += 1
                az += D2R
        collect.append(xy2patch(xp1[0:i], yp1[0:i], res, xy))
        colors.append(rgb1)
        for i in range(0, j2):
            xp2[i] = x2[i]
            yp2[i] = y2[i]
        if azi[1][0] - azi[1][1] > np.pi:
            azi[1][0] -= np.pi * 2.
        elif azi[1][1] - azi[1][0] > np.pi:
            azi[1][0] += np.pi * 2.
        if azi[1][0] < azi[1][1]:
            az = azi[1][1] - D2R
            while az > azi[1][0]:
                si = np.sin(az)
                co = np.cos(az)
                xp2[i] = x0 + radius_size * si
                i += 1
                yp2[i] = y0 + radius_size * co
                az -= D2R
        else:
            az = azi[1][1] + D2R
            while az < azi[1][0]:
                si = np.sin(az)
                co = np.cos(az)
                xp2[i] = x0 + radius_size * si
                i += 1
                yp2[i] = y0 + radius_size * co
                az += D2R
        collect.append(xy2patch(xp2[0:i], yp2[0:i], res, xy))
        colors.append(rgb1)
        return colors, collect
    elif n == 2:
        for i in range(0, j3):
            xp1[i] = x3[i]
            yp1[i] = y3[i]
        for ii in range(0, j):
            xp1[i] = x[ii]
            i += 1
            yp1[i] = y[ii]
        if big_iso:
            ii = j2 - 1
            while ii >= 0:
                xp1[i] = x2[ii]
                i += 1
                yp1[i] = y2[ii]
                ii -= 1
            collect.append(xy2patch(xp1[0:i], yp1[0:i], res, xy))
            colors.append(rgb1)
            return colors, collect

        if azi[2][0] - azi[0][1] > np.pi:
            azi[2][0] -= np.pi * 2.
        elif azi[0][1] - azi[2][0] > np.pi:
            azi[2][0] += np.pi * 2.
        if azi[2][0] < azi[0][1]:
            az = azi[0][1] - D2R
            while az > azi[2][0]:
                si = np.sin(az)
                co = np.cos(az)
                xp1[i] = x0 + radius_size * si
                i += 1
                yp1[i] = y0 + radius_size * co
                az -= D2R
        else:
            az = azi[0][1] + D2R
            while az < azi[2][0]:
                si = np.sin(az)
                co = np.cos(az)
                xp1[i] = x0 + radius_size * si
                i += 1
                yp1[i] = y0 + radius_size * co
                az += D2R
        collect.append(xy2patch(xp1[0:i], yp1[0:i], res, xy))
        colors.append(rgb1)

        for i in range(0, j2):
            xp2[i] = x2[i]
            yp2[i] = y2[i]
        if azi[1][0] - azi[1][1] > np.pi:
            azi[1][0] -= np.pi * 2.
        elif azi[1][1] - azi[1][0] > np.pi:
            azi[1][0] += np.pi * 2.
        if azi[1][0] < azi[1][1]:
            az = azi[1][1] - D2R
            while az > azi[1][0]:
                si = np.sin(az)
                co = np.cos(az)
                xp2[i] = x0 + radius_size * si
                i += 1
                yp2[i] = y0 + radius_size * co
                az -= D2R
        else:
            az = azi[1][1] + D2R
            while az < azi[1][0]:
                si = np.sin(az)
                co = np.cos(az)
                xp2[i] = x0 + radius_size * si
                i += 1
                yp2[i] = y0 + radius_size * co
                az += D2R
        collect.append(xy2patch(xp2[0:i], yp2[0:i], res, xy))
        colors.append(rgb1)
        return colors, collect
    # Normalize the first eigenvector
    norm_vec = eigenvectors[0] / np.linalg.norm(eigenvectors[0])

    # Extract the angle of tilt
    angle = np.arctan2(norm_vec[1], norm_vec[0])
    angle = 180 * angle / np.pi

    # Scaling factor to magnify the ellipses
    # (random value chosen to suit our needs)
    scaling_factor = 8
    eigenvalues *= scaling_factor

    # Draw the ellipse
    ellipse = patches.Ellipse(classifier.means_[i, :2],
                              eigenvalues[0],
                              eigenvalues[1],
                              180 + angle,
                              color=color)
    axis_handle = plt.subplot(1, 1, 1)
    ellipse.set_clip_box(axis_handle.bbox)
    ellipse.set_alpha(0.6)
    axis_handle.add_artist(ellipse)

# Plot the data
colors = 'bgr'
for i, color in enumerate(colors):
    cur_data = iris.data[iris.target == i]
    plt.scatter(cur_data[:, 0],
                cur_data[:, 1],
                marker='o',
                facecolors='none',
            ax[k, l].get_xaxis().set_major_formatter(transform)
            ax[k, l].get_yaxis().set_major_formatter(transform)

            ax[-1, l].set_xlabel("$\Delta$RA")

            # Show the size of the beam.

            bmaj = visibilities["image"][j].header["BMAJ"] / \
                    abs(visibilities["image"][j].header["CDELT1"])
            bmin = visibilities["image"][j].header["BMIN"] / \
                    abs(visibilities["image"][j].header["CDELT1"])
            bpa = visibilities["image"][j].header["BPA"]

            ax[k,l].add_artist(patches.Ellipse(xy=(12.5,17.5), \
                    width=bmaj, height=bmin, angle=(bpa+90), \
                    facecolor="white", edgecolor="black"))

            ax[k, l].set_adjustable('box-forced')
            ax[k, 0].set_ylabel("$\Delta$Dec")
            ax[k, l].tick_params(axis='x', labelsize=5)

    # Adjust the plot and save it.

    fig.set_size_inches((16, 5))
    fig.subplots_adjust(left=0.07, right=0.98, top=0.98, bottom=0.15, \
            wspace=0.0,hspace=0.0)

    # Adjust the figure and save.

    fig.savefig("{0}_{1}_{2:s}.pdf".format('Channelplot', args.source,
Exemple #5
0
def main():
    global Y, Ys
    root = Tk()
    root.withdraw()
    file_name = askopenfilename(initialdir='~/Documents/Manip')
    root.destroy()

    data = pandas.DataFrame.from_csv(file_name)

    data['HIST'] = data['HIST'].apply(literal_eval)

    #    for i in range(0, len(data['HIST'])):
    #        plt.figure()
    #        if(data['SUBJ_NB'][i]==0):
    #            plt.title(data['EXP_COND'][i] + ' : ' + data['SUBJ_NAME1'][i])
    #        elif(data['SUBJ_NB'][i]==1):
    #            plt.title(data['EXP_COND'][i] + ' : ' + data['SUBJ_NAME2'][i])
    #        elif(data['SUBJ_NB'][i]==2):
    #            plt.title(data['EXP_COND'][i] + ' : ' + data['SUBJ_NAME1'][i]+'+'+data['SUBJ_NAME2'][i])
    #        plt.plot(np.linspace(-0.75, 1.5, 101), data['HIST'][i])

    tempName = ''
    k = 0

    data_bytrial = pandas.DataFrame(
        data={
            'SUBJ_NB': [],
            'SUBJ_NAME1': [],
            'SUBJ_NAME2': [],
            'EXP_COND': [],
            'HIST': [],
            'TRIAL_NB': [],
            'IS_TRAINING': []
        })

    #Reconstruct a dataframe with one histogram by trial for plotting
    for subj_name1 in list(set(data['SUBJ_NAME1'])):
        subj_name2 = data[data['SUBJ_NAME1'] == subj_name1][
            'SUBJ_NAME2'].reset_index()['SUBJ_NAME2'][0]
        for cond in list(
                set(data[data['SUBJ_NAME1'] == subj_name1]['EXP_COND'])):
            for trial in list(
                    set(data[(data['SUBJ_NAME1'] == subj_name1)
                             & (data['EXP_COND'] == cond)]['TRIAL_NB'])):
                for s in list(
                        set(data[(data['SUBJ_NAME1'] == subj_name1)
                                 & (data['EXP_COND'] == cond) &
                                 (data['TRIAL_NB'] == trial)]['SUBJ_NB'])):
                    df = data[(data['SUBJ_NAME1'] == subj_name1)
                              & (data['EXP_COND'] == cond) &
                              (data['TRIAL_NB'] == trial) &
                              (data['SUBJ_NB'] == s)].reset_index()
                    temp_hist = [0] * 101
                    for i in range(0, len(df)):
                        temp_hist = np.add(temp_hist, df['HIST'][i])
                    if np.sum(temp_hist) != 0:
                        temp_hist = [
                            float(x) / float(np.sum(temp_hist))
                            for x in temp_hist
                        ]
                    else:
                        temp_hist = [float(x) for x in temp_hist]
                    temp_df = pandas.DataFrame(
                        data={
                            'SUBJ_NB': [s],
                            'SUBJ_NAME1': [subj_name1],
                            'SUBJ_NAME2': [subj_name2],
                            'EXP_COND': [cond],
                            'HIST': [temp_hist],
                            'TRIAL_NB': [trial],
                            'IS_TRAINING': [int(df['IS_TRAINING'][0])]
                        })
                    data_bytrial = data_bytrial.append(temp_df,
                                                       ignore_index=True)

    #Plot HIstograms
    colors = [(0, 0, 1), (0, 0, 0.5), (0, 1, 0), (0, 0.5, 0), (1, 0, 0),
              (0.5, 0, 0)]

    for subj_name1 in list(set(data['SUBJ_NAME1'])):
        plt.figure()
        subj_name2 = data_bytrial[data_bytrial['SUBJ_NAME1'] == subj_name1][
            'SUBJ_NAME2'].reset_index()['SUBJ_NAME2'][0]
        plt.suptitle(subj_name1 + ' + ' + subj_name2)
        y_max = 5 * max([
            max(x) for x in data_bytrial[data_bytrial['SUBJ_NAME1'] ==
                                         subj_name1]['HIST']
        ])
        for cond in list(
                set(data_bytrial[data_bytrial['SUBJ_NAME1'] == subj_name1]
                    ['EXP_COND'])):
            for subj_nb in list(
                    set(data_bytrial[(data_bytrial['SUBJ_NAME1'] == subj_name1)
                                     & (data_bytrial['EXP_COND'] == cond)]
                        ['SUBJ_NB'])):
                df = data_bytrial[(data_bytrial['SUBJ_NAME1'] == subj_name1)
                                  & (data_bytrial['EXP_COND'] == cond) &
                                  (data_bytrial['SUBJ_NB']
                                   == subj_nb)].reset_index()

                if (subj_nb == 0):
                    sp_title = cond + ' : ' + subj_name1
                    if (cond == 'ALONE'):
                        k = 1
                    elif (cond == 'HFO'):
                        k = 5
                elif (subj_nb == 1):
                    sp_title = cond + ' : ' + subj_name2
                    if (cond == 'ALONE'):
                        k = 2
                    elif (cond == 'HFO'):
                        k = 6
                elif (subj_nb == 2):
                    sp_title = cond + ' : ' + subj_name1 + '+' + subj_name2
                    if (cond == 'HFOP'):
                        k = 3
                    elif (cond == 'HFO'):
                        k = 7

                ax = plt.subplot(2, 4, k)
                ax.set_title(sp_title)
                plt.axis([-0.75, 1.5, 0, y_max])
                #        plt.plot(np.linspace(-0.75, 1.5, 101), data_bytrial['HIST'][i])
                edges = np.linspace(-0.75, 1.5, 101)
                plt.bar(edges[:-1],
                        df['HIST'][0][:-1],
                        width=np.diff(edges),
                        ec="k",
                        align="edge",
                        color=colors[0])
                for i in range(1, len(df['HIST'])):
                    bottom = [0] * 100
                    for j in range(0, i):
                        bottom = np.add(bottom, df['HIST'][j][:-1])
                    plt.bar(edges[:-1],
                            df['HIST'][i][:-1],
                            bottom=bottom,
                            width=np.diff(edges),
                            ec="k",
                            align="edge",
                            color=colors[i])

        ax = plt.subplot(2, 4, 4)
        ax.set_title("ALONE : Mean both")
        plt.axis([-0.75, 1.5, 0, y_max])
        #        plt.plot(np.linspace(-0.75, 1.5, 101), data_bytrial['HIST'][i])
        edges = np.linspace(-0.75, 1.5, 101)

        df_mix1 = [0] * 6
        df_mix2 = [0] * 6
        df_mix = [0] * 6
        n = len(
            data_bytrial[(data_bytrial['SUBJ_NAME1'] == subj_name1)
                         & (data_bytrial['EXP_COND'] == 'ALONE') &
                         (data_bytrial['SUBJ_NB'] == 0)].reset_index()['HIST'])
        for i in range(0, n):
            df_mix1[i] = data_bytrial[
                (data_bytrial['SUBJ_NAME1'] == subj_name1)
                & (data_bytrial['EXP_COND'] == 'ALONE') &
                (data_bytrial['SUBJ_NB'] == 0)].reset_index()['HIST'][i]
            df_mix2[i] = data_bytrial[
                (data_bytrial['SUBJ_NAME1'] == subj_name1)
                & (data_bytrial['EXP_COND'] == 'ALONE') &
                (data_bytrial['SUBJ_NB'] == 1)].reset_index()['HIST'][i]
            df_mix[i] = [
                float(x) / 2.0 for x in np.add(df_mix1[i], df_mix2[i])
            ]
#            print df_mix1[i]
#            print df_mix2[i]
#            print df_mix[i]
        for i in range(0, n):
            bottom = [0] * 100
            if i != 0:
                for j in range(0, i):
                    bottom = np.add(bottom, df_mix[j][:-1])
            plt.bar(edges[:-1],
                    df_mix[i][:-1],
                    bottom=bottom,
                    width=np.diff(edges),
                    ec="k",
                    align="edge",
                    color=colors[i])

        ax = plt.subplot(2, 4, 8)
        ax.set_title("HFO : Mean both")
        plt.axis([-0.75, 1.5, 0, y_max])
        #        plt.plot(np.linspace(-0.75, 1.5, 101), data_bytrial['HIST'][i])
        edges = np.linspace(-0.75, 1.5, 101)

        df_mix1 = [0] * 6
        df_mix2 = [0] * 6
        df_mix = [0] * 6
        n = len(
            data_bytrial[(data_bytrial['SUBJ_NAME1'] == subj_name1)
                         & (data_bytrial['EXP_COND'] == 'HFO') &
                         (data_bytrial['SUBJ_NB'] == 0)].reset_index()['HIST'])
        for i in range(0, n):
            df_mix1[i] = data_bytrial[
                (data_bytrial['SUBJ_NAME1'] == subj_name1)
                & (data_bytrial['EXP_COND'] == 'HFO') &
                (data_bytrial['SUBJ_NB'] == 0)].reset_index()['HIST'][i]
            df_mix2[i] = data_bytrial[
                (data_bytrial['SUBJ_NAME1'] == subj_name1)
                & (data_bytrial['EXP_COND'] == 'HFO') &
                (data_bytrial['SUBJ_NB'] == 1)].reset_index()['HIST'][i]
            df_mix[i] = [
                float(x) / 2.0 for x in np.add(df_mix1[i], df_mix2[i])
            ]
#            print df_mix1[i]
#            print df_mix2[i]
#            print df_mix[i]
        for i in range(0, n):
            bottom = [0] * 100
            if i != 0:
                for j in range(0, i):
                    bottom = np.add(bottom, df_mix[j][:-1])
            plt.bar(edges[:-1],
                    df_mix[i][:-1],
                    bottom=bottom,
                    width=np.diff(edges),
                    ec="k",
                    align="edge",
                    color=colors[i])

    df_al = data_bytrial[data_bytrial['EXP_COND'] == 'ALONE']
    n = len(df_al[(df_al['SUBJ_NAME1'] == df_al['SUBJ_NAME1'][0])
                  & (df_al['SUBJ_NB'] == 0)])

    data_D = pandas.DataFrame(data={
        'TRIAL_NB': [],
        'SUBJ_NAME': [],
        'HIST': []
    })
    for i in range(0, n):
        print i
        for subj_name1 in list(set(df_al['SUBJ_NAME1'])):
            print subj_name1
            subj_name2 = df_al[df_al['SUBJ_NAME1'] == subj_name1][
                'SUBJ_NAME2'].reset_index()['SUBJ_NAME2'][0]
            for k in range(0, 2):
                if k == 0:
                    try:
                        tempdf = pandas.DataFrame(
                            data={
                                'TRIAL_NB': [i],
                                'SUBJ_NAME': [subj_name1],
                                'HIST': [
                                    df_al[(df_al['SUBJ_NAME1'] == subj_name1)
                                          & (df_al['SUBJ_NB'] == k)].
                                    reset_index()['HIST'][i]
                                ]
                            })
                    except:
                        tempdf = pandas.DataFrame(
                            data={
                                'TRIAL_NB': [i],
                                'SUBJ_NAME': [subj_name1],
                                'HIST': [[0.0] * 101]
                            })
                    data_D = data_D.append(tempdf, ignore_index=True)
                elif k == 1:
                    try:
                        tempdf = pandas.DataFrame(
                            data={
                                'TRIAL_NB': [i],
                                'SUBJ_NAME': [subj_name2],
                                'HIST': [
                                    df_al[(df_al['SUBJ_NAME2'] == subj_name2)
                                          & (df_al['SUBJ_NB'] == k)].
                                    reset_index()['HIST'][i]
                                ]
                            })
                    except:
                        tempdf = pandas.DataFrame(
                            data={
                                'TRIAL_NB': [i],
                                'SUBJ_NAME': [subj_name2],
                                'HIST': [[0.0] * 101]
                            })
                    data_D = data_D.append(tempdf, ignore_index=True)

    print data_D

    ns = len(list(set(data_D['SUBJ_NAME'])))
    subj_names = list(set(data_D['SUBJ_NAME']))
    D = np.zeros((ns, ns))
    Y = [0] * n
    bins = np.linspace(-0.75, 1.5, 101)
    bin_width = bins[1] - bins[0]
    max_emd = 2.25
    plt.figure()
    a = plt.subplot(111)
    plt.axis('equal')
    colors = [(0, 0, 1), (0, 0, 0.5), (0, 1, 0), (0, 0.5, 0), (1, 0, 0),
              (0.5, 0, 0), (1, 0, 1), (0.5, 0, 0.5), (0, 1, 1), (0, 0.5, 0.5),
              (1, 1, 0), (0.5, 0.5, 0), (1, 1, 1), (0.5, 0.5, 0.5)]
    norm = plt.Normalize()
    colors = cm.jet(norm(range(ns)))
    for i in range(0, n):
        tempdf = data_D[data_D['TRIAL_NB'] == i].reset_index()
        for j in range(0, ns):
            for k in range(0, ns):
                h1 = tempdf['HIST'][j]
                h2 = tempdf['HIST'][k]
                if j == k:
                    D[j][k] = 0
                else:
                    D[j][k] = sum(abs(np.cumsum(h1) -
                                      np.cumsum(h2))) * bin_width / max_emd

        tempY, e = cmdscale(D)
        Y[i] = tempY[:, 0:2]

#        for l in range(0, len(Y)):
#            plt.plot(Y[i][l][0], Y[i][l][1], '+', markersize=8, mew=2, color=colors[i])

    Ys = []
    for i in range(0, ns):
        Ys.append(np.zeros((n, 2)))

    for i in range(0, n):
        for j in range(0, ns):
            #            print Ys[j][i,:]
            Ys[j][i, :] = Y[i][j, :]

    for i in range(0, ns):
        COV = np.cov(Ys[i], rowvar=0)

        CX = np.mean(Ys[i], axis=0)[0]
        CY = np.mean(Ys[i], axis=0)[1]
        #        print Ys[i]
        for j in range(0, n):
            #            print Ys[i][j,0], Ys[i][j,1]
            plt.plot(Ys[i][j, 0],
                     Ys[i][j, 1],
                     '+',
                     markersize=8,
                     mew=2,
                     color=colors[i])
        plt.plot(CX, CY, 'o', markersize=8, mew=2, color=colors[i])
        plt.text(CX, CY, subj_names[i], color=colors[i])

        eigval, eigvec = np.linalg.eigh(COV)

        #        print ""
        #        print eigval
        #        print eigvec
        #        print "\n"

        V1 = eigvec[:][1]
        V2 = eigvec[:][0]
        lmb1 = eigval[1]
        lmb2 = eigval[0]
        s = 4.605  #5.991
        l1 = 2 * np.sqrt(5.991 * lmb1)
        l2 = 2 * np.sqrt(5.991 * lmb2)
        alpha = 180 / pi * np.arctan(V1[1] / V1[0])

        e = mpatches.Ellipse((CX, CY), l1, l2, alpha, color=colors[i])
        e.set_clip_box(a.bbox)
        e.set_alpha(0.1)
        a.add_artist(e)

    plt.show()
    quit()
Exemple #6
0
def draw_ellipse(fig, ax, x, y, w, h, a, fillcolor):
    e = patches.Ellipse(xy=(x, y), width=w, height=h, angle=a, color=fillcolor)
    ax.add_patch(e)
def image_moments(data, semiaxis_a, semiaxis_b):

    global radius0
    radius0 = (semiaxis_a + semiaxis_b) / 2
    global semi_a0, semi_b0
    semi_a0 = int(2 * semiaxis_a)
    semi_b0 = int(2 * semiaxis_b)
    print "Inital mask radius: ", radius0
    h, v = data.shape[:2]
    global step
    step = int((h / 2 - max(semi_a0, semi_b0)) / m)
    print "Step size is: ", step

    #Retrieve cov(R) data
    cov_array = covR(data)
    #Find the image center-of-mass
    xbar, ybar, cov = image_raw_moments(data)
    center = [xbar, ybar]

    p2x, p2y = imtl.ImageFit(data, 1.0)
    print "Image center is at: ", p2x[0], p2y[0]
    center = [p2x[0], p2y[0]]
    #    ellipse = data.copy()
    #    mask_ellipse = create_elliptical_mask(h,v,center,radius0,3*radius0,45.0)
    #    ellipse[~mask_ellipse] = 0
    #    plt.figure()
    #    plt.imshow(ellipse)
    #    plt.show()

    #Calculate the correct radii for <xx>,<yy> and <xy> moments. The condition is min(d covR(R) / dR)
    #    m = len(cov_array)
    #Retrieve the positions of max(d covR(R) / dR)
    #    nx, ny, nxy = dcov_array_max(cov_array)
    #Radius is calculated as the location of derivative minimum
    #    radiusX = radius0 + step*np.argmin(np.gradient(cov_array[nx:m-1,0])) + step*nx
    #    radiusY = radius0 + step*np.argmin(np.gradient(cov_array[ny:m-1,3])) + step*ny
    #    radiusXY = radius0 + step*np.argmin(np.abs(np.gradient(cov_array[nxy:m-1,1]))) + step*nxy

    minx, miny, minxy = dcov_array_min(cov_array)

    semi_aX = semi_a0 + step * minx
    semi_bX = semi_b0 + step * minx
    semi_aY = semi_a0 + step * miny
    semi_bY = semi_b0 + step * miny
    semi_aXY = semi_a0 + step * minxy
    semi_bXY = semi_b0 + step * minxy

    print "Mask ellipse X: ", semi_aX, semi_bX
    print "Mask ellipse Y: ", semi_aY, semi_bY
    print "Mask ellipse XY: ", semi_aXY, semi_bXY
    #Plotting covariance matrix elements for debugging
    plot_covarray(cov_array)
    #Create masks for <xx>,<yy> and <xy> moments
    maskX = create_elliptical_mask(h, v, center, semi_aX, semi_bX, skew)
    maskY = create_elliptical_mask(h, v, center, semi_aY, semi_bY, skew)
    maskXY = create_elliptical_mask(h, v, center, semi_aXY, semi_bXY, skew)
    #Prepare three copies of masked data for final moments calculation
    tempX = data.copy()
    tempY = data.copy()
    tempXY = data.copy()
    tempX[~maskX] = 0
    tempY[~maskY] = 0
    tempXY[~maskXY] = 0
    #    plt.figure()

    fig, ax = plt.subplots(1)
    extent = (0, len(tempXY[:, 0]), 0, len(tempXY[:, 1]))
    tempXY = np.flip(tempXY, 0)
    ax.imshow(imtl.Normalize(tempXY), extent=extent)
    cx = patches.Ellipse(center,
                         2 * semi_aX,
                         2 * semi_bX,
                         skew,
                         color='y',
                         linewidth=3,
                         fill=False)
    cy = patches.Ellipse(center,
                         2 * semi_aY,
                         2 * semi_bY,
                         skew,
                         color='g',
                         linewidth=3,
                         fill=False)
    cxy = patches.Ellipse(center,
                          2 * semi_aXY,
                          2 * semi_bXY,
                          skew,
                          color='m',
                          linewidth=3,
                          fill=False)
    ax.add_patch(cx)
    ax.add_patch(cy)
    ax.add_patch(cxy)
    plt.legend((cx, cy, cxy),
               (r'Mask $\langle xx \rangle$', r'Mask $\langle yy\rangle$',
                r'Mask $\langle xy\rangle$'))
    plt.xlabel('x (px)')
    plt.ylabel('y (px)')
    plt.tight_layout()
    plt.show()

    #Final calculation
    xxt, yyt, covx = image_raw_moments(tempX)
    xxt, yyt, covy = image_raw_moments(tempY)
    xxt, yyt, covxy = image_raw_moments(tempXY)

    return covx[0, 0], covy[1, 1], covxy[0, 1]
            ax.plot(df_mean_std['mu_time'].values,
                    df_mean_std['mu_error'].values,
                    label=method_name_bypass,
                    color=methods[method_name][3],
                    linestyle=methods[method_name][4],
                    marker=methods[method_name][5])

            for i in [
                    df_mean_std.index[0], df_mean_std.index[1],
                    df_mean_std.index[-1]
            ]:
                el = mpatches.Ellipse(
                    (df_mean_std['mu_time'][i], df_mean_std['mu_error'][i]),
                    df_mean_std['std_time'][i],
                    df_mean_std['std_error'][i],
                    angle=0,
                    alpha=0.2,
                    color=methods[method_name][3],
                    linewidth=None)
                ax.add_artist(el)

        ax.set_title('Time error for HOM(2)', fontdict=font_top)
        ax.legend(loc='upper right', shadow=True, prop=legend_prop)

        ax.xaxis.grid(True,
                      linestyle='-',
                      which='major',
                      color='lightgrey',
                      alpha=0.5)
        ax.yaxis.grid(True,
                      linestyle='-',
Exemple #9
0
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.transforms as transforms

fig, ax = plt.subplots()
xdata, ydata = (0.2, 0.7), (0.5, 0.5)
ax.plot(xdata, ydata, "o", color='r', ms=15)
ax.set_xlim((0, 1))

trans = (fig.dpi_scale_trans +
         transforms.ScaledTranslation(xdata[0], ydata[0], ax.transData))

# 围绕数据点画一个长短轴为150x130点(这里“点”是长度单位,72点为1英寸)的椭圆
circle = mpatches.Ellipse((0, 0),
                          150 / 72,
                          130 / 72,
                          angle=40,
                          fill=None,
                          transform=trans,
                          lw=5,
                          color='b')
ax.add_patch(circle)
plt.show()
Exemple #10
0
# ==================================================
# initialize the objects
fig2 = plt.figure(figsize=(6,6))
axes1 = plt.subplot(1,1,1)

axes1.plot(temp_C,humidity,'b-')
axes1.set_xlabel('T, temperature [C]')
axes1.set_ylabel('H, humidity [%]')


# here we are using the class above to scale the ellipse axes to the data so they are round dots.
rad_pix = 20
dot1_width = graphDist.GraphDist(rad_pix, axes1, True)
dot1_height = graphDist.GraphDist(rad_pix, axes1, False)
patch1 = patches.Ellipse((temp_C[0], humidity[0]), dot1_width, dot1_height, fc='red')

# ===================================================
# initialize what will move in the animation
def init():
    patch1.center = (temp_C[0], humidity[0])
    axes1.add_patch(patch1)
    return patch1

# ===================================================
# define what will move in the animation
def animate(i): # is this (i) needed for the animate function
    x , y = temp_C[i], humidity[i]
    patch1.center = (x , y)
    axes1.add_patch(patch1)
    return patch1,
        amaj.append(float(lineSplit[3]))
        amin.append(float(lineSplit[4]))
        phi.append(float(lineSplit[5]))

for ii in range(len(names)):

    idsFile = os.path.join(idsDir, "%d.hdf5" % (ii))
    if not os.path.isfile(idsFile):

        ra, dec, radius = ras[ii], decs[ii], errs[ii]

        if dec < -30: continue
        if np.isnan(radius): continue
        print(ii, ra, dec, radius, amaj[ii], amin[ii])

        ellipse = patches.Ellipse((ra, dec), amaj[ii], amin[ii], angle=phi[ii])

        qu = {
            "query_type": "cone_search",
            "query": {
                "object_coordinates": {
                    "radec": {
                        'test': [ra, dec]
                    },
                    "cone_search_radius": "%.2f" % radius,
                    "cone_search_unit": "arcsec"
                },
                "catalogs": {
                    "PS1_DR1": {
                        "filter": "{}",
                        "projection": "{'_id': 1, 'raMean': 1, 'decMean': 1}"
ax.set_xlim(px.min(), px.max())
ax.set_ylim(py.min(), py.max())
ax.add_artist(p)
plt.show()
# -

# ## Ellipse

xy_center = [0, 0]
fig = plt.figure()
ax = plt.gca()
ax.set_aspect('equal')
plt.plot(xy_center[0], xy_center[1], marker='o', color='k', linestyle='none')
p = patch.Ellipse(xy_center,
                  height=5,
                  width=10,
                  angle=45,
                  fill=True,
                  linewidth=2)
ax.set_xlim(-10, 10)
ax.set_ylim(-5, 5)
ax.add_artist(p)
plt.show()

# ## Circles

# +
xy_center = [0, 0]

plt.figure()
ax = plt.gca()
ax.set_aspect('equal', 'box')
Exemple #13
0
def info_boxplot(ax,
                 data,
                 median_linestyle='solid',
                 median_linewidth=1,
                 median_color='black',
                 upper_whisker_linestyle='solid',
                 upper_whisker_linewidth=1,
                 upper_whisker_color='black',
                 lower_whisker_linestyle='solid',
                 lower_whisker_linewidth=1,
                 lower_whisker_color='black',
                 outliers_color='gray',
                 outliers_linecolor='black',
                 box_facecolor='white',
                 box_linestyle='solid',
                 box_linewidth=1,
                 box_linecolor='black',
                 multiplebox=True,
                 show_outliers=True):
    count = 0

    if type(data[0]) != list:
        print(
            "Warning:Please input the data with format: lists in a list   Example: [[1,2,3,4], [5,6,7,8], [9,10,11,12]] "
        )
        data = [data]
    #Find the maximum and minimum values ​​in all data to determine the scale range of the axis

    z_max_list = []
    z_min_list = []
    x_range_list = []
    y_range_list = []
    for z in data:
        z_max = max(z)
        z_max_list.append(z_max)
        z_min = min(z)
        z_min_list.append(z_min)
    max_range = max(z_max_list)
    min_range = min(z_min_list)

    for z in data:
        z.sort()
        #print(z)
        # Determine the position of each Q line in the data set
        n = len(z)
        d = float(0)
        Q_position = []
        for i in np.arange(11):
            q = (n + 1) * (0.25 + d)
            Q_position.append(q)
            d += 0.05
        # print(Q_position)

        # Determine the value of the Q line
        result = []
        for i in Q_position:
            if math.modf(i)[0] == 0.0:
                Q_value = z[int(i) - 1]
                result.append(Q_value)
            else:
                x = math.modf(i)
                Q_value = (x[0] * z[int(x[1])]) + (1 - x[0]) * z[int(x[1] - 1)]
                result.append(Q_value)
        # print(result)

        # Calculate upper and lower bounds and outliers
        Q1 = result[0]
        Q3 = result[10]
        IQR = Q3 - Q1
        upper_fence = Q3 + 1.5 * IQR
        low_fence = Q1 - 1.5 * IQR
        result.sort()

        low_outlier = []
        upper_outlier = []
        for i in z:
            if i < low_fence:
                low_outlier.append(i)
            if i > upper_fence:
                upper_outlier.append(i)
        if len(low_outlier) == 0:
            result.append(z[0])
        else:
            result.append(low_fence)
        if len(upper_outlier) == 0:
            result.append(z[-1])
        else:
            result.append(upper_fence)

        # Determine the scale range of the X coordinate axis according to the number of box plots
        result.sort()
        x_range = max(result)
        x_range_list.append(x_range)
        real_x_range = max(x_range_list)
        y_range = min(result)
        y_range_list.append(y_range)
        real_y_range = max(y_range_list)
        if show_outliers == True:
            if y_range < 0:
                ax.set_ylim((1.2 * min_range, 1.2 * max_range))
            else:
                ax.set_ylim((0, 1.2 * max_range))
        else:
            if y_range < 0:
                ax.set_ylim((1.2 * real_y_range, 1.2 * real_x_range))
            else:
                ax.set_ylim((0, 1.2 * real_x_range))
        ax.set_xlim(0, 40 * len(data))

        # Use rectangles to generate boxes and paint them
        x = 14 + 40 * count
        ax.add_patch(
            patches.Rectangle((x, result[1]),
                              12, (result[11] - result[1]),
                              facecolor=box_facecolor,
                              edgecolor='white'))

        # Draw the whiskers and the line between the box and the whiskers
        a = 1
        for i in result:
            x = 14 + 40 * count
            y = 26 + 40 * count
            if a == 1:
                x = 17 + 40 * count
                y = 23 + 40 * count
                line = mlines.Line2D([x, y], [i, i],
                                     color=lower_whisker_color,
                                     linestyle=lower_whisker_linestyle,
                                     linewidth=lower_whisker_linewidth)
                ax.add_line(line)
            elif a == len(result):
                x = 17 + 40 * count
                y = 23 + 40 * count
                line = mlines.Line2D([x, y], [i, i],
                                     color=upper_whisker_color,
                                     linestyle=upper_whisker_linestyle,
                                     linewidth=upper_whisker_linewidth)
                ax.add_line(line)
            elif a == 7:
                line = mlines.Line2D([x, y], [i, i],
                                     color=median_color,
                                     linestyle=median_linestyle,
                                     linewidth=median_linewidth)
                ax.add_line(line)
            elif a == 2 or a == 12:
                line = mlines.Line2D([x, y], [i, i],
                                     color=box_linecolor,
                                     linestyle=box_linestyle,
                                     linewidth=box_linewidth)
                ax.add_line(line)
            else:
                if multiplebox == True:
                    line = mlines.Line2D([x, y], [i, i], color='black')
                    ax.add_line(line)
            a += 1

        x = 20 + 40 * count
        y = 14 + 40 * count
        f = 26 + 40 * count
        line_ver1 = mlines.Line2D([x, x], [result[0], result[1]],
                                  color=box_linecolor,
                                  linestyle=box_linestyle,
                                  linewidth=box_linewidth)
        ax.add_line(line_ver1)
        line_ver2 = mlines.Line2D([x, x], [result[-1], result[11]],
                                  color=box_linecolor,
                                  linestyle=box_linestyle,
                                  linewidth=box_linewidth)
        ax.add_line(line_ver2)
        line_ver3 = mlines.Line2D([y, y], [result[11], result[1]],
                                  color=box_linecolor,
                                  linestyle=box_linestyle,
                                  linewidth=box_linewidth)
        ax.add_line(line_ver3)
        line_ver4 = mlines.Line2D([f, f], [result[11], result[1]],
                                  color=box_linecolor,
                                  linestyle=box_linestyle,
                                  linewidth=box_linewidth)
        ax.add_line(line_ver4)

        # Draw outliers
        if show_outliers == True:
            for i in upper_outlier:
                x = 20 + 40 * count
                height = max_range / 100
                ax.add_patch(
                    patches.Ellipse((x, i),
                                    2,
                                    height,
                                    facecolor=outliers_color,
                                    edgecolor=outliers_linecolor))

            for i in low_outlier:
                x = 20 + 40 * count
                height = max_range / 100
                ax.add_patch(
                    patches.Ellipse((x, i),
                                    2,
                                    height,
                                    facecolor=outliers_color,
                                    edgecolor=outliers_linecolor))
        count += 1

    plt.xticks([])
    plt.show()
Exemple #14
0
def creative_boxplot(ax,
                     data,
                     median_linestyle='solid',
                     median_linewidth=1,
                     median_color='black',
                     upper_whisker_linestyle='solid',
                     upper_whisker_linewidth=1,
                     upper_whisker_color='black',
                     lower_whisker_linestyle='solid',
                     lower_whisker_linewidth=1,
                     lower_whisker_color='black',
                     outliers_color='gray',
                     outliers_linecolor='black',
                     box_facecolor='white',
                     box_linestyle='solid',
                     box_linewidth=1,
                     box_linecolor='black',
                     gradient_gray=True,
                     gradient_color=(0.1, 0.7, 0.7),
                     multiplebox=False,
                     show_outliers=True):
    count = 0
    if type(data[0]) != list:
        print(
            "Warning:Please input the data with format: lists in a list   Example: [[1,2,3,4], [5,6,7,8], [9,10,11,12]] "
        )
        data = [data]
    # Find the maximum and minimum values ​​in all data to determine the scale range of the axis
    z_max_list = []
    z_min_list = []
    x_range_list = []
    y_range_list = []
    for z in data:
        z_max = max(z)
        z_max_list.append(z_max)
        z_min = min(z)
        z_min_list.append(z_min)
    max_range = max(z_max_list)
    min_range = min(z_min_list)

    for z in data:
        z.sort()
        # print(z)

        # Determine the position of each Q line in the data set
        n = len(z)
        d = float(0)
        Q_position = []
        for i in np.arange(11):
            q = (n + 1) * (0.25 + d)
            Q_position.append(q)
            d += 0.05
        # print(Q_position)

        # Determine the value of each Q line
        result = []
        for i in Q_position:
            if math.modf(i)[0] == 0.0:
                Q_value = z[int(i) - 1]
                result.append(Q_value)
            else:
                x = math.modf(i)
                Q_value = (x[0] * z[int(x[1])]) + (1 - x[0]) * z[int(x[1] - 1)]
                result.append(Q_value)
        # print(result)

        # Calculate upper and lower bounds and outliers
        Q1 = result[0]
        Q3 = result[10]
        IQR = Q3 - Q1
        upper_fence = Q3 + 1.5 * IQR
        low_fence = Q1 - 1.5 * IQR
        result.sort()

        low_outlier = []
        upper_outlier = []
        for i in z:
            if i < low_fence:
                low_outlier.append(i)
            if i > upper_fence:
                upper_outlier.append(i)
        if len(low_outlier) == 0:
            result.append(z[0])
        else:
            result.append(low_fence)
        if len(upper_outlier) == 0:
            result.append(z[-1])
        else:
            result.append(upper_fence)

        # Determine the scale range of the X coordinate axis according to the number of box plots
        result.sort()
        x_range = max(result)
        x_range_list.append(x_range)
        real_x_range = max(x_range_list)
        y_range = min(result)
        y_range_list.append(y_range)
        real_y_range = max(y_range_list)
        if show_outliers == True:
            if y_range < 0:
                ax.set_ylim((1.2 * min_range, 1.2 * max_range))
            else:
                ax.set_ylim((0, 1.2 * max_range))
        else:
            if y_range < 0:
                ax.set_ylim((1.2 * real_y_range, 1.2 * real_x_range))
            else:
                ax.set_ylim((0, 1.2 * real_x_range))
        ax.set_xlim(0, 40 * len(data))

        # Judge if the user want to use the creative idea
        if gradient_gray == False:
            x = 14 + 40 * count
            ax.add_patch(
                patches.Rectangle((x, result[1]),
                                  12, (result[11] - result[1]),
                                  facecolor=box_facecolor,
                                  edgecolor='white'))

        if gradient_gray == True:
            step = (result[11] - result[1]) / 20
            step_ini = 0
            step_list = []
            for i in np.arange(21):
                step_list.append(step_ini)
                step_ini = step_ini + step
            # print(step_list)
            new_z = []
            for i in z:
                if low_fence < i < upper_fence:
                    new_z.append(i)
            # print(new_z)
            step_count = 0
            new_z_count = 0

            histo = [0 for makezero in range(20)]
            #print(histo)

            for i in np.arange(10000):
                if step_count == 20 or new_z_count == len(new_z):
                    break
                if step_list[step_count] <= new_z[new_z_count] < step_list[
                        step_count + 1]:
                    histo[step_count] += 1
                    # print(histo)
                    new_z_count += 1
                    # print(new_z_count)
                else:
                    step_count += 1
                    # print(step_count)
            # print(histo)
            for i in np.arange(len(histo)):
                histo[i] = (histo[i] / len(new_z)) * 100
            colorlist = []
            for i in histo:
                temp1 = 0.1 * i
                temp2 = float(temp1)
                if temp2 >= 1:
                    temp2 = 1
                colorlist.append(temp2)
            # print(colorlist)
            gradientcolor_list = []
            for j in gradient_color:
                gradientcolor_list.append(j)
            # print(gradientcolor_list)
            for i in np.arange(len(histo)):
                x = 14 + 40 * count
                z = result[1] + step * i
                ax.add_patch(
                    patches.Rectangle(
                        (x, z),
                        12,
                        step,
                        edgecolor='white',
                        linewidth=0,
                        facecolor=(gradientcolor_list[0],
                                   gradientcolor_list[1],
                                   gradientcolor_list[2], colorlist[i])))

        a = 1
        for i in result:
            x = 14 + 40 * count
            y = 26 + 40 * count
            if a == 1:
                x = 17 + 40 * count
                y = 23 + 40 * count
                line = mlines.Line2D([x, y], [i, i],
                                     color=lower_whisker_color,
                                     linestyle=lower_whisker_linestyle,
                                     linewidth=lower_whisker_linewidth)
                ax.add_line(line)
            elif a == len(result):
                x = 17 + 40 * count
                y = 23 + 40 * count
                line = mlines.Line2D([x, y], [i, i],
                                     color=upper_whisker_color,
                                     linestyle=upper_whisker_linestyle,
                                     linewidth=upper_whisker_linewidth)
                ax.add_line(line)
            elif a == 7:
                line = mlines.Line2D([x, y], [i, i],
                                     color=median_color,
                                     linestyle=median_linestyle,
                                     linewidth=median_linewidth)
                ax.add_line(line)
            elif a == 2 or a == 12:
                line = mlines.Line2D([x, y], [i, i],
                                     color=box_linecolor,
                                     linestyle=box_linestyle,
                                     linewidth=box_linewidth)
                ax.add_line(line)
            else:
                if multiplebox == True:
                    line = mlines.Line2D([x, y], [i, i])
                    ax.add_line(line)
            a += 1

        x = 20 + 40 * count
        y = 14 + 40 * count
        f = 26 + 40 * count
        line_ver1 = mlines.Line2D([x, x], [result[0], result[1]],
                                  color=box_linecolor,
                                  linestyle=box_linestyle,
                                  linewidth=box_linewidth)
        ax.add_line(line_ver1)
        line_ver2 = mlines.Line2D([x, x], [result[-1], result[11]],
                                  color=box_linecolor,
                                  linestyle=box_linestyle,
                                  linewidth=box_linewidth)
        ax.add_line(line_ver2)
        line_ver3 = mlines.Line2D([y, y], [result[11], result[1]],
                                  color=box_linecolor,
                                  linestyle=box_linestyle,
                                  linewidth=box_linewidth)
        ax.add_line(line_ver3)
        line_ver4 = mlines.Line2D([f, f], [result[11], result[1]],
                                  color=box_linecolor,
                                  linestyle=box_linestyle,
                                  linewidth=box_linewidth)
        ax.add_line(line_ver4)

        if show_outliers == True:
            for i in upper_outlier:
                x = 20 + 40 * count
                height = max_range / 100
                ax.add_patch(
                    patches.Ellipse((x, i),
                                    2,
                                    height,
                                    facecolor=outliers_color,
                                    edgecolor=outliers_linecolor))

            for i in low_outlier:
                x = 20 + 40 * count
                height = max_range / 100
                ax.add_patch(
                    patches.Ellipse((x, i),
                                    2,
                                    height,
                                    facecolor=outliers_color,
                                    edgecolor=outliers_linecolor))
        count += 1

    plt.xticks([])
    plt.show()
Exemple #15
0
    def patches(self, **kwargs):
        """
        :return: list of (a single) :class:`~matplotlib.patches.Patch` corresponding to entity
        :note: this is the only method that needs to be overridden in descendants for draw, render and IPython _repr_xxx_ to work
        """
        import matplotlib.patches as patches
        from matplotlib.path import Path

        kwargs.setdefault('color', self.color)
        try:
            kwargs.setdefault('linewidth', self.width)
        except:
            pass

        try:
            kwargs.setdefault('fill', self.fill)
        except:
            pass

        if isinstance(self, Segment2):
            path = Path((self.start.xy, self.end.xy),
                        [Path.MOVETO, Path.LINETO])
            return [patches.PathPatch(path, **kwargs)]

        if isinstance(self, Arc2):
            theta1 = degrees(self.a)
            theta2 = degrees(self.b)
            if self.dir < 1:  #swap
                theta1, theta2 = theta2, theta1
            d = self.r * 2
            return [
                patches.Arc(self.c.xy,
                            d,
                            d,
                            theta1=theta1,
                            theta2=theta2,
                            **kwargs)
            ]

        #entities below may be filled, so let's handle the color first
        color = kwargs.pop('color')
        kwargs.setdefault('edgecolor', color)
        kwargs.setdefault('fill', isinstance(self, Point2))
        if type(kwargs['fill']) is not bool:  #assume it's the fill color
            kwargs.setdefault('facecolor', kwargs['fill'])
            kwargs['fill'] = True
        kwargs.setdefault('facecolor', color)

        if isinstance(self, Point2):
            try:
                ms = self.width
            except:
                ms = 0.01
            kwargs.setdefault('clip_on', False)
            return [patches.Circle(self.xy, ms, **kwargs)]
        if isinstance(self, Spline):
            path = Path(self.xy,
                        [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4])
            return [patches.PathPatch(path, **kwargs)]

        if isinstance(self, Ellipse):  #must be after Arc2 and Ellipse
            return [
                patches.Ellipse(self.c.xy, 2 * self.r, 2 * self.r2, **kwargs)
            ]
        if isinstance(self, Circle):  #must be after Arc2 and Ellipse
            return [patches.Circle(self.c.xy, self.r, **kwargs)]

        raise NotImplementedError
Exemple #16
0
    x = x_ref_1 + (i_frame - frame_ref_1) * (x_ref_2 - x_ref_1) / (
        frame_ref_2 - frame_ref_1)

    x_witness = x - witness_delay

    figsize = (8, 8. * img.shape[0] / img.shape[1])

    plt.close('all')

    fig1 = plt.figure(1, figsize=figsize)
    ax = plt.subplot(1, 1, 1)
    ax.axis('off')
    ax.imshow(img)
    # plt.plot([x-L/2, x+L/2], [y, y], '-r', linewidth=5)
    ax.add_patch(mp.Ellipse((x, y), height=10, width=L, alpha=.8, color='r'))
    if flag_witness:
        ax.add_patch(mp.Ellipse((x_witness, y), height=10, width=L, alpha=.8))
    ax.axis('tight')
    ax.set_xlim(left=0., right=800.)

    fig1.subplots_adjust(bottom=0, top=1., left=0., right=1.)
    fig1.savefig(fname.split('.png')[0] + '_modif.png',
                 dpi=90,
                 bbox_inches='tight')

plt.show()

import os
os.system(
    'ffmpeg -i photograms_illustration/f%04d_modif.png -c:v libx264 -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2,setpts=3.0*PTS"  -profile:v high -level:v 4.0 -pix_fmt yuv420p -crf 22 -codec:a aac Output.mp4'
Exemple #17
0
def plot_gate_map(backend,
                  figsize=None,
                  plot_directed=False,
                  label_qubits=True,
                  qubit_size=24,
                  line_width=4,
                  font_size=12,
                  qubit_color=None,
                  qubit_labels=None,
                  line_color=None,
                  font_color='w',
                  ax=None):
    """Plots the gate map of a device.

    Args:
        backend (BaseBackend): A backend instance,
        figsize (tuple): Output figure size (wxh) in inches.
        plot_directed (bool): Plot directed coupling map.
        label_qubits (bool): Label the qubits.
        qubit_size (float): Size of qubit marker.
        line_width (float): Width of lines.
        font_size (int): Font size of qubit labels.
        qubit_color (list): A list of colors for the qubits
        qubit_labels (list): A list of qubit labels
        line_color (list): A list of colors for each line from coupling_map.
        font_color (str): The font color for the qubit labels.
        ax (Axes): A Matplotlib axes instance.

    Returns:
        Figure: A Matplotlib figure instance.

    Raises:
        QiskitError: if tried to pass a simulator.
        ImportError: if matplotlib not installed.
    """
    if not HAS_MATPLOTLIB:
        raise ImportError('Must have Matplotlib installed.')

    if backend.configuration().simulator:
        raise QiskitError('Requires a device backend, not simulator.')

    input_axes = False
    if ax:
        input_axes = True

    mpl_data = {}

    mpl_data[20] = [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1],
                    [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 2], [2, 3],
                    [2, 4], [3, 0], [3, 1], [3, 2], [3, 3], [3, 4]]

    mpl_data[14] = [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6],
                    [1, 7], [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1]]

    mpl_data[16] = [[1, 0], [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5],
                    [0, 6], [0, 7], [1, 7], [1, 6], [1, 5], [1, 4], [1, 3],
                    [1, 2], [1, 1]]

    mpl_data[5] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]]

    mpl_data[53] = [[0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6],
                    [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6],
                    [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1],
                    [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8],
                    [5, 2], [5, 6], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4],
                    [6, 5], [6, 6], [6, 7], [6, 8], [7, 0], [7, 4], [7, 8],
                    [8, 0], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6],
                    [8, 7], [8, 8], [9, 2], [9, 6]]

    config = backend.configuration()
    n_qubits = config.n_qubits
    cmap = config.coupling_map

    if qubit_labels is None:
        qubit_labels = list(range(n_qubits))
    else:
        if len(qubit_labels) != n_qubits:
            raise QiskitError('Length of qubit labels '
                              'does not equal number '
                              'of qubits.')

    if n_qubits in mpl_data.keys():
        grid_data = mpl_data[n_qubits]
    else:
        if not input_axes:
            fig, ax = plt.subplots(figsize=(5, 5))  # pylint: disable=invalid-name
            ax.axis('off')
            return fig

    x_max = max([d[1] for d in grid_data])
    y_max = max([d[0] for d in grid_data])
    max_dim = max(x_max, y_max)

    if figsize is None:
        if x_max / max_dim > 0.33 and y_max / max_dim > 0.33:
            figsize = (5, 5)
        else:
            figsize = (9, 3)

    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)  # pylint: disable=invalid-name
        ax.axis('off')

    # set coloring
    if qubit_color is None:
        qubit_color = ['#648fff'] * config.n_qubits
    if line_color is None:
        line_color = ['#648fff'] * len(cmap)

    # Add lines for couplings
    for ind, edge in enumerate(cmap):
        is_symmetric = False
        if edge[::-1] in cmap:
            is_symmetric = True
        y_start = grid_data[edge[0]][0]
        x_start = grid_data[edge[0]][1]
        y_end = grid_data[edge[1]][0]
        x_end = grid_data[edge[1]][1]

        if is_symmetric:
            if y_start == y_end:
                x_end = (x_end - x_start) / 2 + x_start

            elif x_start == x_end:
                y_end = (y_end - y_start) / 2 + y_start

            else:
                x_end = (x_end - x_start) / 2 + x_start
                y_end = (y_end - y_start) / 2 + y_start
        ax.add_artist(
            plt.Line2D([x_start, x_end], [-y_start, -y_end],
                       color=line_color[ind],
                       linewidth=line_width,
                       zorder=0))
        if plot_directed:
            dx = x_end - x_start  # pylint: disable=invalid-name
            dy = y_end - y_start  # pylint: disable=invalid-name
            if is_symmetric:
                x_arrow = x_start + dx * 0.95
                y_arrow = -y_start - dy * 0.95
                dx_arrow = dx * 0.01
                dy_arrow = -dy * 0.01
                head_width = 0.15
            else:
                x_arrow = x_start + dx * 0.5
                y_arrow = -y_start - dy * 0.5
                dx_arrow = dx * 0.2
                dy_arrow = -dy * 0.2
                head_width = 0.2
            ax.add_patch(
                mpatches.FancyArrow(x_arrow,
                                    y_arrow,
                                    dx_arrow,
                                    dy_arrow,
                                    head_width=head_width,
                                    length_includes_head=True,
                                    edgecolor=None,
                                    linewidth=0,
                                    facecolor=line_color[ind],
                                    zorder=1))

    # Add circles for qubits
    for var, idx in enumerate(grid_data):
        _idx = [idx[1], -idx[0]]
        width = _GraphDist(qubit_size, ax, True)
        height = _GraphDist(qubit_size, ax, False)
        ax.add_artist(
            mpatches.Ellipse(_idx,
                             width,
                             height,
                             color=qubit_color[var],
                             zorder=1))
        if label_qubits:
            ax.text(*_idx,
                    s=qubit_labels[var],
                    horizontalalignment='center',
                    verticalalignment='center',
                    color=font_color,
                    size=font_size,
                    weight='bold')
    ax.set_xlim([-1, x_max + 1])
    ax.set_ylim([-(y_max + 1), 1])
    if not input_axes:
        if get_backend() in [
                'module://ipykernel.pylab.backend_inline', 'nbAgg'
        ]:
            plt.close(fig)
        return fig
    return None
Exemple #18
0
     except:
         pass
     finally:
         square_lines = []
         square_combs = []
         
     # Overlay the copepod measurement
 
     if copepod_measured:
         y0, x0 = props.centroid
         orientation = props.orientation
         
         ellipse = patches.Ellipse((x0+xmin,y0+ymin), 
                                   props.minor_axis_length, 
                                   props.major_axis_length,
                                   -np.rad2deg(orientation),
                                   fill = False,
                                   linestyle = "-",
                                   edgecolor = "green",
                                   linewidth = 3)
           
         axes.add_artist(ellipse)
     
     # Show the image
     # plt.savefig(f"{img_out_dir}qaqc{img_name}")
 
     ####################
     # Show for debugging
     plt.show()
     ####################    
     
     plt.close(fig)
Exemple #19
0
#from matplotlib.font_manager import FontProperties

def add_at(ax, t, loc=2):
    fp = dict(size=10)
    _at = AnchoredText(t, loc=loc, prop=fp)
    ax.add_artist(_at)
    return _at


grid = AxesGrid(fig, 111, (1, 4), label_mode="1", share_all=True)

grid[0].set_autoscale_on(False)

ax = grid[0]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("",
            xy=(x1, y1), xycoords='data',
            xytext=(x2, y2), textcoords='data',
            arrowprops=dict(arrowstyle="-", #linestyle="dashed",
                            color="0.5",
                            patchB=None,
                            shrinkB=0,
                            connectionstyle="arc3,rad=0.3",
                            ),
            )

add_at(ax, "connect", loc=2)

ax = grid[1]
def plotDC(np1, size=200, xy=(0, 0), width=200):
    """
    Uses one nodal plane of a double couple to draw a beach ball plot.

    :param ax: axis object of a matplotlib figure
    :param np1: :class:`~NodalPlane`

    Adapted from MATLAB script
    `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
    written by Andy Michael and Oliver Boyd.
    """
    # check if one or two widths are specified (Circle or Ellipse)
    try:
        assert (len(width) == 2)
    except TypeError:
        width = (width, width)
    S1 = np1.strike
    D1 = np1.dip
    R1 = np1.rake

    M = 0
    if R1 > 180:
        R1 -= 180
        M = 1
    if R1 < 0:
        R1 += 180
        M = 1

    # Get azimuth and dip of second plane
    (S2, D2, _R2) = AuxPlane(S1, D1, R1)

    D = size / 2

    if D1 >= 90:
        D1 = 89.9999
    if D2 >= 90:
        D2 = 89.9999

    # arange checked for numerical stablility, np.pi is not multiple of 0.1
    phi = np.arange(0, np.pi, .01)
    l1 = np.sqrt(
        np.power(90 - D1, 2) /
        (np.power(np.sin(phi), 2) +
         np.power(np.cos(phi), 2) * np.power(90 - D1, 2) / np.power(90, 2)))
    l2 = np.sqrt(
        np.power(90 - D2, 2) /
        (np.power(np.sin(phi), 2) +
         np.power(np.cos(phi), 2) * np.power(90 - D2, 2) / np.power(90, 2)))

    inc = 1
    (X1, Y1) = Pol2Cart(phi + S1 * D2R, l1)

    if M == 1:
        lo = S1 - 180
        hi = S2
        if lo > hi:
            inc = -1
        th1 = np.arange(S1 - 180, S2, inc)
        (Xs1, Ys1) = Pol2Cart(th1 * D2R, 90 * np.ones((1, len(th1))))
        (X2, Y2) = Pol2Cart(phi + S2 * D2R, l2)
        th2 = np.arange(S2 + 180, S1, -inc)
    else:
        hi = S1 - 180
        lo = S2 - 180
        if lo > hi:
            inc = -1
        th1 = np.arange(hi, lo, -inc)
        (Xs1, Ys1) = Pol2Cart(th1 * D2R, 90 * np.ones((1, len(th1))))
        (X2, Y2) = Pol2Cart(phi + S2 * D2R, l2)
        X2 = X2[::-1]
        Y2 = Y2[::-1]
        th2 = np.arange(S2, S1, inc)
    (Xs2, Ys2) = Pol2Cart(th2 * D2R, 90 * np.ones((1, len(th2))))
    X = np.concatenate((X1, Xs1[0], X2, Xs2[0]))
    Y = np.concatenate((Y1, Ys1[0], Y2, Ys2[0]))

    X = X * D / 90
    Y = Y * D / 90

    # calculate resolution
    res = [value / float(size) for value in width]

    # construct the patches
    collect = [patches.Ellipse(xy, width=width[0], height=width[1])]
    collect.append(xy2patch(Y, X, res, xy))
    return ['b', 'w'], collect
Exemple #21
0
def enrichometer(ranks,
                 genesUp,
                 genesDown=None,
                 universe=None,
                 fexact_H1='two-sided',
                 reservoirR1=1.4,
                 reservoirR2=None,
                 fillingLinewidths=False,
                 ax=None,
                 title=None,
                 feminpv=.05,
                 invertx=False,
                 textrotation=0,
                 fontsize=12,
                 **kwargs):
    """Enrichometer plot

    Args:
        ranks (pd.Series): Series with ranked statistic.
        genesUp (set): Up or differentially regulated genes.
        genesDown (set): If not provided, considered as unitary geneset.
        universe (int or list): Total number of genes in the universe
            or list with all genes in the universe .
        fexact_H1 (str): greater, less, or two-sided
        reservoirR1 (float): Radius1 of reservoir
        reservoirR2 (float): Radius2 of reservoir, default 0.8
        fillingLinewidths (bool): Needs to be reimplemented, is not proportional
        ax (ax): ax for plot.
        title (str): Plot title.
        feminpv (float): Plot where enrichment is the strongest;
            provide as float, if fisher enrichment at strongest is not
            significant in respect to value provided nothing is plotted
        invertx (bool): Invert x axis.
        textrotation (float): Text rotation.
        fontsize (float): Font size.

    Returns:
        figure[, leadingEdgeGenes if feminpv]

    Note:
        *kwargs* are passed to `ax.eventplot`
    """
    #enrichometer settings
    axiscale = 10
    eventoffset = 0
    if reservoirR1 and reservoirR2:
        eventlen = np.pi * reservoirR1 * reservoirR2 * len(ranks) / (
            axiscale * len(genesUp))
    else:
        eventlen = 1
    reservoirR2 = reservoirR2 if reservoirR2 else .8
    reservoirR1 = (reservoirR1 if reservoirR1 else axiscale * eventlen *
                   len(genesUp) / (np.pi * reservoirR2 * len(ranks)))
    padding = .1
    if not ax:
        fig, ax = plt.subplots(figsize=(8, 2))
    else:
        fig = ax.get_figure()
    ax.axis('off')
    if fillingLinewidths:
        raise NotImplemented  #todo use rectangle patches, does not work with linewidths
        axPixels = ax.transData.transform([(0, 1),
                                           (1, 0)]) - ax.transData.transform(
                                               (0, 0))
        linewidths = (axPixels[1, 0] / fig.dpi) * axiscale / len(ranks)
    settings = {
        'colors': 'r',
    }
    settings.update(kwargs)

    #Normalize the ranks
    minR, maxR = (ranks.min(), ranks.max())
    normalized = ((ranks - minR) * axiscale / (maxR - minR) - axiscale -
                  reservoirR1)

    ax.eventplot(normalized[normalized.index.isin(genesUp)],
                 lineoffsets=eventoffset,
                 linelengths=eventlen,
                 **settings)
    ax.set_xlim((-axiscale - reservoirR1 - padding, reservoirR1 + padding))
    ax.set_ylim((eventoffset - max(eventlen / 2, reservoirR2) - padding,
                 eventoffset + max(eventlen / 2, reservoirR2) + padding))

    #Draw thermometer
    overlap = sum(ranks.index.isin(genesUp))
    filled = 1 - overlap / len(genesUp)
    emptyReservoir = reservoirR1 * 2 - (reservoirR1 * 2 * filled)
    ax.add_patch(
        ptch.Ellipse((0, eventoffset),
                     width=2 * reservoirR1,
                     height=2 * reservoirR2,
                     facecolor='r',
                     edgecolor='none'))
    ax.add_patch(
        ptch.Rectangle((-reservoirR1, eventoffset - reservoirR2),
                       emptyReservoir,
                       2 * reservoirR2,
                       facecolor='w',
                       edgecolor='none'))
    ax.add_patch(
        ptch.Ellipse((0, eventoffset),
                     width=2 * reservoirR1,
                     height=2 * reservoirR2,
                     facecolor='none',
                     edgecolor='k'))
    ax.add_patch(
        ptch.Rectangle((-axiscale - reservoirR1, eventoffset - eventlen / 2),
                       axiscale,
                       eventlen,
                       facecolor='w',
                       edgecolor='k'))

    #Annotations
    ax.annotate('{:g}'.format(minR), (-axiscale - reservoirR1,
                                      (eventoffset - eventlen / 2) - padding),
                ha='right' if invertx else 'left',
                va='top',
                rotation=textrotation,
                size=fontsize)
    ax.annotate('{:g}'.format(maxR),
                (-reservoirR1, (eventoffset - eventlen / 2) - padding),
                ha='left' if invertx else 'right',
                va='top',
                rotation=textrotation,
                size=fontsize)

    if universe:
        if type(universe) is list: raise NotImplemented
        odds, pval = fisher_exact(
            [[overlap, len(ranks)], [len(genesUp) - overlap, universe]],
            alternative=fexact_H1)
        ax.annotate('{}\n{:.3g}'.format(len(genesUp), pval), (0, eventoffset),
                    ha='center',
                    va='center',
                    rotation=textrotation,
                    size=fontsize)

    if feminpv:
        fenrichscores = fenrichmentscore(ranks, genesUp)
        pvmin = fenrichscores.pvalue.min()
        if pvmin <= feminpv:
            leadingEdgeGene = fenrichscores[fenrichscores.pvalue ==
                                            pvmin].first_valid_index()
            #ax.eventplot((normalized.loc[leadingEdgeGene],),lineoffsets=eventoffset,linelengths=eventlen,
            #             color='g')
            ax.add_patch(
                ptch.Rectangle(
                    (-axiscale - reservoirR1, eventoffset - eventlen / 2),
                    normalized.loc[leadingEdgeGene] + axiscale + reservoirR1,
                    eventlen,
                    facecolor='r',
                    alpha=.4))
            ax.annotate(
                '{:.3g}'.format(pvmin),
                (normalized.loc[leadingEdgeGene] + padding, eventoffset),
                ha='left',
                va='center',
                size=fontsize)
        else:
            leadingEdgeGene = None

    if title:
        #ax.set_title(title)
        ax.annotate(
            title,
            (-axiscale - reservoirR1, eventoffset + padding + eventlen / 2),
            ha='right' if invertx else 'left',
            va='bottom',
            size=fontsize + 2)

    if invertx: ax.invert_xaxis()

    return (fig, leadingEdgeGene) if feminpv else fig
Exemple #22
0
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as patches
# Circle
shape = patches.Circle((0, 0), radius=1., color='.75')
plt.gca().add_patch(shape)
# Rectangle
shape = patches.Rectangle((2.5, -.5), 2., 1., color='.75')
plt.gca().add_patch(shape)
# Ellipse
shape = patches.Ellipse((0, -2.), 2., 1., angle=45., color='.75')
plt.gca().add_patch(shape)
# Fancy box
shape = patches.FancyBboxPatch((2.5, -2.5),
                               2.,
                               1.,
                               boxstyle='sawtooth',
                               color='.75')
plt.gca().add_patch(shape)
# Display all
plt.grid(True)
plt.axis('scaled')
plt.show()
print('#', 50 * "-")
Exemple #23
0
def comparison_countries_fueltypes_bar(dfs=None,
                                       include_WEPP=True,
                                       include_VRE=False,
                                       exclude=None,
                                       show_indicators=True,
                                       year=2015,
                                       **kwargs):
    """
    Plots per country an analysis, how the given datasets differ by fueltype.

    Parameters
    ----------
    dfs : dict
        keys : labels
        values : pandas.Dataframe containing the data to be plotted
    include_WEPP : bool
        Switch to include WEPP-based data
    include_VRE : bool
        Switch to include VRE data
    show_indicators : bool
        Switch whether to calculate a coverage between to datasets
    year : int
        Only plot units with a commissioning year smaller or equal this value
    """
    threshold = kwargs.get('threshold', -1)
    ylabel = kwargs.get('ylabel', u'Capacity [$GW$]')
    mode = kwargs.get('mode', 'screen')  # valid: ['screen', 'print']
    if mode == 'screen':
        figsize = (27, 15)  # Ratio close to FullHD Resolution
        orientation = 'landscape'
        bottom_space = 0.14
    elif mode == 'print':
        figsize = (16.54, 23.38)  # For Din (A2, A3, A4, etc.) paper print
        orientation = 'portrait'
        bottom_space = 0.07
    else:
        raise ValueError('Wrong print mode given!')

    countries = set()
    if dfs is None:
        red_w_wepp, red_wo_wepp, wepp, statistics = (gather_comparison_data(
            include_WEPP=include_WEPP, include_VRE=include_VRE, year=year))
        if include_WEPP:
            stats = lookup(
                [red_w_wepp, red_wo_wepp, wepp, statistics],
                keys=[
                    'Matched dataset w/ WEPP', 'Matched dataset w/o WEPP',
                    'WEPP only', 'Statistics ENTSO-E SO&AF'
                ],
                by='Country, Fueltype',
                exclude=exclude) / 1000
            set.update(countries, set(red_w_wepp.Country),
                       set(red_wo_wepp.Country), set(wepp.Country),
                       set(statistics.Country))
        else:
            stats = lookup(
                [red_wo_wepp, statistics],
                keys=['Matched dataset w/o WEPP', 'Statistics ENTSO-E SO&AF'],
                by='Country, Fueltype',
                exclude=exclude) / 1000
            set.update(countries, set(red_wo_wepp.Country),
                       set(statistics.Country))
    else:
        stats = lookup(dfs.values(),
                       keys=dfs.keys(),
                       by='Country, Fueltype',
                       exclude=exclude) / 1000
        stats.sort_index(axis=1, inplace=True)
        for k, v in dfs.items():
            set.update(countries, set(v.Country))
    # Filter stats
    stats = (
        stats.replace({0.0: np.nan})  # Do this in order to show only
        .dropna(axis=0, how='all')  # relevant fueltypes for each
        .fillna(0.0))  # country (if all zero->drop!).

    if (show_indicators or threshold >= 0.) and len(stats.columns) < 2:
        logger.warn('At least two objects for comparison needed when using '
                    '`show_indicators` or `threshold`. Arguments ignored.')
        show_indicators = False
        threshold = -1

    # Presettings for the plots
    font = {'size': 12}
    plt.rc('font', **font)
    # Loop through countries.
    nrows, ncols, rem = gather_nrows_ncols(len(countries),
                                           orientation=orientation)
    i, j = [0, 0]
    labels_mpatches = collections.OrderedDict()
    fig, ax = plt.subplots(nrows=nrows,
                           ncols=ncols,
                           sharex=False,
                           sharey=False,
                           squeeze=False,
                           figsize=figsize)
    for country in sorted(countries):
        if j == ncols:
            i += 1
            j = 0
        # Perform the plot
        stats.loc[country].plot.bar(ax=ax[i, j],
                                    stacked=False,
                                    legend=False,
                                    colormap='jet')
        if show_indicators or threshold >= 0.0:
            # TODO: Assure that matched is always in 1st+stats in last column.
            colm = stats.loc[country].columns[0]
            cols = stats.loc[country].columns[-1]
        if threshold >= 0.0:
            ctry = stats.loc[country]
            ctry.loc[:, 'ratio'] = abs(ctry[colm] - ctry[cols]) / ctry[cols]
            ctry.loc[:, 'delta'] = abs(ctry[colm] - ctry[cols])
            ctry.loc[:, 'mean'] = ctry.loc[:, colm:cols].apply(np.mean, axis=1)
            ctry = (ctry.reset_index(
                drop=True).loc[lambda x: x['ratio'] >= threshold])
            circles = [
                mpatches.Ellipse(xy=(float(x), r['mean']),
                                 height=(r['delta']) * 2.5,
                                 width=4. / ctry.index.max(),
                                 color='g',
                                 alpha=0.5) for x, r in ctry.iterrows()
            ]
            for c in circles:
                ax[i, j].add_artist(c)
        if show_indicators:
            ctry = stats.loc[country]
            r_sq = round(ctry.corr().iloc[0, 1]**2, 3)
            cov = round(ctry[colm].sum() / ctry[cols].sum(), 3)
            txt = AnchoredText(
                "\n" + r'$R^{2} = $%s' % r_sq + "\n"
                r'$\frac{\sum P_{match}}{\sum P_{stats}} = $%s' % cov,
                loc=get_config()['textbox_position'][country],
                prop={'size': 11})
            txt.patch.set(boxstyle='round', alpha=0.5)
            ax[i, j].add_artist(txt)
        # Pass the legend information into the Ordered Dict
        stats_handle, stats_labels = ax[i, j].get_legend_handles_labels()
        for u, v in enumerate(stats_labels):
            if v not in labels_mpatches:
                labels_mpatches[v] = mpatches.Patch(
                    color=stats_handle[u].patches[0].get_facecolor(), label=v)
        if threshold >= 0.0:
            label = 'Threshold (={}%) marker'.format(int(threshold * 100.))
            labels_mpatches[label] = mpatches.Patch(color='g',
                                                    alpha=0.5,
                                                    label=label)
        # Format the subplots nicely
        ax[i, j].set_facecolor('#d9d9d9')
        ax[i, j].set_axisbelow(True)
        ax[i, j].grid(color='white', linestyle='dotted')
        ax[i, j].set_title(country)
        ax[i, 0].set_ylabel(ylabel)
        ax[i, j].xaxis.label.set_visible(False)
        j += 1
    # After the loop, do the rest of the layouting.
    fig.tight_layout()
    # Legend
    fig.subplots_adjust(bottom=bottom_space)
    labels_mpatches = collections.OrderedDict(sorted(labels_mpatches.items()))
    fig.legend(labels_mpatches.values(),
               labels_mpatches.keys(),
               loc=8,
               ncol=len(labels_mpatches),
               facecolor='#d9d9d9')
    return fig, ax
Exemple #24
0
         ha="center",
         family=font,
         size=14)

# add a Polygon
polygon = mpatches.RegularPolygon(pos[:, 3], 5, 0.1)
patches.append(polygon)
plt.text(pos[0, 3],
         pos[1, 3] - 0.15,
         "Polygon",
         ha="center",
         family=font,
         size=14)

#add an ellipse
ellipse = mpatches.Ellipse(pos[:, 4], 0.2, 0.1)
patches.append(ellipse)
plt.text(pos[0, 4],
         pos[1, 4] - 0.15,
         "Ellipse",
         ha="center",
         family=font,
         size=14)

#add an arrow
arrow = mpatches.Arrow(pos[0, 5] - 0.05, pos[1, 5] - 0.05, 0.1, 0.1, width=0.1)
patches.append(arrow)
plt.text(pos[0, 5],
         pos[1, 5] - 0.15,
         "Arrow",
         ha="center",
Exemple #25
0
rect = mpatches.Rectangle(grid[1] - [0.025, 0.05], 0.05, 0.1, ec="none")
patches.append(rect)
label(grid[1], "Rectangle")

# add a wedge
wedge = mpatches.Wedge(grid[2], 0.1, 30, 270, ec="none")
patches.append(wedge)
label(grid[2], "Wedge")

# add a Polygon
polygon = mpatches.RegularPolygon(grid[3], 5, 0.1)
patches.append(polygon)
label(grid[3], "Polygon")

# add an ellipse
ellipse = mpatches.Ellipse(grid[4], 0.2, 0.1)
patches.append(ellipse)
label(grid[4], "Ellipse")

# add an arrow
arrow = mpatches.Arrow(grid[5, 0] - 0.05,
                       grid[5, 1] - 0.05,
                       0.1,
                       0.1,
                       width=0.1)
patches.append(arrow)
label(grid[5], "Arrow")

# add a path patch
Path = mpath.Path
path_data = [(Path.MOVETO, [0.018, -0.11]), (Path.CURVE4, [-0.031, -0.051]),
Exemple #26
0
    eigvals, eigvecs = np.linalg.eig(projected_covariance)

    print(eigvals)
    print(eigvecs)

    print('Sampling objective function of registration pair...')
    error_f = TranslationErrorFunction(dataset, algo, args.reading,
                                       args.reference, args.n_samples_t,
                                       args.n_samples_r)

    error_f.compute(args.span_t, args.span_r, at=mean)
    error_f.read_data()
    error_f.plot()

    e = pat.Ellipse([mean[0, 3], mean[1, 3]], 2 * np.sqrt(eigvals[0]),
                    2 * np.sqrt(eigvals[1]),
                    np.arctan2(eigvecs[0, 1], eigvecs[0, 0]))
    plt.gca().add_artist(e)
    e.set_alpha(1.0)
    e.set_fill(False)
    e.set_edgecolor('black')
    e.set_clip_box(plt.gca().bbox)

    plt.plot([mean[0, 3]], [mean[1, 3]], color='black', marker='o')

    gt = dataset.ground_truth(args.reading, args.reference)
    plt.plot([gt[0, 3]], [gt[1, 3]], color='black', marker='x')

    odom = dataset.odometry_estimate(args.reading, args.reference)
    plt.plot([odom[0, 3]], [odom[1, 3]], color='black', marker='^')
Exemple #27
0
def plot_dc(np1, size=200, xy=(0, 0), width=200):
    """
    Uses one nodal plane of a double couple to draw a beach ball plot.

    :param ax: axis object of a matplotlib figure
    :param np1: :class:`~NodalPlane`

    Adapted from MATLAB script
    `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
    written by Andy Michael, Chen Ji and Oliver Boyd.
    """
    # check if one or two widths are specified (Circle or Ellipse)
    try:
        assert (len(width) == 2)
    except TypeError:
        width = (width, width)
    s_1 = np1.strike
    d_1 = np1.dip
    r_1 = np1.rake

    m = 0
    if r_1 > 180:
        r_1 -= 180
        m = 1
    if r_1 < 0:
        r_1 += 180
        m = 1

    # Get azimuth and dip of second plane
    (s_2, d_2, _r_2) = aux_plane(s_1, d_1, r_1)

    d = size / 2

    if d_1 >= 90:
        d_1 = 89.9999
    if d_2 >= 90:
        d_2 = 89.9999

    # arange checked for numerical stability, np.pi is not multiple of 0.1
    phi = np.arange(0, np.pi, .01)
    l1 = np.sqrt(
        np.power(90 - d_1, 2) /
        (np.power(np.sin(phi), 2) +
         np.power(np.cos(phi), 2) * np.power(90 - d_1, 2) / np.power(90, 2)))
    l2 = np.sqrt(
        np.power(90 - d_2, 2) /
        (np.power(np.sin(phi), 2) +
         np.power(np.cos(phi), 2) * np.power(90 - d_2, 2) / np.power(90, 2)))

    inc = 1
    (x_1, y_1) = pol2cart(phi + s_1 * D2R, l1)

    if m == 1:
        lo = s_1 - 180
        hi = s_2
        if lo > hi:
            inc = -1
        th1 = np.arange(s_1 - 180, s_2, inc)
        (xs_1, ys_1) = pol2cart(th1 * D2R, 90 * np.ones((1, len(th1))))
        (x_2, y_2) = pol2cart(phi + s_2 * D2R, l2)
        th2 = np.arange(s_2 + 180, s_1, -inc)
    else:
        hi = s_1 - 180
        lo = s_2 - 180
        if lo > hi:
            inc = -1
        th1 = np.arange(hi, lo, -inc)
        (xs_1, ys_1) = pol2cart(th1 * D2R, 90 * np.ones((1, len(th1))))
        (x_2, y_2) = pol2cart(phi + s_2 * D2R, l2)
        x_2 = x_2[::-1]
        y_2 = y_2[::-1]
        th2 = np.arange(s_2, s_1, inc)
    (xs_2, ys_2) = pol2cart(th2 * D2R, 90 * np.ones((1, len(th2))))
    x = np.concatenate((x_1, xs_1[0], x_2, xs_2[0]))
    y = np.concatenate((y_1, ys_1[0], y_2, ys_2[0]))

    x = x * d / 90
    y = y * d / 90

    # calculate resolution
    res = [value / float(size) for value in width]

    # construct the patches
    collect = [patches.Ellipse(xy, width=width[0], height=width[1])]
    collect.append(xy2patch(y, x, res, xy))
    return ['b', 'w'], collect
Exemple #28
0
def geometric_ray_diagram(focal_length=1., magnification=False):
    """ Sketch of geometric ray diagram od one lens

    Parameters
    ----------
    focal_length: float
        focal length of lens
    magnification: boolean
        draw magnification on the side

    Returns
    -------
    matplotlib figure
    """

    f = focal_length

    u = 1.5
    v = 1 / (1 / f - 1 / u)
    m = v / u
    if magnification:
        line_strong = .5
    else:
        line_strong = 2

    x = 0.4

    fig, ax = plt.subplots()

    # add an ellipse
    ellipse = patches.Ellipse((0.0, 0.0), 3.4, 0.3, alpha=0.3, color='blue')
    ax.add_patch(ellipse)
    ax.plot([1.5, -1.5], [0, 0], '--', color='black')
    ax.plot([0, 0], [u, -v], '--', color='black')
    single_prop = dict(arrowstyle="->", shrinkA=0, shrinkB=0)
    double_prop = dict(arrowstyle="<->", shrinkA=0, shrinkB=0)

    if magnification:
        ax.annotate("", xy=(-x, u), xytext=(x, u), arrowprops=single_prop)
        ax.annotate("",
                    xy=(x * m, -v),
                    xytext=(-x * m, -v),
                    arrowprops=single_prop)

    else:
        ax.annotate("", xy=(-x, u), xytext=(0, u), arrowprops=single_prop)
        ax.annotate("", xy=(x * m, -v), xytext=(0, -v), arrowprops=single_prop)

    ax.text(x + 0.1, u, 'object plane', va='center')
    ax.plot([1, -1], [-f, -f], '--', color='black')
    ax.text(1.1, -f, 'back focal\n plane', va='center')
    ax.text(x * m + 0.1, -v, 'image plane', va='center')

    ax.annotate("", xy=(-.9, 0), xytext=(-.9, -f), arrowprops=double_prop)
    ax.text(-1, -f / 2, 'f')
    if magnification:
        ax.annotate("",
                    xy=(-1.8, 0),
                    xytext=(-1.8, -v),
                    arrowprops=double_prop)
        ax.text(-1.7, -v / 2, 'v')
        ax.annotate("", xy=(-1.8, 0), xytext=(-1.8, u), arrowprops=double_prop)
        ax.text(-1.7, u / 2, 'u')

    ax.plot([-x, x * m], [u, -v], color='black', linewidth=line_strong)
    ax.plot([-x, -x], [u, 0], color='black', linewidth=line_strong)
    ax.plot([-x, x * m], [0, -v], color='black', linewidth=line_strong)

    ax.plot([-x, -2 * x], [u, 0], color='black', linewidth=0.5)
    ax.plot([-2 * x, x * m], [0, -v], color='black', linewidth=0.5)
    if magnification:
        ax.plot([x, -x * m], [u, -v], color='black', linewidth=0.5)
        ax.plot([x, x], [u, 0], color='black', linewidth=0.5)
        ax.plot([x, -x * m], [0, -v], color='black', linewidth=0.5)

        ax.plot([x, 2 * x], [u, 0], color='black', linewidth=0.5)
        ax.plot([2 * x, -x * m], [0, -v], color='black', linewidth=0.5)
    else:
        ax.plot([-x, x * m], [u, 0], color='black', linewidth=0.5)
        ax.plot([x * m, x * m], [0, -v], color='black', linewidth=0.5)

    ax.set_xlim(-2, 3)
    ax.set_ylim(-3.5, 2)
    ax.set_aspect('equal')
Exemple #29
0
def create_ellipse(loc, w, color):
    ellipse = mpatches.Ellipse(loc, w, w * 0.8, color=color)
    return ellipse
Exemple #30
0
# DRAW AN ELLIPSE #############################################################

ax = axs[next(it)]

center = (0., 0.)  # center of the circle
width = 8
height = 6
angle = 0.

patch = mpatches.Ellipse(
    xy=center,
    width=width,
    height=height,
    angle=angle,
    # COMMON OPTIONS:
    alpha=alpha,
    fill=fill,
    facecolor=fill_color,
    hatch=fill_pattern,
    ec=line_color,
    lw=line_width,
    linestyle=line_style)

ax.add_patch(patch)
ax.set_title("matplotlib.patches.Ellipse", fontsize=TITLE_FONT_SIZE)

# DRAW A WEDGE ################################################################

ax = axs[next(it)]

center = (0., 0.)  # center of the circle