Ejemplo n.º 1
0
    def drawWordCloud(self):
        filePaths = []
        fileContents = []
        # 输入名成
        dataUrl = 'C:/server/PyServer/data/' + self.mystr

        for root, dirs, files in os.walk(dataUrl):
            for name in files:
                filePath = os.path.join(root, name)
                filePaths.append(filePath)
                f = codecs.open(filePath, 'r', 'utf-8')
                fileContent = f.read()
                f.close()
                fileContents.append(fileContent)

        corpos = pandas.DataFrame({
            'filePath': filePaths,
            'fileContent': fileContents
        })

        segments = []
        filePaths = []

        for index, row in corpos.iterrows():
            filePath = row['filePath']
            fileContent = row['fileContent']
            # 接着调用cut方法,对文件内容进行分词
            segs = jieba.cut(fileContent)
            # 接着遍历每个分词,和分词对应的文件路径一起,把它加到两列中
            for seg in segs:
                segments.append(seg)
                filePaths.append(filePath)

        # 最后我们把得到的结果存在一个数据框中
        segmentDataFrame = pandas.DataFrame({
            'segment': segments,
            'filePath': filePaths
        })

        segStat = segmentDataFrame.groupby(by='segment')['segment'].agg({
            '计数':
            numpy.size
        }).reset_index().sort_index(by=["计数"], ascending=False)

        stopwords = self.get_custom_stopwords()
        fSegStat = segStat[~segStat.segment.isin(stopwords)]

        color = ['#feca57', '#ff6b6b', '#0abde3', '#1dd1a1', '#00d2d3']
        colormap = colors.ListedColormap(color)
        wordcloud = WordCloud(
            font_path='./fonts/simhei.ttf',
            background_color='#333333',
            width=600,
            height=400,
            max_font_size=60,
            colormap=colormap,
        )
        # WordCloud方法接受一个字典结构的输入,我们前面整理出来的词频统计结果是数据框的形式
        # ,因此需要转换,转换的方法,首先把分词设置为数据框的索引,然后在调用一个to_dict()的方法,就可以转换为字典的机构
        words = fSegStat.set_index('segment').to_dict()
        # #接着调用fit_words方法来调用我们的词频
        wycloud = wordcloud.fit_words(words['计数'])
        # 绘图
        plt.imshow(wycloud)
        imgpath = "C:/server/PyServer/img/" + self.sharenum + '.png'
        wordcloud.to_file(imgpath)
Ejemplo n.º 2
0
def discrete_cmap(N=8):
    # define individual colors as hex values
    cpool = [ '#000000', '#00EE00', '#0000EE', '#00EEEE', '#EE0000',
              '#FFFF00', '#EE00EE', '#FFFFFF']
    cmap_i8 = col.ListedColormap(cpool[0:N], 'i8')
    cm.register_cmap(cmap=cmap_i8)
Ejemplo n.º 3
0
    def __init__(self, ax, *args, **kwargs):
        """
        Draw contour lines or filled regions, depending on
        whether keyword arg 'filled' is False (default) or True.

        The first argument of the initializer must be an axes
        object.  The remaining arguments and keyword arguments
        are described in ContourSet.contour_doc.

        """
        self.ax = ax
        self.levels = kwargs.get('levels', None)
        self.filled = kwargs.get('filled', False)
        self.linewidths = kwargs.get('linewidths', None)
        self.linestyles = kwargs.get('linestyles', None)

        self.alpha = kwargs.get('alpha', 1.0)
        self.origin = kwargs.get('origin', None)
        self.extent = kwargs.get('extent', None)
        cmap = kwargs.get('cmap', None)
        self.colors = kwargs.get('colors', None)
        norm = kwargs.get('norm', None)
        self.extend = kwargs.get('extend', 'neither')
        self.antialiased = kwargs.get('antialiased', True)
        self.nchunk = kwargs.get('nchunk', 0)
        self.locator = kwargs.get('locator', None)
        if (isinstance(norm, colors.LogNorm)
                or isinstance(self.locator, ticker.LogLocator)):
            self.logscale = True
            if norm is None:
                norm = colors.LogNorm()
            if self.extend is not 'neither':
                raise ValueError('extend kwarg does not work yet with log scale')
        else:
            self.logscale = False

        if self.origin is not None: assert(self.origin in
                                            ['lower', 'upper', 'image'])
        if self.extent is not None: assert(len(self.extent) == 4)
        if cmap is not None: assert(isinstance(cmap, colors.Colormap))
        if self.colors is not None and cmap is not None:
            raise ValueError('Either colors or cmap must be None')
        if self.origin == 'image': self.origin = mpl.rcParams['image.origin']

        if isinstance(args[0], ContourSet):
            C = args[0].Cntr
            if self.levels is None:
                self.levels = args[0].levels
        else:
            x, y, z = self._contour_args(*args)

            x0 = ma.minimum(x)
            x1 = ma.maximum(x)
            y0 = ma.minimum(y)
            y1 = ma.maximum(y)
            self.ax.update_datalim([(x0,y0), (x1,y1)])
            self.ax.autoscale_view()
            _mask = ma.getmask(z)
            if _mask is ma.nomask:
                _mask = None
            C = _cntr.Cntr(x, y, z.filled(), _mask)
        self.Cntr = C
        self._process_levels()

        if self.colors is not None:
            cmap = colors.ListedColormap(self.colors, N=len(self.layers))
        if self.filled:
            self.collections = cbook.silent_list('collections.PathCollection')
        else:
            self.collections = cbook.silent_list('collections.LineCollection')
        # label lists must be initialized here
        self.labelTexts = []
        self.labelCValues = []

        kw = {'cmap': cmap}
        if norm is not None:
            kw['norm'] = norm
        cm.ScalarMappable.__init__(self, **kw) # sets self.cmap;
        self._process_colors()
        if self.filled:
            if self.linewidths is not None:
                warnings.warn('linewidths is ignored by contourf')
            lowers = self._levels[:-1]
            uppers = self._levels[1:]
            for level, level_upper in zip(lowers, uppers):
                nlist = C.trace(level, level_upper, nchunk = self.nchunk)
                nseg = len(nlist)//2
                segs = nlist[:nseg]
                kinds = nlist[nseg:]

                paths = self._make_paths(segs, kinds)

                col = collections.PathCollection(paths,
                                     antialiaseds = (self.antialiased,),
                                     edgecolors= 'none',
                                     alpha=self.alpha)
                self.ax.add_collection(col)
                self.collections.append(col)
        else:
            tlinewidths = self._process_linewidths()
            self.tlinewidths = tlinewidths
            tlinestyles = self._process_linestyles()
            for level, width, lstyle in zip(self.levels, tlinewidths, tlinestyles):
                nlist = C.trace(level)
                nseg = len(nlist)//2
                segs = nlist[:nseg]
                #kinds = nlist[nseg:]
                col = collections.LineCollection(segs,
                                     linewidths = width,
                                     linestyle = lstyle,
                                     alpha=self.alpha)

                col.set_label('_nolegend_')
                self.ax.add_collection(col, False)
                self.collections.append(col)
        self.changed() # set the colors
Ejemplo n.º 4
0
    def search_shortest_path_dws(self, start, goal):
        """
        start = (y, x)
        goal = (y, x)
        """

        start_goal = np.zeros((self.h, self.w), dtype=int)
        cost = np.zeros((self.h, self.w), dtype=int) + 1E10
        done = np.zeros((self.h, self.w), dtype=bool)
        barrier = np.zeros((self.h, self.w), dtype=bool)
        path = np.zeros((self.h, self.w), dtype=int)
        entrance = np.zeros((self.h, self.w), dtype=bool)

        for iy in range(self.h):
            for ix in range(self.w):
                if iy == start[0] and ix == start[1]:
                    cost[iy, ix] = 0
                    done[iy, ix] = True
                    start_goal[iy, ix] = -255

                if iy == goal[0] and ix == goal[1]:
                    start_goal[iy, ix] = 255

                if self.data[iy, ix] == 1:  # WALL
                    barrier[iy, ix] = True
                if (iy, ix) in self.entrances:
                    entrance[iy, ix] = True

        barrier[start[0], start[1]] = False
        barrier[goal[0], goal[1]] = False

        g = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])

        for i in range(1, 10000000):

            done_next = maximum_filter(done, footprint=g) * ~done
            cost_next = minimum_filter(cost, footprint=g) * done_next
            cost_next[done_next] += 1

            # is_entranceがTrueのそれぞれのセルについて、
            is_entrance = done_next * entrance
            entrance_xy = list(zip(*np.where(is_entrance == True)))
            for ey, ex in entrance_xy:

                if done[ey - 1, ex] == True and self.rooms[ey - 1, ex] != True:
                    cost_next[ey, ex] = 10000000
                    done_next[ey, ex] = False

                if done[ey, ex + 1] == True and self.rooms[ey, ex + 1] != True:
                    cost_next[ey, ex] = 10000000
                    done_next[ey, ex] = False

                if done[ey + 1, ex] == True and self.rooms[ey + 1, ex] != True:
                    cost_next[ey, ex] = 10000000
                    done_next[ey, ex] = False

                if done[ey, ex - 1] == True and self.rooms[ey, ex - 1] != True:
                    cost_next[ey, ex] = 10000000
                    done_next[ey, ex] = False

            cost[done_next] = cost_next[done_next]
            cost[barrier] = 10000000
            done[done_next] = done_next[done_next]
            done[barrier] = False

            if done[goal[0], goal[1]] == True:
                break

        point_now = goal
        cost_now = cost[goal[0], goal[1]]
        route = [goal]

        while cost_now > 0:
            try:
                if cost[point_now[0] - 1, point_now[1]] == cost_now - 1:
                    point_now = (point_now[0] - 1, point_now[1])
                    cost_now = cost_now - 1
                    route.append(point_now)
            except:
                pass
            try:
                if cost[point_now[0] + 1, point_now[1]] == cost_now - 1:
                    point_now = (point_now[0] + 1, point_now[1])
                    cost_now = cost_now - 1
                    route.append(point_now)
            except:
                pass
            try:
                if cost[point_now[0], point_now[1] - 1] == cost_now - 1:
                    point_now = (point_now[0], point_now[1] - 1)
                    cost_now = cost_now - 1
                    route.append(point_now)
            except:
                pass
            try:
                if cost[point_now[0], point_now[1] + 1] == cost_now - 1:
                    point_now = (point_now[0], point_now[1] + 1)
                    cost_now = cost_now - 1
                    route.append(point_now)
            except:
                pass

        route = route[::-1]

        for cell in route:
            ix = cell[1]
            iy = cell[0]
            path[iy, ix] = 1

        if self.debug:

            import matplotlib.pyplot as plt
            import matplotlib.cm as cm
            import matplotlib.colors as colors

            cmap = cm.jet
            cmap_data = cmap(np.arange(cmap.N))
            cmap_data[0, 3] = 0
            customized_jet = colors.ListedColormap(cmap_data)

            cmap = cm.magma
            cmap_data = cmap(np.arange(cmap.N))
            cmap_data[0, 3] = 0
            customized_magma = colors.ListedColormap(cmap_data)

            cmap = cm.cool
            cmap_data = cmap(np.arange(cmap.N))
            cmap_data[0, 3] = 0
            customized_cool = colors.ListedColormap(cmap_data)

            cmap = cm.gist_yarg
            cmap_data = cmap(np.arange(cmap.N))
            cmap_data[0, 3] = 0
            customized_gist_yarg = colors.ListedColormap(cmap_data)

            plt.scatter(start[1], start[0], s=2, c="blue", label="start")
            plt.scatter(goal[1], goal[0], s=2, c="red", label="goal")
            plt.imshow(barrier, cmap="gist_yarg")
            plt.imshow(entrance, cmap=customized_cool)
            plt.legend()
            plt.show()

            plt.scatter(start[1], start[0], s=2, c="blue", label="start")
            plt.scatter(goal[1], goal[0], s=2, c="red", label="goal")
            plt.imshow(self.corridors, cmap=customized_cool)
            plt.legend()
            plt.show()

            plt.imshow(cost, cmap="jet", vmax=100, vmin=0, alpha=0.8)
            plt.imshow(barrier, cmap=customized_gist_yarg)
            plt.scatter(start[1], start[0], s=2, c="blue", label="start")
            plt.scatter(goal[1], goal[0], s=2, c="red", label="goal")
            plt.legend()
            plt.show()

            plt.imshow(path, cmap=customized_cool)
            plt.imshow(barrier, cmap=customized_gist_yarg)
            plt.scatter(start[1], start[0], s=2, c="blue", label="start")
            plt.scatter(goal[1], goal[0], s=2, c="red", label="goal")
            plt.legend()
            plt.show()

        return route
