def colorbar_index(ncolors, cmap, orientation="vertical"):
    cmap = cmap_discretize(cmap, ncolors)
    mappable = cm.ScalarMappable(cmap=cmap)
    mappable.set_array([])
    mappable.set_clim(-0.5, ncolors+0.5)
    colorbar = plt.colorbar(mappable, orientation=orientation)
    colorbar.set_ticks(np.linspace(0, ncolors, ncolors))
    colorbar.set_ticklabels(range(ncolors))

    return colorbar
Exemple #2
0
def generate_table(table_data, rows, columns):
    df = DataFrame(table_data, index=rows, columns=columns)
    base = 0
    colorings = []
    #colorings.append([base]*(len(rows)+1))
    for column in columns:
        vals = df[column].values
        normal = normalize(vals.min() - 1, vals.max() + 1)
        m = cm.ScalarMappable(
            norm=matplotlib.colors.Normalize(vmin=vals.min(), vmax=vals.max()))
        m.set_cmap("YlGn")
        col_colors = m.to_rgba(vals)
        print col_colors
        colorings.append(col_colors)

        #colorings.append(list(np.transpose(cm.hot(normal(vals)))[1]))
    colorings = np.transpose(colorings, (1, 0, 2))
    print colorings.shape

    fig = figure(figsize=(15, 8))
    ax = fig.add_subplot(111, frameon=True, xticks=[], yticks=[])
    #print colorings
    vals = df.values

    the_table = table(cellText=vals,
                      rowLabels=df.index,
                      colLabels=df.columns,
                      colWidths=[0.13] * vals.shape[1],
                      loc='center',
                      cellColours=colorings,
                      fontsize=15)

    #nrows, ncols = len(rows)+1, len(columns)+1
    #hcell, wcell = 1, 1
    #hpad, wpad = .5, 0
    #fig = figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad))
    #fig = figure()
    #ax = fig.add_subplot(111)
    #ax.axis('off')
    #ax.table(cellText=table_data,
    #      rowLabels=rows,
    #      colLabels=columns,
    #      loc='center')
    show()
    close()
def plot_spikes(df, sample_type, ax=None, mi=None, mx=None):

    if ax is None:
        fig, ax = plt.subplots()
    else:
        fig = None
    x = df[df['Sample Type'] == sample_type]['x']
    y = df[df['Sample Type'] == sample_type]['z']
    s = df[df['Sample Type'] == sample_type]['volume']

    if mi is None:
        mi = min(s)
        mx = max(s)
    norm = np.array([((i - mi) / (mx - mi)) * 100 for i in s])
    colors_to_use = cm.rainbow(norm / max(norm))
    colmap = cm.ScalarMappable(cmap=cm.rainbow)
    colmap.set_array(colors_to_use)
    t = ax.scatter(x, y, c=colors_to_use, s=norm, marker='o')
    ax.set_xlim(150, 400)

    if fig is not None:
        fig.colorbar(colmap)
        return (fig, ax)
    return colmap
Exemple #4
0
def plot_spike(df, spikename, ax=None, mi=None, mx=None):

    if ax is None:
        fig, ax = plt.subplots()
    x = df[df['Sample name'] == spikename]['x']
    y = df[df['Sample name'] == spikename]['z']
    s = df[df['Sample name'] == spikename]['volume']

    if mi is None:
        mi = min(s)
        mx = max(s)
    norm = np.array([((i - mi) / (mx - mi)) * 75 for i in s])
    colors_to_use = cm.rainbow(norm / max(norm))
    colmap = cm.ScalarMappable(cmap=cm.rainbow)
    colmap.set_array(colors_to_use)
    ax.scatter(x, y, c=colors_to_use, s=norm, marker='o')
    ax.set_xlim(0, 512)
    fid = list(df[df['Sample name'] == spikename]['folderid'])[0]
    ax.set_title('{0}\n{1}'.format(spikename, fid))

    # if fig:
    #     fig.colorbar(colmap)
    #     return (fig, ax)
    return colmap
