Ejemplo n.º 1
0
 def load_setting(self, setting, prefix=''):
     if isseq(setting):
         setting_list = setting
     elif isinstance(setting, (str, unicode)):
         setting_file = open(setting)
         setting_list = []
         current_lines = []
         for l in setting_file:
             l = l.rstrip()
             if not l:
                 continue
             current_lines.append(l)
             if not l.endswith(','):
                 joined = '\n'.join(current_lines)
                 setting_list.append(joined)
                 current_lines = []
         if current_lines:
             setting_list.append('\n'.join(current_lines))
     for setting_item in setting_list:
         if setting_item.startswith(prefix):
             try:
                 setting_item = setting_item.lstrip(prefix)
                 cmd = 'self.' + setting_item
                 exec cmd
             except Exception as e:
                 pass
Ejemplo n.º 2
0
 def load_setting(self, setting, prefix=""):
     if isseq(setting):
         setting_list = setting
     elif isinstance(setting, (str, unicode)):
         setting_file = open(setting)
         setting_list = []
         current_lines = []
         for l in setting_file:
             l = l.rstrip()
             if not l:
                 continue
             current_lines.append(l)
             if not l.endswith(","):
                 joined = "\n".join(current_lines)
                 setting_list.append(joined)
                 current_lines = []
         if current_lines:
             setting_list.append("\n".join(current_lines))
     for setting_item in setting_list:
         if setting_item.startswith(prefix):
             try:
                 setting_item = setting_item.lstrip(prefix)
                 cmd = "self." + setting_item
                 exec cmd
             except Exception as e:
                 pass
Ejemplo n.º 3
0
def datetime2yearseason(dts, seasonformat='name', sep='_', DJF='JF_year'):
    """Converts datetime to "Year_Season" strs
    Parameters:
        dts: datetime / datetime seq;
        seasonformat: '0123', '1234', 'name' or ANY seq with at least 4 elements;
        sep: result str is "Year" + sep + "Season";
        DJF: 
            'JF_year' (default): December belongs to the next year (same as Jan/Feb).
            'D_year': Jan/Feb belongs to the prev year (same as Dec).
            '': Dec/Jan/Feb belongs to its own year.
    Returns:
        "Year_Season" str/seq.
"""
    dts = T(dts)
    if isseq(dts):
        scalar_res = False
    else:
        scalar_res = True
        dts = np.array([dts])

    seasons = datetime2season(dts, seasonformat)
    years = np.array([dt.year for dt in dts])
    months = np.array([dt.month for dt in dts])
    if DJF == 'JF_year':
        years[months == 12] += 1
    elif DJF == 'D_year':
        years[months == 1] -= 1
        years[months == 2] -= 1
    res = np.array(['%s%s%s' % (year, sep, season) for year, season in zip(years, seasons)])
    if scalar_res:
        res = res[0]
    return res
Ejemplo n.º 4
0
def datetime2yearseason(dts, seasonformat='name', sep='_', DJF='JF_year'):
    """Converts datetime to "Year_Season" strs
    Parameters:
        dts: datetime / datetime seq;
        seasonformat: '0123', '1234', 'name' or ANY seq with at least 4 elements;
        sep: result str is "Year" + sep + "Season";
        DJF: 
            'JF_year' (default): December belongs to the next year (same as Jan/Feb).
            'D_year': Jan/Feb belongs to the prev year (same as Dec).
            '': Dec/Jan/Feb belongs to its own year.
    Returns:
        "Year_Season" str/seq.
"""
    dts = T(dts)
    if isseq(dts):
        scalar_res = False
    else:
        scalar_res = True
        dts = np.array([dts])

    seasons = datetime2season(dts, seasonformat)
    years = np.array([dt.year for dt in dts])
    months = np.array([dt.month for dt in dts])
    if DJF == 'JF_year':
        years[months == 12] += 1
    elif DJF == 'D_year':
        years[months == 1] -= 1
        years[months == 2] -= 1
    res = np.array([
        '%s%s%s' % (year, sep, season) for year, season in zip(years, seasons)
    ])
    if scalar_res:
        res = res[0]
    return res
Ejemplo n.º 5
0
def format_ticks(ax=None, fmt=None, axis='x', **kwargs):
    """Format ticks.
    ax: ax, default gca().
    fmt: date format like "%Y%m%d", or format string like "%.2f", or a func, or sequence of strs, or sequence of (position, str), default None.
    axis: 'x' | 'y' | 'z', default 'x'.
    kwargs: anything that can be applied to ticklabels, e.g., fontsize, fontweight, etc.
    """
    if not ax:
        ax = plt.gca()

    if axis == 'x':
        theaxis = ax.xaxis
    elif axis == 'y':
        theaxis = ax.yaxis
    elif theaxis == 'z':
        theaxis = ax.zaxis
    else:
        theaxis = Null

    if fmt:
        datefmt_pattern = r'%H|%I|%M|%S|%Y|%y|%m|%w|%W|%a|%A|%b|%B|%p|%z|%Z|%j|%U|%c|%x|%X'
        str_pattern = r'%'
        if callable(fmt):
            fmt = FuncFormatter(fmt)
        elif isinstance(fmt, (str, unicode, np.string_)):
            if re.search(datefmt_pattern, fmt):
                fmter = DateFormatter(fmt)
            elif re.search(str_pattern, fmt):
                fmter = FormatStrFormatter(fmt)
            else:
                fmter = Null
        elif isseq(fmt):
            if np.ndim(fmt) == 1:
                fmter = FixedFormatter(fmt)
            elif np.ndim(fmt) == 2 and np.shape(fmt)[1] == 2:
                fmt = np.array(fmt)
                pos = fmt[:, 0]
                fmter = FixedFormatter(fmt[:, 1])
                theaxis.set_ticks(pos)
            else:
                fmter = Null
        else:
            fmt = Null

        if fmter:
            theaxis.set_major_formatter(fmter)

    ticklabels = theaxis.get_ticklabels()
    for key, value in kwargs.iteritems():
        little_kwargs = {key: value}
        try:
            plt.setp(ticklabels, **little_kwargs)
        except Exception as e:
            warnings.warn(e)