Ejemplo n.º 5
0
                if np.mean(allscores[reg][-1]) > topper:
                    topper = np.mean(allscores[reg][-1])
                    toppertag = [drilis[co][1] for co in comb]
                #print(pi, model.score(X, Y))
            print(reg, topper, toppertag)

        pickle.dump([okcombs, allscores], open(cart_out_gen.format(ensmod) + 'allscores_v2_{}drivs_{}.p'.format(nu, ensmod), 'wb'))
        # fine.

        okcombs, allscores = pickle.load(open(cart_out_gen.format(ensmod) + 'allscores_v2_{}drivs_{}.p'.format(nu, ensmod), 'rb'))

        colo = '#a50026 #d73027 #f46d43 #fdae61 #fee090 #ffffff #e0f3f8 #abd9e9 #74add1 #4575b4 #313695'
        colo = colo.split()
        colo = colo[::-1]
        cmappa = colors.ListedColormap(colo)
        cmappa.set_over('#800026') #662506
        cmappa.set_under('#023858') #542788

        cmappa2 = colors.ListedColormap(colo[1:-1])
        cmappa2.set_over('#800026') #662506
        cmappa2.set_under('#023858') #542788

        for reg in regtip:
            cart_out = cart_out_gen.format(ensmod) + reg + '/'
            ctl.mkdir(cart_out)

            # ctl.printsep()
            # ctl.printsep()
            print(reg)
            ire = int(reg[1])
Ejemplo n.º 6
0
    def plotStamp(self):
        fig_width_px, dpi = 1280, 90
        fig = plt.figure(dpi=dpi)

        num_rows, num_columns = 3, 4
        fig_width = fig_width_px / dpi
        width_per_panel = fig_width / float(num_columns)
        height_per_panel = width_per_panel * self.m.aspect
        fig_height = height_per_panel * num_rows
        fig_height_px = fig_height * dpi
        fig.set_size_inches((fig_width, fig_height))

        levels = self.opts['fill']['levels']
        cmap = colors.ListedColormap(self.opts['fill']['colors'])
        norm = colors.BoundaryNorm(levels, cmap.N)
        filename = self.opts['fill']['filename']

        memberidx = 0
        for j in range(0, num_rows):
            for i in range(0, num_columns):
                member = num_columns * j + i
                if member > 9: break
                spacing_w, spacing_h = 5 / float(fig_width_px), 5 / float(
                    fig_height_px)
                spacing_w = 10 / float(fig_width_px)
                x, y = i * width_per_panel / float(fig_width), 1.0 - (
                    j + 1) * height_per_panel / float(fig_height)
                w, h = (width_per_panel / float(fig_width)) - spacing_w, (
                    height_per_panel / float(fig_height)) - spacing_h
                if member == 9: y = 0

                #print 'member', member, 'creating axes at', x, y
                thisax = fig.add_axes([x, y, w, h])

                thisax.axis('on')
                for axis in ['top', 'bottom', 'left', 'right']:
                    thisax.spines[axis].set_linewidth(0.5)
                self.m.drawcoastlines(ax=thisax, linewidth=0.3)
                self.m.drawstates(linewidth=0.15, ax=thisax)
                self.m.drawcountries(ax=thisax, linewidth=0.3)
                thisax.text(0.03,
                            0.97,
                            member + 1,
                            ha="left",
                            va="top",
                            bbox=dict(boxstyle="square", lw=0.5, fc="white"),
                            transform=thisax.transAxes)

                # plot, unless file that has fill field is missing, then skip
                if member not in self.missing_members[
                        filename] and member < self.ENS_SIZE:
                    cs1 = self.m.contourf(self.x,
                                          self.y,
                                          self.data['fill'][0][memberidx, :],
                                          levels=levels,
                                          cmap=cmap,
                                          norm=norm,
                                          extend='max',
                                          ax=thisax)
                    memberidx += 1

        # use every other tick for large colortables, remove last tick label for both
        if self.opts['fill']['name'] in [
                'goesch3', 'goesch4', 't2', 'precipacc'
        ]:
            ticks = levels[:-1][::2]  # CSS added precipacc
        else:
            ticks = levels[:-1]

        # add colorbar to figure
        cax = fig.add_axes([0.51, 0.3, 0.48, 0.02])
        cb = plt.colorbar(cs1,
                          cax=cax,
                          orientation='horizontal',
                          ticks=ticks,
                          extendfrac=0.0)
        cb.outline.set_linewidth(0.5)
        cb.ax.tick_params(labelsize=9)

        # add init/valid text
        fontdict = {'family': 'monospace', 'size': 13, 'weight': 'bold'}
        initstr = self.initdate.strftime(' Init: %a %Y-%m-%d %H UTC')
        if ((self.ehr - self.shr) == 0):
            validstr = (self.initdate + timedelta(hours=self.shr)
                        ).strftime('Valid: %a %Y-%m-%d %H UTC')
        else:
            validstr1 = (
                self.initdate +
                timedelta(hours=(self.shr - 1))).strftime('%a %Y-%m-%d %H UTC')
            validstr2 = (
                self.initdate +
                timedelta(hours=self.ehr)).strftime('%a %Y-%m-%d %H UTC')
            validstr = "Valid: %s - %s" % (validstr1, validstr2)

        fig.text(0.51,
                 0.22,
                 self.title,
                 fontdict=fontdict,
                 transform=fig.transFigure)
        fig.text(0.51,
                 0.22 - 25 / float(fig_height_px),
                 initstr,
                 transform=fig.transFigure)
        fig.text(0.51,
                 0.22 - 40 / float(fig_height_px),
                 validstr,
                 transform=fig.transFigure)

        # add logo and text below logo
        x, y = fig.transFigure.transform((0.51, 0))
        fig.figimage(plt.imread('ncar.png'), xo=x, yo=y + 15, zorder=1000)
        plt.text(x + 10,
                 y + 5,
                 'ensemble.ucar.edu',
                 fontdict={
                     'size': 9,
                     'color': '#505050'
                 },
                 transform=None)
   Hrs = ['12Z','18Z','00Z','06Z','12Z','18Z','00Z','06Z','12Z','18Z','00Z','06Z','12Z','18Z','00Z','06Z','12Z','18Z','00Z','06Z']



if (mod   == 'cosmo'):
   MOD     = 'COSMO';
elif (mod == 'gfs'):
   MOD     = 'GFS';
elif (mod == 'icon'):
   MOD     = 'ICON';
elif (mod == 'ico13'):
   MOD     = 'ICON'; 

# Tabela para HS
cells  = np.array(hs_sv[0:20]); cells=cells.T               
cmap   = colors.ListedColormap(['mediumspringgreen','yellow','lightsalmon'])
bounds = [0,3,4,25]
norm   = colors.BoundaryNorm(bounds, cmap.N)

img = plt.imshow(cells, cmap=cmap, norm=norm)
img.set_visible(False)
if (str(cyc)=='00'):
   header   = plt.table(cellText=[['']*5], colLabels=[dias[0],dias[1],dias[2],dias[3], dias[4]], loc='center', bbox=[0, 0.8, 1.0, 0.18]) #bbox=[x,y,width,heigh]
else:
   header_0 = plt.table(cellText=[['']*1], colLabels=[dias[0]], loc='center', bbox=[0, 0.8, 0.1, 0.18]) #bbox=[x,y,width,heigh]
   header_1 = plt.table(cellText=[['']*4], colLabels=[dias[1],dias[2],dias[3],dias[4]], loc='center', bbox=[0.1, 0.8, 0.8, 0.18]) #bbox=[x,y,width,heigh]
   header_2 = plt.table(cellText=[['']*1], colLabels=[dias[5]], loc='center', bbox=[0.9, 0.8, 0.1, 0.18]) #bbox=[x,y,width,heigh]