Exemple #5
0
def get_param_param_scores(param1,
                           param2,
                           param3=None,
                           dataPath=os.getcwd(),
                           score=0,
                           model=None):
    param1_vals = []
    param2_vals = []
    param3_vals = []
    score_vals = []
    eachPoint = {}  # dict of list as point coordinate : score list

    model_pattern = re.compile("LG14modelID.*:\ *(\d+).")
    param1Val_pattern = re.compile(str(param1) + ".*:\ *(\d+[\.\d*]*).*")
    param2Val_pattern = re.compile(str(param2) + ".*:\ *(\d+[\.\d*]*).*")
    param3Val_pattern = re.compile(str(param3) + ".*:\ *(\d+[\.\d*]*).*")
    for fName in os.listdir(dataPath):
        dirPath = os.path.join(dataPath, fName)
        if os.path.isdir(dirPath) and fName.startswith("2017"):
            try:
                with open(os.path.join(dirPath, "score.txt"),
                          "r") as scoreFile:
                    obt_score = float(scoreFile.readline().rstrip())
            except Exception:
                continue
            if obt_score < float(score):
                continue
            # If the score is ok
            # lets check the model nb by getting the modelParams
            with open(dirPath + "/modelParams.py", 'r') as paramsFile:
                Paramsdata = paramsFile.readlines()
                # only getting the results of the expected model
            if (not model is None):
                mod = int(
                    model_pattern.findall(
                        filter(lambda x: model_pattern.search(x),
                               Paramsdata)[0])[0])
                if (mod != model):
                    continue
            # get values
            point = []
            try:
                val1 = float(
                    param1Val_pattern.findall(
                        filter(lambda x: param1Val_pattern.search(x),
                               Paramsdata)[0])[0])
                param1_vals.append(val1)
                point.append(val1)
            except IndexError:  # if there were no result : the variable name is wrong
                reason = "------------- ERROR : Wrong variable name [" + str(
                    param1) + "]"
                print reason
                return plot_print_wrong(axis, reason)
            try:
                val2 = float(
                    param2Val_pattern.findall(
                        filter(lambda x: param2Val_pattern.search(x),
                               Paramsdata)[0])[0])
                param2_vals.append(val2)
                point.append(val2)
            except IndexError:  # if there were no result : the variable name is wrong
                reason = "------------- ERROR : Wrong variable name [" + str(
                    param2) + "]"
                print reason
                return plot_print_wrong(axis, reason)
            if not param3 is None:
                try:
                    val3 = float(
                        param3Val_pattern.findall(
                            filter(lambda x: param3Val_pattern.search(x),
                                   Paramsdata)[0])[0])
                    param3_vals.append(val3)
                    point.append(val3)
                except IndexError:  # if there were no result : the variable name is wrong
                    reason = "------------- ERROR : Wrong variable name [" + str(
                        param3) + "]"
                    print reason
                    return plot_print_wrong(axis, reason)
            # saving every score for each point
            point = tuple(point)
            if eachPoint.has_key(point):
                eachPoint[point].append(obt_score)
            else:
                eachPoint[point] = [obt_score]
            score_vals.append(obt_score)
    # end for
    score_vals = np.array(score_vals)
    colmap = cm.ScalarMappable(cmap=cm.hsv)
    colmap.set_array(score_vals)

    return param1_vals, param2_vals, param3_vals, eachPoint, score_vals, colmap
def fig2_b(df_orig, ax=None, mi=None, mx=None, use_fig=False, fig=None):

    df = df_orig.copy(deep=True)

    mono_names = list(
        filter(lambda n: True if 'wild' not in n else False,
               einkorn['Sample name'].unique()))[:13]

    mono_names.extend(
        list(
            filter(lambda n: True if 'wild' in n else False,
                   einkorn['Sample name'].unique())))

    df = df[df['Sample name'].isin(mono_names)]

    df.ix[df['Sample Type'] == 'T. monococcum',
          'x'] = df[df['Sample Type'] == 'T. monococcum']['x'] + 512

    if ax is None:
        fig, ax = plt.subplots()

    x = df['x']
    y = df['z']
    s = df['volume']

    if mi is None:
        mi = min(s)
        mx = max(s)
    norm = np.array([((i - mi) / (mx - mi)) * 100 for i in s])
    colors_to_use = cm.rainbow(norm / max(norm))
    colmap = cm.ScalarMappable(cmap=cm.rainbow)
    colmap.set_array(colors_to_use)
    t = ax.scatter(x, y, c=colors_to_use, s=norm, marker='o')

    if not use_fig:
        colbar = fig.colorbar(colmap, ticks=[0, 0.5, 1])
        colbar.ax.set_yticklabels([
            r'{0:3.2f}mm$^3$'.format(mi),
            r'{0:3.2f}mm$^3$'.format(df['volume'].mean()),
            r'{0:3.2f}mm$^3$'.format(mx)
        ])

        x1 = [300, 800]
        squad = ['T. beoticum', 'T. monococcum']
        ax.set_xticks(x1)
        ax.set_xticklabels(squad, minor=False)
        return (fig, ax)

    else:
        colbar = fig.colorbar(colmap, ticks=[0, 0.5, 1], ax=ax)
        colbar.ax.set_yticklabels([
            r'{0:3.2f}mm$^3$'.format(mi),
            r'{0:3.2f}mm$^3$'.format(df['volume'].mean()),
            r'{0:3.2f}mm$^3$'.format(mx)
        ])

        x1 = [300, 800]
        squad = ['T. beoticum', 'T. monococcum']
        ax.set_xticks(x1)
        ax.set_xticklabels(squad, minor=False)

    return colmap
