예제 #1
0
파일: mapbuilder.py 프로젝트: inogs/bit.sea
 def plot_maps_data(self, coastline_lon=None, coastline_lat=None, maptype=0, background_img=None):
     '''
     Generator of a large set of images.
     Arguments : 
       * coastline_lon *  1-D array 
       * coastline_lat *  1-D array
       * map_type      *  integer, flag used to choose a plot method in mapplot module
             = 0, the default, to call mapplot.mapplot()
             = 1, to call mapplot.mapplot_onlycolor()
             = 2, to call mapplot.mapplot_nocolor()
     
     ''' 
     fig = None
     ax = None
     for f in self.__netcdffileslist:
         longdate , shortdate = get_date_string(f)
         for p in self.__plotlist:
             try:
                 de = DataExtractor(self._mask, filename=f, varname=p.varname)
             except NotFoundError as e:
                 msg="File: %s\n%s" % (f, e)
                 warn_user(msg)
                 continue
             for i,l in enumerate(p.layerlist):
                 outfile = "%s/ave.%s.%s.%s" % (self.__outputdir,shortdate, p.varname, l)
                 mapdata = MapBuilder.get_layer_average(de, l)
                 try:
                     clim = p.climlist[i]
                     if clim is None:
                         raise ValueError
                 except ValueError:
                     if p.clim is None:
                         raise ValueError("No clim defined for %s %s" % (p.varname, repr(l)))
                     else:
                         clim = p.clim
                 if maptype == 0:
                     fig, ax = mapplot({'varname':p.varname, 'clim':clim, 'layer':l, 'data':mapdata, 'date':longdate}, fig=fig, ax=ax, mask=self._mask, ncolors=24, coastline_lon=coastline_lon, coastline_lat=coastline_lat)
                     fig.savefig(outfile + ".png")
                 if maptype == 1:
                     dateobj=datetime.datetime.strptime(shortdate,'%Y%m%d')
                     mapdict={'varname':p.varname, 'longname':p.longvarname(), 'clim':clim, 'layer':l, 'data':mapdata, 'date':dateobj,'units':p.units()}
                     fig, ax = mapplot_medeaf(mapdict, fig=fig, ax=ax, mask=self._mask, ncolors=24,background_img=background_img)
                     fig.savefig(outfile + ".png",dpi=86)
                     pl.close(fig)
                 if maptype == 2:
                     fig, ax = mapplot_nocolor({'varname':p.varname, 'clim':clim, 'layer':l, 'data':mapdata, 'date':longdate}, fig=fig, ax=ax, mask=self._mask, ncolors=24, coastline_lon=coastline_lon, coastline_lat=coastline_lat)
                     fig.canvas.print_figure(outfile + ".svg")
                     return
                 
             fig = None
             ax = None
예제 #2
0
def extract_from_runs(run, varname, subbasin, coast=CoastEnum.open_sea, stat=StatEnum.mean):
    """
    Extracts a time series based on a list of file paths.

    Args:
        - *run*: name of the run
        - *varname*: name of the variable to extract
        - *subbasin*: an element from SubBasinEnum.
        - *coast* (optional): an element from CoastEnum (default:
          CoastEnum.open_sea).
        - *stat* (optional): an element from StatEnum (default: StatEnum.mean).

    Returns: statistics and dates
    """

    MYLIST = list()
    Data_dict = {}
    for dep in DEPTH_LIST:
        Data_dict[dep] = list()

    run_path = args.indir + run + args.pathtxt
    print(run_path)
    file_list = sorted(glob(run_path + "/*nc"))
    label_list = list()
    for f in file_list:
        # Get date string from file name
        _, ds = get_date_string(path.basename(f))
        # Create datetime object from date string
        dt = datetime.strptime(ds, "%Y%m%d")
        # Append the date to label_list
        label_list.append(dt)
        # Open it with netCDF4
        dset = netCDF4.Dataset(f)
        # Append the variable value to data_list
        for idep, dep in enumerate(DEPTH_LIST):
            depth_index = TheMask.getDepthIndex(dep)
            value = dset[varname][subbasin, coast, depth_index, stat].copy()
            Data_dict[dep].append(value)

        # Close the file
        dset.close()
    print(value)

    LIST = [i for i in range(len(DEPTH_LIST) + 1)]
    LIST[0] = label_list
    for idep, dep in enumerate(DEPTH_LIST):
        LIST[idep + 1] = Data_dict[dep]

    return LIST