tb = plt.table(cellText = cells, rowLabels = pts, colLabels = Hrs, loc = 'center', cellColours = img.to_rgba(cells), bbox=[0, 0, 1, 0.9])
plt.axis('off')
plt.title('Altura Significativa de Onda (m) CHM/WW3/'+MOD+' '+str(cyc)+'Z '+datai+' Simpson',fontsize=9,loc='left')
Ejemplo n.º 8
0
    def status_plot(self):
        warnings.filterwarnings("ignore")
        fig = plt.figure(figsize=(10, 10))
        ax = fig.add_subplot(111)
        report_matrix = np.zeros(
            (len(self.clusterIDAllowed), len(self.redshiftAllowed)),
            dtype=np.int)
        length_operation = np.product(report_matrix.shape)
        counter = 0
        for cluster_number, cluster_redshift in itertools.product(
                self.clusterIDAllowed, self.redshiftAllowed):

            out_path = os.path.join(
                self.pathSave, self.simulation_name,
                f'halo{self.halo_Num(cluster_number)}',
                f'halo{self.halo_Num(cluster_number)}_{cluster_redshift}')

            if self.sample_completeness[
                    cluster_number,
                    self.redshiftAllowed.index(cluster_redshift)]:
                num_of_files = len([
                    name for name in os.listdir(out_path)
                    if os.path.isfile(os.path.join(out_path, name))
                ])
                report_matrix[cluster_number,
                              self.redshiftAllowed.index(cluster_redshift
                                                         )] = num_of_files
            else:
                report_matrix[
                    cluster_number,
                    self.redshiftAllowed.index(cluster_redshift)] = -1
            yield ((counter + 1) / length_operation
                   )  # Give control back to decorator
            counter += 1

        expected_total_files = 13
        timestr = time.strftime("%d%m%Y-%H%M%S")
        fraction_complete = np.sum(report_matrix[report_matrix > 0]) / (
            np.product(report_matrix.shape) * expected_total_files) * 100

        cmap = colors.ListedColormap(
            ['white', 'black', 'red', 'orange', 'lime'])
        bounds = [
            -1, 0, 0.5, 3.5, expected_total_files - 0.5, expected_total_files
        ]
        norm = colors.BoundaryNorm(bounds, cmap.N)
        ax.imshow(report_matrix,
                  interpolation='nearest',
                  cmap=cmap,
                  norm=norm,
                  origin='lower',
                  aspect=report_matrix.shape[1] / report_matrix.shape[0],
                  extent=(0, len(self.redshiftAllowed), 0, self.totalClusters))

        patch_1 = Patch(facecolor='black',
                        label='0 files',
                        edgecolor='k',
                        linewidth=1)
        patch_2 = Patch(facecolor='red',
                        label='1 - 3 files',
                        edgecolor='k',
                        linewidth=1)
        patch_3 = Patch(facecolor='orange',
                        label=f'4 - {expected_total_files - 1} files',
                        edgecolor='k',
                        linewidth=1)
        patch_4 = Patch(facecolor='lime',
                        label=f'{expected_total_files} files',
                        edgecolor='k',
                        linewidth=1)
        patch_5 = Patch(facecolor='white',
                        label='Excluded',
                        edgecolor='k',
                        linewidth=1)
        ax.legend(handles=[patch_4, patch_3, patch_2, patch_1, patch_5],
                  loc='upper right',
                  labelspacing=1.5,
                  handlelength=1,
                  fontsize=20,
                  bbox_to_anchor=(1.3, 0.75))

        ax.set_title(
            f'{self.simulation:s} output status: {fraction_complete:.0f}\% complete \qquad{timestr:s}',
            size=20)
        ax.set_xlabel(r'redshift', size=20)
        ax.set_ylabel(r'Cluster ID', size=20)
        ax.set_xticks(list(range(0, len(self.redshiftAllowed), 4)))
        redhifts_ticks = [
            self.redshiftAllowed[i]
            for i in range(0, len(self.redshiftAllowed), 4)
        ]
        redhifts_ticks = [f"{redshift_str2num(z):.1f}" for z in redhifts_ticks]
        ax.set_xticklabels(redhifts_ticks)
        plt.tight_layout()
        plt.savefig(os.path.join(
            self.pathSave, self.simulation_name,
            f"{self.simulation_name}_OutputStatusReport_{timestr}.png"),
                    dpi=400)
Ejemplo n.º 9
0
pts = [(5, 4), (5, 21), (1, 40), (17, 40), (30, 40), (37, 42), (23, 25), (28, 4), (15, 11)]

data = np.random.rand(51, 50) * 0
with open('Location values.csv') as file:
    csvData = csv.reader(file, delimiter=',')
    for row in csvData:
        data[int(row[0])][int(row[1])] = float(row[4]) - 22

for i in range(51):
    for j in range(50):
        if((i, j) not in pts):
            d = 0;
            for pt in pts:
                d = d + (1/dist(i, j, pt[0], pt[1]))
                data[i][j] = data[i][j] + (1/dist(i, j, pt[0], pt[1]) * data[pt[0]][pt[1]])
            data[i][j] = data[i][j] / d

# create discrete colormap
cmap = colors.ListedColormap(['green', 'yellow', 'orange', 'red', 'purple', 'black'])
bounds = [0, 1, 2, 10, 17, 34]
norm = colors.BoundaryNorm(bounds, cmap.N)
fig, ax = plt.subplots()
ax.imshow(data, cmap=cmap, norm=norm)
# draw gridlines
ax.grid(which='major', axis='both', linestyle=':', color='k', linewidth=0.5)
ax.set_xticks(np.arange(-.5, 50, 1))
ax.set_yticks(np.arange(-.5, 51, 1))

plt.savefig('CO.png')
legend_lfc1 = mpatches.Patch(color='blue', label='1')  # 1=brine sand
legend_lfc2 = mpatches.Patch(color='green', label='2')  # 2=oil sand
legend_lfc3 = mpatches.Patch(color='red', label='3')  # 3=gas sand
legend_lfc4 = mpatches.Patch(color='#996633', label='4')  # 4=shale

#===== creazione colormap facies
import matplotlib.colors as colors
#      0=undef   1=bri  2=oil   3=gas 4=shale
ccc = [
    '#B3B3B3',
    'blue',
    'green',
    'red',
    '#996633',
]
cmap_facies = colors.ListedColormap(ccc[0:len(ccc)], 'indexed')


# funzione voigt-reuss-hill
def vrh(volumes, k, mu):
    f = np.array(volumes).T
    k = np.resize(np.array(k), np.shape(f))
    mu = np.resize(np.array(mu), np.shape(f))

    k_u = np.sum(f * k, axis=1)
    k_l = 1. / np.sum(f / k, axis=1)
    mu_u = np.sum(f * mu, axis=1)
    mu_l = 1. / np.sum(f / mu, axis=1)
    k0 = (k_u + k_l) / 2.
    mu0 = (mu_u + mu_l) / 2.
    return [k_u, k_l, mu_u, mu_l, k0, mu0]
    print(str(numSides) + " =========== LOAD DATA ===========")
    _test_x_data, _test_y_data = load_raster_data(
        "../data/problem2/raster_pc/" + BUFFER_OPT + "/test_" + str(numSides) +
        ".csv")
    test_x_data.extend(_test_x_data)
    test_y_data.extend(_test_y_data)

# result file
print("Accuraccy : " + open(RESULT_FILE_PATH, 'r').readline())
result_data = np.loadtxt(RESULT_FILE_PATH, dtype=np.float32, skiprows=1)
# result_data = result_data.reshape(result_data.shape[0], 1)

# polygon
for test_i in TEST_TARGET:
    coords_x = []
    coords_y = []

    # create discrete colormap
    cmap = colors.ListedColormap(['red', 'blue'])
    bounds = [0, 10, 20]
    norm = colors.BoundaryNorm(bounds, cmap.N)

    fig, ax = plt.subplots()
    ax.imshow(data, cmap=cmap, norm=norm)

    # draw gridlines
    ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2)
    ax.set_xticks(np.arange(WHOLE_RANGE[0], WHOLE_RANGE[1], WIDTH_NUM))
    ax.set_yticks(np.arange(WHOLE_RANGE[2], WHOLE_RANGE[3], HEIGHT_NUM))

    plt.show()
Ejemplo n.º 12
0
color_breaks_int = sorted(np.append(quantils, int_min_max))

for key, stats_year in zip(data_list, data_analysis):
    data_year = data_year = data_list.get(key)

    #plotting
    #prepare information
    year = data_analysis_list[stats_year]['date']
    plotfilename_det = 'detections_' + str(year)
    plotfilename_int = 'intensity_' + str(year)

    print('Plotting: ', year)

    #plotting number of detected hotspots
    fig, ax = plt.subplots(1, figsize=(12, 10))
    cmap = colors.ListedColormap(
        ['#2b83ba', '#abdda4', '#ffffbf', '#fdae61', '#d7191c'])
    norm = colors.BoundaryNorm(boundaries=color_breaks_det, ncolors=5)

    area_shape.plot(ax=ax, color='#DDDDDD', edgecolor='grey', linewidth=1)
    data_year.plot(ax=ax, color='grey')
    data_year.plot(ax=ax, column='indexesFound', cmap=cmap, norm=norm)

    fig.suptitle('Number of Detected Hotspots', fontsize=18)
    ax.set_title('Date: {y}'.format(y=year), fontdict={'fontsize': 13})

    #axis colorbar
    divider = make_axes_locatable(ax)
    cax = divider.append_axes('right', size='3 %', pad=0.05)
    vmax = data_year.frpMWkm2Avg.max()

    #handeling case with only one unique value of number of detected hotspots
Ejemplo n.º 13
0
    def plot_structured_grid_interactive(
        self,
        name: str,
        render_topography: bool = False,
        **kwargs,
    ):
        """Plot interactive 3-D geomodel with three cross sections in subplot.

        Args:
            geo_model: Geomodel object with solutions.
            name (str): Can be either one of the following
                'lith' - Lithology id block.
                'scalar' - Scalar field block.
                'values' - Values matrix block.
            render_topography: Render topography. Defaults to False.
            **kwargs:

        Returns:
            (Vista) GemPy Vista object for plotting.
        """
        mesh = self.plot_structured_grid(name=name,
                                         render_topography=render_topography,
                                         **kwargs)[0]

        # define colormaps
        if name == "lith":
            cmap = mcolors.ListedColormap(
                list(self._get_color_lot(faults=False)))
        elif name == "scalar":
            cmap = cm.viridis

        # callback functions for subplots
        def xcallback(normal, origin):
            self.p.subplot(1)
            self.p.add_mesh(mesh.slice(normal=normal, origin=origin),
                            name="xslc",
                            cmap=cmap)

        def ycallback(normal, origin):
            self.p.subplot(2)
            self.p.add_mesh(mesh.slice(normal=normal, origin=origin),
                            name="yslc",
                            cmap=cmap)

        def zcallback(normal, origin):
            self.p.subplot(3)
            self.p.add_mesh(mesh.slice(normal=normal, origin=origin),
                            name="zslc",
                            cmap=cmap)

        # cross section widgets
        self.p.subplot(0)
        self.p.add_plane_widget(xcallback, normal="x")
        self.p.subplot(0)
        self.p.add_plane_widget(ycallback, normal="y")
        self.p.subplot(0)
        self.p.add_plane_widget(zcallback, normal="z")

        # Lock other three views in place
        self.p.subplot(1)
        self.p.view_yz()
        self.p.disable()
        self.p.subplot(2)
        self.p.view_xz()
        self.p.disable()
        self.p.subplot(3)
        self.p.view_xy()
        self.p.disable()
    def ResponseCountMatrix(
            self,
            annot_df,
            heatmap_df,
            lookback=15,
            fill_null_days=False,
            query: Union[str, dict] = None,
            figsize=(14, 10),
            **kwargs,
    ) -> plt.figure:
        """Creates a calendar heatmap

        x axis shows model names and y axis the dates. Data in each cell is the total number
        of responses. The color indicates where responses increased/decreased or
        did not change compared to the previous day

        Parameters
        ----------
        lookback : int
            Defines how many days to look back at data from the last snapshot
        fill_null_days : bool
            If True, null values will be generated in the dataframe for
            days where there is no model snapshot
        query : Union[str, dict]
            The query to supply to _apply_query
            If a string, uses the default Pandas query function
            Else, a dict of lists where the key is column name in the dataframe
            and the corresponding value is a list of values to keep in the dataframe
        figsize : tuple
            Size of graph

        Returns
        -------
        plt.figure
        """

        f, ax = plt.subplots(figsize=figsize)
        myColors = ["r", "orange", "w"]
        colorText = ["Decreased", "No Change", "Increased or NA"]
        cmap = colors.ListedColormap(myColors)
        sns.heatmap(
            heatmap_df.T,
            annot=annot_df.T,
            mask=annot_df.T.isnull(),
            ax=ax,
            linewidths=0.5,
            fmt=".0f",
            cmap=cmap,
            vmin=-1,
            vmax=1,
            cbar=False,
        )
        bottom, top = ax.get_ylim()
        ax.set_ylim(bottom + 0.5, top - 0.5)
        patches = [
            mpatches.Patch(color=myColors[i], label=colorText[i])
            for i in range(len(myColors))
        ]

        legend = plt.legend(
            handles=patches,
            bbox_to_anchor=(1.05, 1),
            loc=2,
            borderaxespad=0.5,
            frameon=True,
        )
        frame = legend.get_frame()
        frame.set_facecolor("lightgrey")
        return ax