Exemple #7
0
        sns.distplot(initLoss)
        plt.savefig(os.path.join(foldername, 'costs-dist.jpg'))
        x = np.arange(len(initLoss))
        sns.jointplot(x=x, y=initLoss)
        plt.savefig(os.path.join(foldername, 'costs-seq.jpg'))

        arr = np.array(list_ball[:len(initLoss)])
        x = arr[:, 0]
        y = arr[:, 1]
        z = arr[:, 2]
        fig = plt.figure(figsize=(8, 6))
        ax = fig.add_subplot(111, projection='3d')
        n = 100
        cmap = cm.RdGy
        colors = cmap(initLoss / max(initLoss))
        colmap = cm.ScalarMappable(cmap=cmap)
        colmap.set_array(initLoss)
        yg = ax.scatter(x, y, z, c=colors, marker='o')
        cb = fig.colorbar(colmap)
        plt.savefig(os.path.join(foldername, 'viz_errors.jpg'))
        plt.show()

    np.set_printoptions(suppress=True,
                        formatter={'float_kind': '{:.20f},'.format},
                        linewidth=100)  # Try to print 4 numbers on one line

    # ----------------------------------------------------------------------------
    # STEP1: Optimize R
    # ----------------------------------------------------------------------------
    if args.step == 1:
        print(
print "size of X is: ", X.shape
print "size of Y is: ", Y.shape
Z=[[-58,-59.5,-65,-71,-76,-80,-84],	[-65,-67,-71,-75.5,-80,-83,-85.5],[-72,-73,-75,-79,-82,-84,-87],[-75,-77,-80,-81,-84,-85.5,-90]]
'''Z=[]
Z.append([-58,-61,-66,-83,-69,-63,-58])
Z.append([-66, -69, -74, -86, -74, -69.5, -66.5])
Z.append([-75, -76, -81, -90, -85, -75.5, -72])
Z.append([-76, -80, -84, -91, -88, -83, -78])'''
print Z
#ax.plot_surface(X, Y, Z,cmap=cm.RdBu,vmin=-100, vmax=-50)
A = np.arange(-90, -50, 2)
ax.plot_trisurf(X.flatten(), Y.flatten(), np.array(Z).flatten(), color="Red", cmap='winter', shade=True, linewidth="0.7")
ax.set_xlabel('X coordinate')
ax.set_ylabel('Y coordinate')
ax.set_zlabel('Power')
m = cm.ScalarMappable(cmap=cm.winter)
m.set_array(A)
plt.colorbar(m)


# Plotting Power vs x,y,z in the case of single antenna
"""fig2 = plt.figure()
ax2 = fig2.add_subplot(111, projection='3d')

Z2 = []
Z2.append([-58,-59.5,-65,-71,-76,-80,-84])
Z2.append([-65,-67,-71,-75.5,-80,-83,-85.5])
Z2.append([-72,-73,-75,-79,-82,-84,-87])
Z2.append([-75,-77,-80,-81,-84,-85.5,-90])

ax2.plot_trisurf(X.flatten(), Y.flatten(), np.array(Z2).flatten(), color="Red", cmap='hot', shade=True, linewidth="0.7")
    root = int(sqrt(num_concepts))
    if root * root >= num_concepts:
        columns = root
        rows = root
    elif root * (root + 1) >= num_concepts:
        columns = root + 1
        rows = root
    else:
        columns = root + 1
        rows = root

    # for each concept, create a colored scatter plot of all unlabeled data points
    counter = 1
    for label, memberships in validation_memberships.items():
        colors = cm.jet(memberships)
        colmap = cm.ScalarMappable(cmap=cm.jet)
        colmap.set_array(memberships)
        ax = fig.add_subplot(rows, columns, counter)

        if ltn.default_type == "cuboid":
            # also plot the actual box
            import matplotlib.patches as patches
            import shapely.geometry
            from matplotlib.path import Path

            def _path_for_core(cuboids, d1, d2):
                """Creates the 2d path for a complete core."""

                polygon = None
                for cuboid in cuboids:
                    p_min = cuboid[0]