Ejemplo n.º 6
0
def format_ticks(ax=None, fmt=None, axis='x', **kwargs):
    """Format ticks.
    ax: ax, default gca().
    fmt: date format like "%Y%m%d", or format string like "%.2f", or a func, or sequence of strs, or sequence of (position, str), default None.
    axis: 'x' | 'y' | 'z', default 'x'.
    kwargs: anything that can be applied to ticklabels, e.g., fontsize, fontweight, etc.
    """
    if not ax:
        ax = plt.gca()

    if axis == 'x':
        theaxis = ax.xaxis
    elif axis == 'y':
        theaxis = ax.yaxis
    elif theaxis == 'z':
        theaxis = ax.zaxis
    else:
        theaxis = Null

    if fmt:
        datefmt_pattern = r'%H|%I|%M|%S|%Y|%y|%m|%w|%W|%a|%A|%b|%B|%p|%z|%Z|%j|%U|%c|%x|%X'
        str_pattern = r'%'
        if callable(fmt):
            fmt = FuncFormatter(fmt)
        elif isinstance(fmt, (str, unicode, np.string_)):
            if re.search(datefmt_pattern, fmt):
                fmter = DateFormatter(fmt)
            elif re.search(str_pattern, fmt):
                fmter = FormatStrFormatter(fmt)
            else:
                fmter = Null
        elif isseq(fmt):
            if np.ndim(fmt) == 1:
                fmter = FixedFormatter(fmt)
            elif np.ndim(fmt) == 2 and np.shape(fmt)[1] == 2:
                fmt = np.array(fmt)
                pos = fmt[:, 0]
                fmter = FixedFormatter(fmt[:,1])
                theaxis.set_ticks(pos)
            else:
                fmter = Null
        else:
            fmt = Null

        if fmter:
            theaxis.set_major_formatter(fmter)

    ticklabels = theaxis.get_ticklabels()
    for key, value in kwargs.iteritems():
        little_kwargs = {key:value}
        try:
            plt.setp(ticklabels, **little_kwargs)
        except Exception as e:
            warnings.warn(e)
Ejemplo n.º 7
0
def datetime2season(dts, outformat='0123'):
    """Converts datetime to season number or names.
    Parameters:
        dts: datetime / datetime seq.
        outformat: '0123', '1234', 'name' or ANY seq with at least 4 elements
"""
    if isseq(dts):
        months = [dt.month for dt in T(dts)]
    else:
        months = T(dts).month
    return month2season(months, outformat=outformat)
Ejemplo n.º 8
0
def datetime2season(dts, outformat='0123'):
    """Converts datetime to season number or names.
    Parameters:
        dts: datetime / datetime seq.
        outformat: '0123', '1234', 'name' or ANY seq with at least 4 elements
"""
    if isseq(dts):
        months = [dt.month for dt in T(dts)]
    else:
        months = T(dts).month
    return month2season(months, outformat=outformat)
Ejemplo n.º 9
0
def month2season(month, outformat='0123'):
    """Converts month number ( 1-12 ) to season number or names.
    Parameters:
        month : int or seq of int ( 1 - 12 )
        outformat: '0123', '1234', 'name' or ANY seq with at least 4 elements
"""
    if outformat == 'name':
        season_names = np.array(['Spring', 'Summer', 'Autumn', 'Winter'], dtype='O')
    elif outformat == '0123':
        season_names = np.array([0,1,2,3], dtype='i4')
    elif outformat == '1234':
        season_names = np.array([1,2,3,4], dtype='i4')
    else:
        if len(outformat) < 4:
            raise ValueError, 'outformat: "%s" length less than 4' % outformat
        season_names = np.array(list(outformat))

    if isseq(month):
        season_index = (np.array(month, dtype=int)+9) / 3 % 4
    else:
        season_index = (int(month) + 9) / 3 % 4
    return season_names[season_index]
Ejemplo n.º 10
0
def month2season(month, outformat='0123'):
    """Converts month number ( 1-12 ) to season number or names.
    Parameters:
        month : int or seq of int ( 1 - 12 )
        outformat: '0123', '1234', 'name' or ANY seq with at least 4 elements
"""
    if outformat == 'name':
        season_names = np.array(['Spring', 'Summer', 'Autumn', 'Winter'],
                                dtype='O')
    elif outformat == '0123':
        season_names = np.array([0, 1, 2, 3], dtype='i4')
    elif outformat == '1234':
        season_names = np.array([1, 2, 3, 4], dtype='i4')
    else:
        if len(outformat) < 4:
            raise ValueError, 'outformat: "%s" length less than 4' % outformat
        season_names = np.array(list(outformat))

    if isseq(month):
        season_index = (np.array(month, dtype=int) + 9) / 3 % 4
    else:
        season_index = (int(month) + 9) / 3 % 4
    return season_names[season_index]