Ejemplo n.º 15
0
from Bio import PDB
from matplotlib import colors
"""
Written by Gábor Erdős, 2017
Contact info: gerdos[at]caesar.elte.hu

The preferences were calculated from the following artice:
Lovell et al. Structure validation by Calpha geometry: phi,psi and Cbeta deviation. 2003
DOI: 10.1002/prot.10286
"""

# General variable for the background preferences
rama_preferences = {
    "General": {
        "file": "pref_general.data",
        "cmap": colors.ListedColormap(['#FFFFFF', '#B3E8FF', '#7FD9FF']),
        "bounds": [0, 0.0005, 0.02, 1],
    },
    "GLY": {
        "file": "pref_glycine.data",
        "cmap": colors.ListedColormap(['#FFFFFF', '#FFE8C5', '#FFCC7F']),
        "bounds": [0, 0.002, 0.02, 1],
    },
    "PRO": {
        "file": "pref_proline.data",
        "cmap": colors.ListedColormap(['#FFFFFF', '#D0FFC5', '#7FFF8C']),
        "bounds": [0, 0.002, 0.02, 1],
    },
    "PRE-PRO": {
        "file": "pref_preproline.data",
        "cmap": colors.ListedColormap(['#FFFFFF', '#B3E8FF', '#7FD9FF']),
Ejemplo n.º 16
0
# Check to see if matplotlib is at least sorta up to date
from distutils.version import LooseVersion

mpl_ge_150 = LooseVersion(mpl.__version__) >= "1.5.0"

# TODO: This block should probably be moved/removed soon
##########################################################################
## Compatability with old stuff for now
##########################################################################

ddl_heat = [
    '#DBDBDB', '#DCD5CC', '#DCCEBE', '#DDC8AF', '#DEC2A0', '#DEBB91',
    '#DFB583', '#DFAE74', '#E0A865', '#E1A256', '#E19B48', '#E29539'
]

ddlheatmap = mplcol.ListedColormap(ddl_heat)

##########################################################################
## Color Utils
##########################################################################


def get_color_cycle():
    if mpl_ge_150:
        cyl = mpl.rcParams['axes.prop_cycle']
        # matplotlib 1.5 verifies that axes.prop_cycle *is* a cycler
        # but no garuantee that there's a `color` key.
        # so users could have a custom rcParmas w/ no color...
        try:
            return [x['color'] for x in cyl]
        except KeyError:
Ejemplo n.º 17
0
#
# #k_prediction_times = np.divide(k_prediction_times, max(k_prediction_times))
# x_axis = np.arange(2, 51)
# plt.plot(x_axis, np.mean(k_accuracy_scores, axis = 1))
# plt.xlabel('k')
# plt.ylabel('Accuracy Score')
# plt.title('Accuracy score of kNN for different values of k averaged over 400 repeats')
# plt.show()

# X = iris.data[:, :2]
y = iris.target

h = .02  # step size in the mesh

# Create color maps
cmap = colors.ListedColormap(['cadetblue', 'firebrick', 'gold'])
cmap_scat = colors.ListedColormap(['blue', 'red', 'yellow'])

for k in [2, 5]:
    knn_iris = neighbors.KNeighborsClassifier(n_neighbors=k)
    knn_iris.fit(X, y)
    y_pred = knn_iris.predict(X)
    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, x_max]x[y_min, y_max].
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    Z = knn_iris.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
def plotmap(data, lat, lon, **kwargs):
    """
    => Parâmetros obrigatórios:
    :param data:          = matriz a ser plotada (np.array 2d)
    :param lat:           = pontos da grade na latitude (np.array) (-90:90)
    :param lon:           = pontos da grade na longitude (np.array) (-180:180)

    => Parâmetros opcionais:
    resol: (string)
        c = resolução muito baixa
        l = resolução baixa
        i = resolução intermediária (padrão)
        h = resolução alta
        f = resolução muito alta
    maptype       = Tipo do mapa: fillc, fill e shaded (padrão) (string)
    fig_name      = Nome da figura: 'my_picture.png' (padrão) (string)
    fig_title     = Título da figura: 'My Title' (padrão) (string)
    barloc        = Posição da paleta: 'bellow' ou 'right' (padrão) (string)
    barinf        = Se a paleta tende a infinito: 'both', 'max', 'min' ou 'neither' (padrão) (string)
    ocean_mask    = Mascara sobre o oceano: 1 ou 0 (padrão) (inteiro)
    parallels     = Range e intervalo das paralelas do globo:
                    Ex.: np.arange(-90., 91., 10.) (padrão) (np.array)
    meridians     = Range e intervalo dos meridianos do globo:
                    Ex.: np.arange(-160., 161., 10.) (padrão) (np.array)
    dirshapefile  = Diretório onde encontra-se o shape a ser plotado. (string)
    shapefile     = Arquivo do tipo shape a ser plotado no mapa. (string)
                    O padrão é o shape 'world' disponível nesse pacote.
    latsouthpoint = ponto mais ao sul   (float)
    latnorthpoint = ponto mais ao norte (float)
    lonwestpoint  = ponto mais ao oeste (float)
    loneastpoint  = ponto mais ao leste (float)
    barlevs       = Níveis da paleta de cores (list)
    barcolor      = Cores em hexadecimal da paleta de cores (list)
    """

    # colormap.set_bad('w', 1.0)

    # TODO: http://stackoverflow.com/a/7172970

    maptype = kwargs.get('maptype', 'shade')
    fig_name = kwargs.get('fig_name', 'my_picture.png')
    fig_title = kwargs.get('fig_title', 'My Title')
    barloc = kwargs.get('barloc', 'bellow')
    barinf = kwargs.get('barinf', 'neither')
    resol = kwargs.get('resol', 'c')
    parallels = kwargs.get('parallels', np.arange(-90., 91., 15.))
    meridians = kwargs.get('meridians', np.arange(0., 360., 15.))
    barlevs = kwargs.get('barlevs', np.linspace(np.min(data), np.max(data),
                                                10))
    barcolor = kwargs.get(
        'barcolor',
        ('#000092', '#0000ED', '#0031FF', '#0059FF', '#0081FF', '#00A5FF',
         '#00CDFF', '#2CFFCA', '#6DFF8A', '#8AFF6D', '#CAFF2C', '#EBFF0C',
         '#FFB900', '#FF7300', '#FF2900', '#BF0000', '#920000'))
    latsouthpoint = kwargs.get('latsouthpoint', np.nanmin(lat) + 1)
    latnorthpoint = kwargs.get('latnorthpoint', np.nanmax(lat))
    lonwestpoint = kwargs.get('lonwestpoint', np.min(lon) + 1)
    loneastpoint = kwargs.get('loneastpoint', np.max(lon))
    dpi = kwargs.get('dpi', 200)

    if maptype == 'shade':
        # ajuste nos pontos do plot
        deltalat = np.mean(np.diff(lat)) / 2.
        deltalon = np.mean(np.diff(lon)) / 2.
        lat = lat - deltalat
        lon = lon - deltalon

    # verifica se o dado é 2d
    if data.ndim != 2:
        print('\n => Erro ao plotar mapa! Verifique dims do dado!')
        print('\n => O dado deve ser um Numpy Array 2d!')
        print('\n => Dims atual: {dims}\n'.format(dims=data.ndim))
        raise SystemExit  # changed here

    fig = plt.figure(figsize=(12, 6))

    mymap = Basemap(projection='cyl',
                    llcrnrlat=latsouthpoint,
                    urcrnrlat=latnorthpoint,
                    llcrnrlon=lonwestpoint,
                    urcrnrlon=loneastpoint,
                    resolution=resol,
                    suppress_ticks=True)

    mymap.drawmeridians(meridians,
                        labels=[0, 0, 0, 1],
                        linewidth=0.001,
                        fontsize=6)

    mymap.drawparallels(parallels,
                        labels=[1, 0, 0, 0],
                        linewidth=0.001,
                        fontsize=6)

    lons, lats = np.meshgrid(lon, lat)

    x, y = mymap(lons, lats)

    if barinf == 'both':

        cpalunder = barcolor[0]
        cpalover = barcolor[-1]
        barcolor = barcolor[1:-1]
        my_cmap = c.ListedColormap(barcolor)
        my_cmap.set_under(cpalunder)
        my_cmap.set_over(cpalover)

    elif barinf == 'max':

        cpalover = barcolor[-1]
        barcolor = barcolor[:-1]
        my_cmap = c.ListedColormap(barcolor)
        my_cmap.set_over(cpalover)

    elif barinf == 'min':

        cpalunder = barcolor[0]
        barcolor = barcolor[1:]
        my_cmap = c.ListedColormap(barcolor)
        my_cmap.set_under(cpalunder)

    elif barinf == 'neither':

        my_cmap = c.ListedColormap(barcolor)

    else:

        print('Use neither, both, min, max para barinfo!')
        raise SystemExit

    norm = BoundaryNorm(barlevs, ncolors=my_cmap.N, clip=False)

    if maptype == 'shade':

        cs = plt.pcolormesh(x, y, data, cmap=my_cmap, norm=norm)

    elif maptype == 'fill':

        cs = plt.contourf(x,
                          y,
                          data,
                          levels=barlevs,
                          extend=barinf,
                          latlon=True,
                          norm=norm,
                          cmap=my_cmap)

    elif maptype == 'fillc':

        plt.rcParams['contour.negative_linestyle'] = 'solid'

        cs = plt.contourf(x,
                          y,
                          data,
                          levels=barlevs,
                          extend=barinf,
                          latlon=True,
                          norm=norm,
                          cmap=my_cmap)

        cs = plt.contour(x,
                         y,
                         data,
                         levels=barlevs,
                         colors='k',
                         linewidths=0.5)

        plt.clabel(cs, inline=True, inline_spacing=2, fontsize=7., fmt='%1.1f')

    elif maptype == 'contour':

        plt.rcParams['contour.negative_linestyle'] = 'solid'

        cs = plt.contour(x,
                         y,
                         data,
                         levels=barlevs,
                         colors='k',
                         linewidths=0.5)

        plt.clabel(cs, inline=True, inline_spacing=2, fontsize=7., fmt='%1.1f')

    else:

        print('ERRO!: Use shade, fill or fillc para o tipo de mapa (maptype)!')
        raise SystemExit

    if maptype == 'shade' or maptype == 'fill':

        bar = mymap.colorbar(cs,
                             location=barloc,
                             spacing='uniform',
                             ticks=barlevs,
                             extendfrac='auto',
                             extend=barinf,
                             pad='8%')

        bar.ax.tick_params(labelsize=6)

    # mymap.drawcoastlines()

    mymap.fillcontinents(color='gray', lake_color='gray')

    # mymap.drawrivers(linewidth=0.2, color='gray')

    plt.title(fig_title, fontsize=12)

    plt.savefig(fig_name, bbox_inches='tight', dpi=dpi)

    plt.close()
Ejemplo n.º 19
0
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.ticker as plticker
from matplotlib import colors
import time
from Grid import *

#Reglage des couleurs
Contrast_constant=1
Clist=[]
A=(np.linspace(1,0.2,10))*Contrast_constant
B=(np.linspace(0.2,0.2,10))*Contrast_constant
C=(np.linspace(0.2,1,10))*Contrast_constant
for i in range(10): 
    Clist.append((A[i],B[i],C[i]))
cmap = colors.ListedColormap(np.concatenate((Clist,np.flip(Clist,0)),axis=0))
bounds = np.linspace(0,2*np.pi,20)
norm = colors.BoundaryNorm(bounds, cmap.N)


#Constantes de la simulation
length_cycle =1
nt = 200
Sizefig=6


# instantiate a configuration
config=Grid(128,1,1.7)
Angles=config.angles
U=np.cos(Angles)*2
V=np.sin(Angles)*2
Ejemplo n.º 20
0
# molar volume m3/mol
arrays = [arr / 16.043 * 0.024465403697038 * 1e9 for arr in arrays]

# sum of regular and unintended emission
arrays[1] += arrays[0]
arrays[2] += arrays[0]

# Reproduce Mrinali/Gary's surfer color scale
# matplotlib.colors.ListedColormap
# https://matplotlib.org/api/_as_gen/matplotlib.colors.ListedColormap.html
# https://matplotlib.org/tutorials/colors/colormap-manipulation.html
cmap = colors.ListedColormap([
    '#D6FAFE',
    '#02FEFF',
    '#C4FFC4',
    '#01FE02',
    '#FFEE02',
    '#FAB979',
    '#EF6601',
    '#FC0100',
])
# also setting colors for under/overflow
cmap.set_under('#FFFFFF')
cmap.set_over('#000000')

# Define a normalization from values -> colors
# https://matplotlib.org/api/_as_gen/matplotlib.colors.BoundaryNorm.html
# https://matplotlib.org/tutorials/colors/colormapnorms.html
bndry = [1, 10, 50, 100, 200, 500, 1000, 2000]
norm = colors.BoundaryNorm(bndry, len(bndry))

# options passed to each of three plots
Ejemplo n.º 21
0
# http://scipython.com/blog/the-forest-fire-model/

# SET VALUES HERE
growth_prob1 = 0.25
growth_prob2 = 0.25
lightning_prob = 0.001

# Displacements from a cell to its eight nearest neighbours
neighbourhood = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0),
                 (1, 1))