예제 #3
0
파일: plot.py 프로젝트: inogs/bit.sea
def plot_from_files(file_list, varname, subbasin, coast=CoastEnum.open_sea, stat=StatEnum.mean, depth_index=0, fig=None, ax=None):
    """
    Plots a time series based on a list of file paths.

    Args:
        - *file_list*: a list of path strings for the files in the time series.
        - *varname*: name of the variable to plot.
        - *subbasin*: an element from SubBasinEnum.
        - *coast* (optional): an element from CoastEnum (default:
          CoastEnum.open_sea).
        - *stat* (optional): an element from StatEnum (default: StatEnum.mean).
        - *depth_index* (optional): the depth index z (default: 0).
        - *fig* (optional): an instance of matplotlib figure. A new one will be
          created if it is set to None (default: None).
        - *ax* (optional): an instance of matplotlib axes. A new one will be
          created if it is set to None (default: None).

    Returns: a matplotlib figure and axes object.
    """
    if (fig is None) or (ax is None):
        fig , ax = plt.subplots()
    plot_list = list()
    label_list = list()
    #For each file in file_list
    for f in file_list:
        #Get date string from file name
        _, ds = get_date_string(path.basename(f))
        #Create datetime object from date string
        dt = datetime.strptime(ds,'%Y%m%d')
        #Append the date to label_list
        label_list.append(dt)
        #Open it with netCDF4
        dset = netCDF4.Dataset(f)
        #Append the variable value to plot_list
        plot_list.append(dset[varname][subbasin, coast, depth_index, stat])
        #Close the file
        dset.close()
    #Plot data
    ax.plot(label_list, plot_list)
    return fig,ax
예제 #4
0
파일: plot.py 프로젝트: inogs/bit.sea
def plot_Hovmoeller_diagram(file_list, varname, subbasin, coast=CoastEnum.open_sea, stat=StatEnum.mean, depths=72, fig=None, ax=None):
    """
    Plots a time series Hovmoeller diagram.

    Args:
        - *file_list*: a list of path strings for the files in the time series.
        - *varname*: name of the variable to plot.
        - *subbasin*: an element from SubBasinEnum.
        - *coast* (optional): an element from CoastEnum (default:
          CoastEnum.open_sea).
        - *stat* (optional): an element from StatEnum (default: StatEnum.mean).
        - *depths* (optional): integer OR list OR Numpy array of depth values
          (default: 72).  If you pass a single integer it will be interpreted
          as the lenght of the depths array if you pass a list or Numpy array
          it will be used to set the labels and its lenght will be assumed as
          the lenght of the depths array.
        - *fig* (optional): an instance of matplotlib figure. A new one will be
          created if it is set to None (default: None).
        - *ax* (optional): an instance of matplotlib axes. A new one will be
          created if it is set to None (default: None).

    Returns: a matplotlib Figure, Axes and QuadMesh object tuple.
    """
    if (fig is None) or (ax is None):
        fig , ax = plt.subplots()
    dlabels = None
    if isinstance(depths, (int, long)):
        pass
    elif isinstance(depths, (list, tuple)):
        dlabels = np.array(depths)
        depths = len(dlabels)
    elif isinstance(depths, np.ndarray):
        #If 1D array
        if len(depths.shape) == 1:
            dlabels = np.copy(depths)
            depths = dlabels.shape[0]
        else:
            raise ValueError("Invalid depths argument")
    else:
        raise ValueError("Invalid depths argument")
    plotmat = np.zeros([depths, len(file_list)])
    xlabel_list = list()
    #For each file
    for i,f in enumerate(file_list):
        #Get date string from file name
        _, ds = get_date_string(path.basename(f))
        #Create datetime object from date string
        dt = datetime.strptime(ds,'%Y%m%d')
        #Append the date to xlabel_list
        xlabel_list.append(dt)
        #Open it with netCDF4
        dset = netCDF4.Dataset(f)
        #Copy the data in the plot matrix
        plotmat[:,i] = dset[varname][subbasin, coast, 0:depths, stat]
        #Close the file
        dset.close()
    #Create the meshgrid
    xlabel_list = mpldates.date2num(xlabel_list)
    xs,ys = np.meshgrid(xlabel_list, dlabels)
    #Plot the matrix
    quadmesh = ax.pcolormesh(xs, ys, plotmat,shading='flat')# default is 'flat'
    #Inform matplotlib that the x axis is made by dates
    ax.xaxis_date()
    return fig, ax, quadmesh