EMPTY, TREE1, FIRE, TREE2 = 0, 1, 2, 3
# Colours for visualization: black for EMPTY, green for TREE and orange
# for FIRE. Note that for the colormap to work, this list and the bounds list
# must be one larger than the number of different values in the array.
colors_list = ['black', 'green', 'orange', (0, 0, 0), 'greenyellow']
cmap = colors.ListedColormap(colors_list)
bounds = [0, 1, 2, 3, 4]
norm = colors.BoundaryNorm(bounds, cmap.N)


def iterate(X):
    """Iterate the forest according to the forest-fire rules."""

    # The boundary of the forest is always empty, so only consider cells
    # indexed from 1 to nx-2, 1 to ny-2
    X1 = np.zeros((ny, nx))
    for ix in range(1, nx - 1):
        for iy in range(1, ny - 1):
            if X[iy, ix] == EMPTY:
                myrandom = np.random.random()
                if myrandom <= p1:
Ejemplo n.º 22
0
def axplot_ChangeProbs(ax,
                       change_probs,
                       wt_colors,
                       ttl='',
                       vmin=0,
                       vmax=1,
                       cmap='Blues',
                       cbar_ttl=''):
    'axes plot cluster change probabilities'

    num_clusters = change_probs.shape[0]

    # clsuter transition plot
    pc = ax.pcolor(
        change_probs,
        cmap=cmap,
        vmin=vmin,
        vmax=vmax,
    )

    # add colorbar
    cbar = plt.colorbar(pc, ax=ax)
    cbar.ax.tick_params(labelsize=8)
    if vmin != 0 or vmax != 1:
        cbar.set_ticks(np.linspace(vmin, vmax, 6))
    cbar.ax.set_ylabel(cbar_ttl, rotation=270, labelpad=20)

    # customize axes
    ax.set_xticks(np.arange(num_clusters) + 0.5)
    ax.set_yticks(np.arange(num_clusters) + 0.5)
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.set_title(ttl, {'fontsize': 10, 'fontweight': 'bold'})

    # add custom color axis
    ccmap = mcolors.ListedColormap([tuple(r) for r in wt_colors])

    # custom color axis positions
    ax_pos = ax.get_position()
    cax_x_pos = [ax_pos.x0, ax_pos.y0 - 0.03, ax_pos.width, 0.02]
    cax_y_pos = [
        ax_pos.x0 - 0.03 / _faspect, ax_pos.y0, 0.02 / _faspect, ax_pos.height
    ]

    # custom color axis X
    cax_x = ax.figure.add_axes(cax_x_pos)
    cbar_x = ColorbarBase(
        cax_x,
        cmap=ccmap,
        orientation='horizontal',
        norm=mcolors.Normalize(vmin=0, vmax=num_clusters),
    )
    cbar_x.set_ticks([])

    # custom color axis Y
    cax_y = ax.figure.add_axes(cax_y_pos)
    cbar_y = ColorbarBase(
        cax_y,
        cmap=ccmap,
        orientation='vertical',
        norm=mcolors.Normalize(vmin=0, vmax=num_clusters),
    )
    cbar_y.set_ticks([])
Ejemplo n.º 23
0
    def plot_colormapped(self, u, v, c, bounds=None, colors=None, **kwargs):
        r"""Plot u, v data, with line colored based on a third set of data.

        Plots the wind data on the hodograph, but with a colormapped line. Takes a third
        variable besides the winds and either a colormap to color it with or a series of
        bounds and colors to create a colormap and norm to control colormapping.
        The bounds must always be in increasing order. For using custom bounds with
        height data, the function will automatically interpolate to the actual bounds from the
        height and wind data, as well as convert the input bounds from
        height AGL to height above MSL to work with the provided heights.

        Simple wrapper around plot so that pressure is the first (independent)
        input. This is essentially a wrapper around `semilogy`. It also
        sets some appropriate ticking and plot ranges.

        Parameters
        ----------
        u : array_like
            u-component of wind
        v : array_like
            v-component of wind
        c : array_like
            data to use for colormapping
        bounds: array-like, optional
            Array of bounds for c to use in coloring the hodograph.
        colors: list, optional
            Array of strings representing colors for the hodograph segments.
        kwargs
            Other keyword arguments to pass to :class:`matplotlib.collections.LineCollection`

        Returns
        -------
        matplotlib.collections.LineCollection
            instance created

        See Also
        --------
        :meth:`Hodograph.plot`

        """
        u, v, c = _delete_masked_points(u, v, c)

        # Plotting a color segmented hodograph
        if colors:
            cmap = mcolors.ListedColormap(colors)
            # If we are segmenting by height (a length), interpolate the bounds
            if bounds.dimensionality == {'[length]': 1.0}:

                # Find any bounds not in the data and interpolate them
                interpolation_heights = [
                    bound.m for bound in bounds if bound not in c
                ]
                interpolation_heights = np.array(
                    interpolation_heights) * bounds.units
                interpolation_heights = (np.sort(interpolation_heights) *
                                         interpolation_heights.units)
                (interpolated_heights, interpolated_u,
                 interpolated_v) = interp(interpolation_heights, c, c, u, v)

                # Combine the interpolated data with the actual data
                c = concatenate([c, interpolated_heights])
                u = concatenate([u, interpolated_u])
                v = concatenate([v, interpolated_v])
                sort_inds = np.argsort(c)
                c = c[sort_inds]
                u = u[sort_inds]
                v = v[sort_inds]

                # Unit conversion required for coloring of bounds/data in dissimilar units
                # to work properly.
                c = c.to_base_units()  # TODO: This shouldn't be required!
                bounds = bounds.to_base_units()
            # If segmenting by anything else, do not interpolate, just use the data
            else:
                bounds = np.asarray(bounds) * bounds.units

            norm = mcolors.BoundaryNorm(bounds.magnitude, cmap.N)
            cmap.set_over('none')
            cmap.set_under('none')
            kwargs['cmap'] = cmap
            kwargs['norm'] = norm
            line_args = self._form_line_args(kwargs)

        # Plotting a continuously colored line
        else:
            line_args = self._form_line_args(kwargs)

        # Do the plotting
        lc = colored_line(u, v, c, **line_args)
        self.ax.add_collection(lc)
        return lc
Ejemplo n.º 24
0
def Plot_Compare_PerpYear(num_clusters,
                          bmus_values_sim,
                          bmus_dates_sim,
                          bmus_values_hist,
                          bmus_dates_hist,
                          n_sim=1,
                          month_ini=1,
                          show=True):
    '''
    Plot simulated - historical bmus comparison in a perpetual year

    bmus_dates requires 1 day resolution time
    bmus_values set min value has to be 1 (not 0)
    '''

    # check dates have 1 day time resolution
    td_h = bmus_dates_hist[1] - bmus_dates_hist[0]
    td_s = bmus_dates_sim[1] - bmus_dates_sim[0]
    if td_h.days != 1 or td_s.days != 1:
        print('PerpetualYear bmus comparison skipped.')
        print('timedelta (days): Hist - {0}, Sim - {1})'.format(
            td_h.days, td_s.days))
        return

    # plot figure
    fig, (ax_hist, ax_sim) = plt.subplots(2,
                                          1,
                                          figsize=(_faspect * _fsize, _fsize))

    # historical perpetual year
    axplot_PerpYear(
        ax_hist,
        num_clusters,
        bmus_values_hist,
        bmus_dates_hist,
        num_sim=1,
        month_ini=month_ini,
    )
    ax_hist.set_title('Historical')

    # simulated perpetual year
    axplot_PerpYear(
        ax_sim,
        num_clusters,
        bmus_values_sim,
        bmus_dates_sim,
        num_sim=n_sim,
        month_ini=month_ini,
    )
    ax_sim.set_title('Simulation')

    # add custom colorbar
    np_colors_int = GetClusterColors(num_clusters)
    ccmap = mcolors.ListedColormap([tuple(r) for r in np_colors_int])
    cax = fig.add_axes([0.92, 0.125, 0.025, 0.755])
    cbar = ColorbarBase(
        cax,
        cmap=ccmap,
        norm=mcolors.Normalize(vmin=0, vmax=num_clusters),
        ticks=np.arange(num_clusters) + 0.5,
    )
    cbar.ax.tick_params(labelsize=8)
    cbar.set_ticklabels(range(1, num_clusters + 1))

    # text
    fig.suptitle('Perpetual Year', fontweight='bold', fontsize=12)

    # show and return figure
    if show: plt.show()
    return fig
Ejemplo n.º 25
0
import matplotlib.pyplot as plt
from matplotlib import colors
from pprint import pprint as pp
import numpy as np

cmap = colors.ListedColormap([
    '#000000', '#0074D9', '#FF4136', '#2ECC40', '#FFDC00', '#AAAAAA',
    '#F012BE', '#FF851B', '#7FDBFF', '#870C25'
])
norm = colors.Normalize(vmin=0, vmax=9)


def plotResults(task_samples, predictions):
    for sample, prediction in zip(task_samples, predictions):
        t_in, t_out, prediction = np.array(sample["input"]), np.array(
            sample["output"]), np.array(prediction)
        titles = [
            f'Input {t_in.shape}', f'Output {t_out.shape}',
            f'Predicted {prediction.shape}'
        ]
        figures = [t_in, t_out, prediction]
        fig, axs = plt.subplots(1, 3, figsize=(2 * 3, 32))
        for i, (figure, title) in enumerate(zip(figures, titles)):
            plotOne(axs[i], figure, title)
        plt.show()


def showTotalColors():
    # 0:black, 1:blue, 2:red, 3:greed, 4:yellow,
    # 5:gray, 6:magenta, 7:orange, 8:sky, 9:brown
    plt.figure(figsize=(5, 2), dpi=100)
Ejemplo n.º 26
0
    def plot_landuse(self,
                     landuse,
                     catchments,
                     attribute,
                     categoryfile,
                     output=None,
                     datatype='raw',
                     overwrite=False,
                     pixels=1000,
                     border=0.02,
                     lw=0.5,
                     show=False,
                     verbose=True,
                     vverbose=False):
        """
        Makes a plot of the landuse of a catchment shapefile on top of a
        raster landuse file.
        """

        if self.order is None:
            print('error: no landuse aggregation file information provided\n')
            raise

        self.read_categoryfile(categoryfile)

        if verbose: print('generating a {} land use plot\n'.format(datatype))

        # make the figure

        fig = pyplot.figure()
        subplot = fig.add_subplot(111, aspect='equal')
        subplot.tick_params(axis='both', which='major', labelsize=11)

        # add the title

        if datatype == 'results': title = 'Land Use Fractions'
        else: title = 'Raw Land Use Data'

        subplot.set_title(title, size=14)

        # open the shapefile and get the bounding box

        s = Reader(catchments, shapeType=5)

        xmin, ymin, xmax, ymax = s.bbox

        # get the index of the field for the attribute matching

        index = [f[0] for f in s.fields].index(attribute) - 1

        # set up a custom colormap using the rgbs supplied in the aggregate file

        color_table = [(self.reds[g] / 255, self.greens[g] / 255,
                        self.blues[g] / 255) for g in self.order]

        cmap = colors.ListedColormap(color_table)

        # provide the cutoff boundaries for the mapping of values to the table

        bounds = [i - 0.5 for i in range(len(self.order) + 1)]

        # create a norm to map the bounds to the colors

        norm = colors.BoundaryNorm(bounds, cmap.N)

        # get the pixel width and origin

        w = (xmax - xmin) / pixels

        # calculate the image array height and the height of a pixel

        height = int(numpy.ceil((ymax - ymin) / (xmax - xmin)) * pixels)
        h = (ymax - ymin) / height

        # set up the image array

        image_array = numpy.zeros((height, pixels), dtype='uint8')

        # get the land use fraction for each category

        if datatype == 'results':

            # iterate through the shapes and make patches

            for i in range(len(s.records())):
                comid = s.record(i)[index]
                points = numpy.array(s.shape(i).points)

                # convert the shape to pixel coordinates

                pixel_polygon = [(get_pixel(x, xmin, w), get_pixel(y, ymin, h))
                                 for x, y in points]

                # make a PIL image to use as a mask

                rasterpoly = Image.new('L', (pixels, height), 1)
                rasterize = ImageDraw.Draw(rasterpoly)

                # rasterize the polygon

                rasterize.polygon(pixel_polygon, 0)

                # convert the PIL array to numpy boolean to use as a mask

                mask = 1 - numpy.array(rasterpoly)

                # get the total number of pixels in the shape

                tot = mask.sum()

                # iterate from left to right and get the fraction of the total
                # area inside the shape as a function of x (takes into account
                # the depth)

                fractions = [column.sum() / tot for column in mask.transpose()]
                area_cdf = [
                    sum(fractions[:i + 1]) for i in range(len(fractions))
                ]

                # convert the land use fractions into a land use cdf

                fractions = [self.landuse[comid][g] for g in self.order]
                land_cdf = [
                    sum(fractions[:i + 1]) for i in range(len(fractions))
                ]

                # use the area cdf to determine the break points for the land
                # use patches. note this array does not account for the masking
                # of the patch. thus there are n+1 vertical bands. the first
                # and last are the "empty" (first in the aggregate file). in
                # between the break points are determined from the area cdf.

                color_array = numpy.zeros(len(mask[0]), dtype='uint8')

                # find the break point for each band by looping through the land
                # ues cdf and filling from left to right

                i = 0
                for p, n in zip(land_cdf, range(len(self.order))):

                    # move from left to right nuntil the area_cdf exceeds
                    # the land area cdf

                    while area_cdf[i] <= p:
                        color_array[i] = n
                        if i < len(area_cdf) - 1: i += 1
                        else: break

                # multiply the color band array by the mask to get the img

                sub_img = mask * color_array

                # add the new mask to the watershed image

                image_array = image_array + sub_img

                # add a patch for the shape boundary

                subplot.add_patch(
                    self.make_patch(points, (1, 0, 0, 0), width=lw))

            # show the bands

            bbox = s.bbox[0], s.bbox[2], s.bbox[1], s.bbox[3]
            im = subplot.imshow(image_array,
                                extent=bbox,
                                origin='upper left',
                                interpolation='nearest',
                                cmap=cmap,
                                norm=norm)

            # adjust the plot bounding box

            xmin, xmax = xmin - border * (xmax - xmin), xmax + border * (xmax -
                                                                         xmin)
            ymin, ymax = ymin - border * (ymax - ymin), ymax + border * (ymax -
                                                                         ymin)

        else:

            # adjust the plot bounding box

            xmin, xmax = xmin - border * (xmax - xmin), xmax + border * (xmax -
                                                                         xmin)
            ymin, ymax = ymin - border * (ymax - ymin), ymax + border * (ymax -
                                                                         ymin)

            # pixel width in latitude

            pw = (xmax - xmin) / pixels

            # calculate the image height in pixels

            ny = int(numpy.ceil((ymax - ymin) / (xmax - xmin) * pixels))

            # note the height of pixels = width of pixels
            # and image width in pixels is "pixels"

            xs = numpy.array([xmin + (i + 0.5) * pw for i in range(pixels)])
            ys = numpy.array([ymin + (i + 0.5) * pw for i in range(ny)])

            # set up an array of values for the image

            zs = numpy.zeros((ny, pixels))

            for i in range(len(ys)):
                ps = [(x, ys[i]) for x in xs]
                zs[i, :] = numpy.array(get_raster(landuse, ps, quiet=True))

            zs = zs.astype(int)

            tot = zs.size

            for v in numpy.unique(zs):
                group = self.groups[v]
                i = self.order.index(group)
                zs[numpy.where(zs == v)] = i

            # plot the grid

            im = subplot.imshow(
                zs,
                interpolation='nearest',
                origin='upper left',
                extent=[xmin, xmax, ymin, ymax],
                norm=norm,
                cmap=cmap,
            )

            # add patch for the shape boundary

            for shape in s.shapes():
                points = numpy.array(shape.points)
                subplot.add_patch(
                    self.make_patch(points, (1, 0, 0, 0), width=0.5))

        # add the legend using a dummy box to make patches for the legend

        dummybox = [[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]
        handles, labels = [], []
        for group, color in zip(self.order[1:], color_table[1:]):
            p = self.make_patch(dummybox, facecolor=color, width=0)
            handles.append(subplot.add_patch(p))
            labels.append(group)

        leg = subplot.legend(handles,
                             labels,
                             bbox_to_anchor=(1.0, 0.5),
                             loc='center left',
                             title='Land Use Categories')
        legtext = leg.get_texts()
        pyplot.setp(legtext, fontsize=10)
        subplot.set_position([0.125, 0.1, 0.6, 0.8])

        # add the labels and set the limits

        subplot.set_xlabel('Longitude, Decimal Degrees', size=13)
        subplot.set_ylabel('Latitude, Decimal Degrees', size=13)

        subplot.set_xlim([xmin, xmax])
        subplot.set_ylim([ymin, ymax])

        subplot.xaxis.set_major_locator(ticker.MaxNLocator(8))
        subplot.yaxis.set_major_locator(ticker.MaxNLocator(8))

        subplot.xaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f'))
        subplot.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f'))

        # show it

        if output is not None: pyplot.savefig(output)
        if show: pyplot.show()

        pyplot.clf()
        pyplot.close()
Ejemplo n.º 27
0
    def clabel(self, *args, **kwargs):
        """
        call signature::

          clabel(cs, **kwargs)

        adds labels to line contours in *cs*, where *cs* is a
        :class:`~matplotlib.contour.ContourSet` object returned by
        contour.

        ::

          clabel(cs, v, **kwargs)

        only labels contours listed in *v*.

        Optional keyword arguments:

          *fontsize*:
            See http://matplotlib.sf.net/fonts.html

          *colors*:
            - if *None*, the color of each label matches the color of
              the corresponding contour

            - if one string color, e.g. *colors* = 'r' or *colors* =
              'red', all labels will be plotted in this color

            - if a tuple of matplotlib color args (string, float, rgb, etc),
              different labels will be plotted in different colors in the order
              specified

          *inline*:
            controls whether the underlying contour is removed or
            not. Default is *True*.

          *inline_spacing*:
            space in pixels to leave on each side of label when
            placing inline.  Defaults to 5.  This spacing will be
            exact for labels at locations where the contour is
            straight, less so for labels on curved contours.

          *fmt*:
            a format string for the label. Default is '%1.3f'
            Alternatively, this can be a dictionary matching contour
            levels with arbitrary strings to use for each contour level
            (i.e., fmt[level]=string)

          *manual*:
            if *True*, contour labels will be placed manually using
            mouse clicks.  Click the first button near a contour to
            add a label, click the second button (or potentially both
            mouse buttons at once) to finish adding labels.  The third
            button can be used to remove the last label added, but
            only if labels are not inline.  Alternatively, the keyboard
            can be used to select label locations (enter to end label
            placement, delete or backspace act like the third mouse button,
            and any other key will select a label location).

          *rightside_up*:
            if *True* (default), label rotations will always be plus
            or minus 90 degrees from level.

        .. plot:: mpl_examples/pylab_examples/contour_demo.py
        """

        """
        NOTES on how this all works:

        clabel basically takes the input arguments and uses them to
        add a list of "label specific" attributes to the ContourSet
        object.  These attributes are all of the form label* and names
        should be fairly self explanatory.

        Once these attributes are set, clabel passes control to the
        labels method (case of automatic label placement) or
        BlockingContourLabeler (case of manual label placement).
        """

        fontsize = kwargs.get('fontsize', None)
        inline = kwargs.get('inline', 1)
        inline_spacing = kwargs.get('inline_spacing', 5)
        self.labelFmt = kwargs.get('fmt', '%1.3f')
        _colors = kwargs.get('colors', None)

        # Detect if manual selection is desired and remove from argument list
        self.labelManual=kwargs.get('manual',False)

        self.rightside_up = kwargs.get('rightside_up', True)

        if len(args) == 0:
            levels = self.levels
            indices = range(len(self.levels))
        elif len(args) == 1:
            levlabs = list(args[0])
            indices, levels = [], []
            for i, lev in enumerate(self.levels):
                if lev in levlabs:
                    indices.append(i)
                    levels.append(lev)
            if len(levels) < len(levlabs):
                msg = "Specified levels " + str(levlabs)
                msg += "\n don't match available levels "
                msg += str(self.levels)
                raise ValueError(msg)
        else:
            raise TypeError("Illegal arguments to clabel, see help(clabel)")
        self.labelLevelList = levels
        self.labelIndiceList = indices

        self.labelFontProps = font_manager.FontProperties()
        if fontsize == None:
            font_size = int(self.labelFontProps.get_size_in_points())
        else:
            if type(fontsize) not in [int, float, str]:
                raise TypeError("Font size must be an integer number.")
                # Can't it be floating point, as indicated in line above?
            else:
                if type(fontsize) == str:
                    font_size = int(self.labelFontProps.get_size_in_points())
                else:
                    self.labelFontProps.set_size(fontsize)
                    font_size = fontsize
        self.labelFontSizeList = [font_size] * len(levels)

        if _colors == None:
            self.labelMappable = self
            self.labelCValueList = np.take(self.cvalues, self.labelIndiceList)
        else:
            cmap = colors.ListedColormap(_colors, N=len(self.labelLevelList))
            self.labelCValueList = range(len(self.labelLevelList))
            self.labelMappable = cm.ScalarMappable(cmap = cmap,
                                                   norm = colors.NoNorm())

        #self.labelTexts = []   # Initialized in ContourSet.__init__
        #self.labelCValues = [] # same
        self.labelXYs = []

        if self.labelManual:
            print 'Select label locations manually using first mouse button.'
            print 'End manual selection with second mouse button.'
            if not inline:
                print 'Remove last label by clicking third mouse button.'

            blocking_contour_labeler = BlockingContourLabeler(self)
            blocking_contour_labeler(inline,inline_spacing)
        else:
            self.labels(inline,inline_spacing)

        # Hold on to some old attribute names.  These are depricated and will
        # be removed in the near future (sometime after 2008-08-01), but keeping
        # for now for backwards compatibility
        self.cl = self.labelTexts
        self.cl_xy = self.labelXYs
        self.cl_cvalues = self.labelCValues

        self.labelTextsList =  cbook.silent_list('text.Text', self.labelTexts)
        return self.labelTextsList
Ejemplo n.º 28
0
def LineCluster(BiasAmount, BiasChoice, MaxWalker, Probability,radius, needGif, LineColour, BackColour):

    
    #check if folder "images" exists, and if not - create it
    if not os.path.isdir("images"):
        os.mkdir("images")
    
    if needGif:

        import imageio

    
    #initialize variables that are dependent upon the radius
    # note - we add 2 to the parameters to get a thick border between the edges of the disk and square
    # x coordinate of a seed particle
    seedX = radius
    # y coordinate of a seed
    seedY = radius
    # size of the grid to account for field of wandering around
    squareSize = radius*2

    matrix=numpy.zeros((squareSize, squareSize))

    MissedWalkerCount = 0    

    for row in range (0,squareSize):
        for col in range (0,squareSize):
            #put a seed particle
            if row==seedY and col==seedX: 
                matrix[row][col]=1

                for count in range (-radius, seedX):
                    matrix[row][col-radius+count] = 1
                    
            #define field outside of circle
            elif numpy.sqrt((seedX-col)**2+(seedY-row)**2)>radius:
                matrix[row][col]=2
                
    cmap = colors.ListedColormap([BackColour,LineColour, BackColour])

    # Initialize the random walker counter
    randomWalkersCount = 0

    # Set the cluster to NOT be complete
    Complete = False

    # Start running random walkers
    addedCount=0 #keep track of number added

    # initialize array for the used interval for graphing
    usedInterval=[]

    while not Complete:
        # Release a walker
        randomWalkersCount += 1
        random.seed()

        # Generate a (Xstart, Ystart) for walker, need within radius
        location=randomAtRadius(radius, seedX, seedY)

        # Initialize variables, like Friend tag and near edge identifier
        foundFriend = False #not near other particle
        nearEdge = False #not near the edge of the field


        # Set an individual walker out, stop if found a 'friend', give up if it reached the edge of the board
        while not foundFriend and not nearEdge:
            # Run the checking/walking function
            locationNew,foundFriend, nearEdge, exitCircle = checkAround(BiasAmount, BiasChoice, location, squareSize, matrix)

            # Add to the cluster if near a friend
            if foundFriend:
                # current location, replace with 1 and stop
                matrix[location[1]][location[0]] = 1
                addedCount+=1

            # Otherwise, save the location
            else:
                location = locationNew
        
        intervalSavePic=range(2,400000,500)
        
        if randomWalkersCount in intervalSavePic:
            print("Added ", randomWalkersCount, " random walkers.", " Cluster: ", addedCount)
            
        if needGif:
            if randomWalkersCount in intervalSavePic:
                
                usedInterval.append(randomWalkersCount) #append to the used count
                label=str(randomWalkersCount)
                plt.title("DLA Cluster", fontsize=20)
                plt.matshow(matrix, interpolation='nearest',cmap=cmap)#plt.cm.Blues) #ocean, Paired
                plt.xlabel("$x$", fontsize=15)
                plt.ylabel("$y$", fontsize=15)
                plt.savefig("images/cluster{}.png".format(label), dpi=200)
                plt.close()
       
        if randomWalkersCount==MaxWalker:
            ctypes.windll.user32.MessageBoxW(0, "Max Walkers Reached ", addedCount, 1)
            ctypes.windll.user32.MessageBoxW(0, "Walkers that didn't stick: ", MissedWalkerCount, 1)
            ctypes.windll.user32.MessageBoxW(0, "Random walkers in the cluster: ", addedCount, 1)
            Complete = True

        # Once it finds a friend and leaves the previous loop, we must check if it
        # is also touching a circular wall. If so, we have a complete cluster
        if foundFriend and exitCircle:
            ctypes.windll.user32.MessageBoxW(0, "Random walkers in the cluster: ", addedCount, 0)
            ctypes.windll.user32.MessageBoxW(0, "Walkers that didn't stick: ", MissedWalkerCount, 0)
            Complete = True
    
    plt.title("DLA Cluster", fontsize=20)
    plt.matshow(matrix, interpolation='nearest',cmap=cmap)#plt.cm.Blues) #ocean, Paired
    plt.xlabel("$x$", fontsize=15)
    plt.ylabel("$y$", fontsize=15)
    plt.savefig("images/cluster.png", dpi=200)
    plt.close()

    print(usedInterval)

    if needGif:
        with imageio.get_writer('images/movie.gif', mode='I') as writer:
            for i in usedInterval:
                filename="images/cluster"+str(i)+".png"
                image = imageio.imread(filename)
                writer.append_data(image)
                os.remove(filename)
            image = imageio.imread("images/cluster.png")
            writer.append_data(image)

    return addedCount, matrix
Ejemplo n.º 29
0
    def _norm_kwargs(self, element, ranges, opts, vdim, prefix=''):
        """
        Returns valid color normalization kwargs
        to be passed to matplotlib plot function.
        """
        clim = opts.pop(prefix + 'clims', None)
        values = np.asarray(element.dimension_values(vdim))
        if clim is None:
            if not len(values):
                clim = (0, 0)
                categorical = False
            elif values.dtype.kind in 'uif':
                if vdim.name in ranges:
                    clim = ranges[vdim.name]['combined']
                else:
                    clim = element.range(vdim)
                if self.logz:
                    # Lower clim must be >0 when logz=True
                    # Choose the maximum between the lowest non-zero value
                    # and the overall range
                    if clim[0] == 0:
                        clim = (values[values != 0].min(), clim[1])
                if self.symmetric:
                    clim = -np.abs(clim).max(), np.abs(clim).max()
                categorical = False
            else:
                clim = (0, len(np.unique(values)) - 1)
                categorical = True
        else:
            categorical = values.dtype.kind not in 'uif'

        if self.logz:
            if self.symmetric:
                norm = mpl_colors.SymLogNorm(vmin=clim[0],
                                             vmax=clim[1],
                                             linthresh=clim[1] / np.e)
            else:
                norm = mpl_colors.LogNorm(vmin=clim[0], vmax=clim[1])
            opts[prefix + 'norm'] = norm
        opts[prefix + 'vmin'] = clim[0]
        opts[prefix + 'vmax'] = clim[1]

        cmap = opts.get(prefix + 'cmap', 'viridis')
        if values.dtype.kind not in 'OSUM':
            ncolors = None
            if isinstance(self.color_levels, int):
                ncolors = self.color_levels
            elif isinstance(self.color_levels, list):
                ncolors = len(self.color_levels) - 1
                if isinstance(cmap, list) and len(cmap) != ncolors:
                    raise ValueError(
                        'The number of colors in the colormap '
                        'must match the intervals defined in the '
                        'color_levels, expected %d colors found %d.' %
                        (ncolors, len(cmap)))
            try:
                el_min, el_max = np.nanmin(values), np.nanmax(values)
            except ValueError:
                el_min, el_max = -np.inf, np.inf
        else:
            ncolors = clim[-1] + 1
            el_min, el_max = -np.inf, np.inf
        vmin = -np.inf if opts[prefix + 'vmin'] is None else opts[prefix +
                                                                  'vmin']
        vmax = np.inf if opts[prefix + 'vmax'] is None else opts[prefix +
                                                                 'vmax']
        if el_min < vmin and el_max > vmax:
            self._cbar_extend = 'both'
        elif el_min < vmin:
            self._cbar_extend = 'min'
        elif el_max > vmax:
            self._cbar_extend = 'max'

        # Define special out-of-range colors on colormap
        colors = {}
        for k, val in self.clipping_colors.items():
            if val == 'transparent':
                colors[k] = {'color': 'w', 'alpha': 0}
            elif isinstance(val, tuple):
                colors[k] = {
                    'color': val[:3],
                    'alpha': val[3] if len(val) > 3 else 1
                }
            elif isinstance(val, util.basestring):
                color = val
                alpha = 1
                if color.startswith('#') and len(color) == 9:
                    alpha = int(color[-2:], 16) / 255.
                    color = color[:-2]
                colors[k] = {'color': color, 'alpha': alpha}

        if not isinstance(cmap, mpl_colors.Colormap):
            if isinstance(cmap, dict):
                factors = np.unique(values)
                palette = [
                    cmap.get(
                        f,
                        colors.get('NaN',
                                   {'color': self._default_nan})['color'])
                    for f in factors
                ]
            else:
                palette = process_cmap(cmap, ncolors, categorical=categorical)
                if isinstance(self.color_levels, list):
                    palette, (vmin, vmax) = color_intervals(palette,
                                                            self.color_levels,
                                                            clip=(vmin, vmax))
            cmap = mpl_colors.ListedColormap(palette)
        if 'max' in colors: cmap.set_over(**colors['max'])
        if 'min' in colors: cmap.set_under(**colors['min'])
        if 'NaN' in colors: cmap.set_bad(**colors['NaN'])
        opts[prefix + 'cmap'] = cmap
Ejemplo n.º 30
0
def test_BoundaryNorm():
    """
    GitHub issue #1258: interpolation was failing with numpy
    1.7 pre-release.
    """

    boundaries = [0, 1.1, 2.2]
    vals = [-1, 0, 1, 2, 2.2, 4]

    # Without interpolation
    expected = [-1, 0, 0, 1, 2, 2]
    ncolors = len(boundaries) - 1
    bn = mcolors.BoundaryNorm(boundaries, ncolors)
    assert_array_equal(bn(vals), expected)

    # ncolors != len(boundaries) - 1 triggers interpolation
    expected = [-1, 0, 0, 2, 3, 3]
    ncolors = len(boundaries)
    bn = mcolors.BoundaryNorm(boundaries, ncolors)
    assert_array_equal(bn(vals), expected)

    # with a single region and interpolation
    expected = [-1, 1, 1, 1, 3, 3]
    bn = mcolors.BoundaryNorm([0, 2.2], ncolors)
    assert_array_equal(bn(vals), expected)

    # more boundaries for a third color
    boundaries = [0, 1, 2, 3]
    vals = [-1, 0.1, 1.1, 2.2, 4]
    ncolors = 5
    expected = [-1, 0, 2, 4, 5]
    bn = mcolors.BoundaryNorm(boundaries, ncolors)
    assert_array_equal(bn(vals), expected)

    # a scalar as input should not trigger an error and should return a scalar
    boundaries = [0, 1, 2]
    vals = [-1, 0.1, 1.1, 2.2]
    bn = mcolors.BoundaryNorm(boundaries, 2)
    expected = [-1, 0, 1, 2]
    for v, ex in zip(vals, expected):
        ret = bn(v)
        assert isinstance(ret, int)
        assert_array_equal(ret, ex)
        assert_array_equal(bn([v]), ex)

    # same with interp
    bn = mcolors.BoundaryNorm(boundaries, 3)
    expected = [-1, 0, 2, 3]
    for v, ex in zip(vals, expected):
        ret = bn(v)
        assert isinstance(ret, int)
        assert_array_equal(ret, ex)
        assert_array_equal(bn([v]), ex)

    # Clipping
    bn = mcolors.BoundaryNorm(boundaries, 3, clip=True)
    expected = [0, 0, 2, 2]
    for v, ex in zip(vals, expected):
        ret = bn(v)
        assert isinstance(ret, int)
        assert_array_equal(ret, ex)
        assert_array_equal(bn([v]), ex)

    # Masked arrays
    boundaries = [0, 1.1, 2.2]
    vals = np.ma.masked_invalid([-1., np.NaN, 0, 1.4, 9])

    # Without interpolation
    ncolors = len(boundaries) - 1
    bn = mcolors.BoundaryNorm(boundaries, ncolors)
    expected = np.ma.masked_array([-1, -99, 0, 1, 2], mask=[0, 1, 0, 0, 0])
    assert_array_equal(bn(vals), expected)

    # With interpolation
    bn = mcolors.BoundaryNorm(boundaries, len(boundaries))
    expected = np.ma.masked_array([-1, -99, 0, 2, 3], mask=[0, 1, 0, 0, 0])
    assert_array_equal(bn(vals), expected)

    # Non-trivial masked arrays
    vals = np.ma.masked_invalid([np.Inf, np.NaN])
    assert np.all(bn(vals).mask)
    vals = np.ma.masked_invalid([np.Inf])
    assert np.all(bn(vals).mask)

    # Incompatible extend and clip
    with pytest.raises(ValueError, match="not compatible"):
        mcolors.BoundaryNorm(np.arange(4), 5, extend='both', clip=True)

    # Too small ncolors argument
    with pytest.raises(ValueError, match="ncolors must equal or exceed"):
        mcolors.BoundaryNorm(np.arange(4), 2)

    with pytest.raises(ValueError, match="ncolors must equal or exceed"):
        mcolors.BoundaryNorm(np.arange(4), 3, extend='min')

    with pytest.raises(ValueError, match="ncolors must equal or exceed"):
        mcolors.BoundaryNorm(np.arange(4), 4, extend='both')

    # Testing extend keyword, with interpolation (large cmap)
    bounds = [1, 2, 3]
    cmap = cm.get_cmap('viridis')
    mynorm = mcolors.BoundaryNorm(bounds, cmap.N, extend='both')
    refnorm = mcolors.BoundaryNorm([0] + bounds + [4], cmap.N)
    x = np.random.randn(100) * 10 + 2
    ref = refnorm(x)
    ref[ref == 0] = -1
    ref[ref == cmap.N - 1] = cmap.N
    assert_array_equal(mynorm(x), ref)

    # Without interpolation
    cmref = mcolors.ListedColormap(['blue', 'red'])
    cmref.set_over('black')
    cmref.set_under('white')
    cmshould = mcolors.ListedColormap(['white', 'blue', 'red', 'black'])

    assert mcolors.same_color(cmref.get_over(), 'black')
    assert mcolors.same_color(cmref.get_under(), 'white')

    refnorm = mcolors.BoundaryNorm(bounds, cmref.N)
    mynorm = mcolors.BoundaryNorm(bounds, cmshould.N, extend='both')
    assert mynorm.vmin == refnorm.vmin
    assert mynorm.vmax == refnorm.vmax

    assert mynorm(bounds[0] - 0.1) == -1  # under
    assert mynorm(bounds[0] + 0.1) == 1  # first bin -> second color
    assert mynorm(bounds[-1] - 0.1) == cmshould.N - 2  # next-to-last color
    assert mynorm(bounds[-1] + 0.1) == cmshould.N  # over

    x = [-1, 1.2, 2.3, 9.6]
    assert_array_equal(cmshould(mynorm(x)), cmshould([0, 1, 2, 3]))
    x = np.random.randn(100) * 10 + 2
    assert_array_equal(cmshould(mynorm(x)), cmref(refnorm(x)))

    # Just min
    cmref = mcolors.ListedColormap(['blue', 'red'])
    cmref.set_under('white')
    cmshould = mcolors.ListedColormap(['white', 'blue', 'red'])

    assert mcolors.same_color(cmref.get_under(), 'white')

    assert cmref.N == 2
    assert cmshould.N == 3
    refnorm = mcolors.BoundaryNorm(bounds, cmref.N)
    mynorm = mcolors.BoundaryNorm(bounds, cmshould.N, extend='min')
    assert mynorm.vmin == refnorm.vmin
    assert mynorm.vmax == refnorm.vmax
    x = [-1, 1.2, 2.3]
    assert_array_equal(cmshould(mynorm(x)), cmshould([0, 1, 2]))
    x = np.random.randn(100) * 10 + 2
    assert_array_equal(cmshould(mynorm(x)), cmref(refnorm(x)))

    # Just max
    cmref = mcolors.ListedColormap(['blue', 'red'])
    cmref.set_over('black')
    cmshould = mcolors.ListedColormap(['blue', 'red', 'black'])

    assert mcolors.same_color(cmref.get_over(), 'black')

    assert cmref.N == 2
    assert cmshould.N == 3
    refnorm = mcolors.BoundaryNorm(bounds, cmref.N)
    mynorm = mcolors.BoundaryNorm(bounds, cmshould.N, extend='max')
    assert mynorm.vmin == refnorm.vmin
    assert mynorm.vmax == refnorm.vmax
    x = [1.2, 2.3, 4]
    assert_array_equal(cmshould(mynorm(x)), cmshould([0, 1, 2]))
    x = np.random.randn(100) * 10 + 2
    assert_array_equal(cmshould(mynorm(x)), cmref(refnorm(x)))